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
|
#include "stdafx.h" #include <Windows.h>
void rc4_init(unsigned char* S, unsigned char* K, unsigned long len) { char T[256] = { 0 }; unsigned char tmp = 0; for(int i=0; i<256; i++) { S[i] = i; T[i] = K[i%len]; } int j = 0; for(int i=0; i<256; i++) { j = (j + S[i] + T[i]) % 256; int middle = S[i]; S[i] = S[j]; S[j] = middle; } }
void rc4_crypt(unsigned char* S, unsigned char* Data, unsigned long len) { int i = 0, j = 0, t = 0; unsigned long k = 0; unsigned char tmp; for(; k<len; k++) { i = (i + 1) % 256; j = (j + S[i]) % 256; tmp = S[i]; S[i] = S[j]; S[j] = tmp; t = (S[i] + S[j]) % 256; Data[k] ^= S[t]; } } int main() { unsigned char s[256] = { 0 }, s2[256] = { 0 }; char key[256] = { "justfortest" }; char pData[512] = "这是一个用来加密的数据Data"; unsigned long len = strlen(pData); int i;
printf("pData=%s\n", pData); printf("key=%s,length=%d\n\n", key, strlen(key)); rc4_init(s, (unsigned char*)key, strlen(key)); printf("完成对S[i]的初始化,如下:\n\n"); for (i = 0; i < 256; i++) { printf("%02X", s[i]); if (i && (i + 1) % 16 == 0)putchar('\n'); } printf("\n\n"); for (i = 0; i < 256; i++) { s2[i] = s[i]; } printf("已经初始化,现在加密:\n\n"); rc4_crypt(s, (unsigned char*)pData, len); printf("pData=%s\n\n", pData); printf("已经加密,现在解密:\n\n"); rc4_crypt(s2, (unsigned char*)pData, len); printf("pData=%s\n\n", pData); getchar(); return 0; }
|