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("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) {
*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; k[i] = key[i % klen]; } for ( i = 0, j = 0; i < LEN; i++ ) { j = (j + s[i] + k[i]) % 256; Swap(&s[i], &s[j]); } }
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;
p[k] ^= s[t]; } }
|