January 31, 2022

RC4-P.Z

先贴个我手打的源码

RC4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <string.h>

#define LEN 256

void Swap(unsigned char * a, unsigned char * b);
void Rc4_Init(unsigned char * s, unsigned char * key, int klen);
void Rc4_Crypt(unsigned char * s, unsigned char * p, int plen);

int main(void)
{
unsigned char s[LEN] = { 0 };
unsigned char ss[LEN] = { 0 };
unsigned char key[LEN] = { "20220127" };
unsigned char p[LEN * 2] = { "20211205" };
int i, j;

Rc4_Init(s, key, strlen(key));
for ( i = 0; i < LEN; i++ )
{
ss[i] = s[i];
// printf("%d %d ", s[i], ss[i]);
}

printf("Encrypt:");
Rc4_Crypt(s, p, strlen(p));
for ( i = 0; i < strlen(p); i++ )
printf("0x%X, ", p[i]);

puts("\n");

printf("Decrypt:");
Rc4_Crypt(ss, p, strlen(p));
for ( i = 0; i < strlen(p); i++ )
printf("0x%X, ", p[i]);

return 0;
}

void Swap(unsigned char * a, unsigned char * b)
{
// Swap((unsigned char *)&key[0], (unsigned char *)&key[1]);
// printf("%c %c", key[0], key[1]);
// printf("%d %d\n", *(__int8 *)&a, *(__int8 *)&b);
// Swap((__int8 *)&a, (__int8 *)&b); //以int8来读取这个地址的值 并不是解引用
// printf("%c %c\n", a, b);
// printf("%c %c\n", *a, *b);
*a ^= *b; //可以加个异或的混淆
*b ^= *a;
*a ^= *b;
}

void Rc4_Init(unsigned char * s, unsigned char * key, int klen)
{
unsigned char k[LEN] = { };
unsigned char t = 0;
int i, j;

for ( i = 0; i < LEN; i++ )
{
s[i] = i; //向量S
k[i] = key[i % klen]; //向量T 由key组成 用来打乱S
}
for ( i = 0, j = 0; i < LEN; i++ )
{
j = (j + s[i] + k[i]) % 256;
Swap(&s[i], &s[j]); //以int8来读取这个地址的值 并不是解引用
}
}

void Rc4_Crypt(unsigned char * s, unsigned char * p, int plen)
{
int i, j, k, t;

for ( i = 0, j = 0, k = 0; k < plen; k++ )
{
i = (i + 1) % 256;
j = (j + s[i]) % 256;
Swap(&s[i], &s[j]);
t = (s[i] + s[j]) % 256; //有点不理解RC4为什么要交换了再加
// printf("%d %d\n", p[k], s[t]);
p[k] ^= s[t];
}
}
DASCTF X SU
🍬
HFCTF2022
🍪

About this Post

This post is written by P.Z, licensed under CC BY-NC 4.0.