/** * 來源:百度百科 * 運行環境:kaliLinux */ //程序開始 #include<stdio.h> #include<string.h> typedef unsigned longULONG; /*初始化函數*/ void rc4_init(char*s, char*key,long Len) { int i = 0, j = 0; char k[256] = { 0 }; char tmp = 0; for (i = 0; i<256; i++) { s[i] = i; k[i] = key[i%Len]; } for (i = 0; i<256; i++) { j = (j + s[i] + k[i]) % 256; tmp = s[i]; s[i] = s[j];//交換s[i]和s[j] s[j] = tmp; } } /*加解密*/ void rc4_crypt(char*s, char*Data,long Len) { int i = 0, j = 0, t = 0; long k = 0; char tmp; for (k = 0; k<Len; k++) { i = (i + 1) % 256; j = (j + s[i]) % 256; tmp = s[i]; s[i] = s[j];//交換s[x]和s[y] s[j] = tmp; t = (s[i] + s[j]) % 256; Data[k] ^= s[t]; } } int main() { char s[256] = { 0 }, s2[256] = { 0 };//S-box char key[256] = { "justfortest" }; char pData[512] = "這是一個用來加密的數據Data"; long len = strlen(pData); int i; printf("pData=%s\n", pData); printf("key=%s,length=%d\n\n", key, strlen(key)); rc4_init(s, (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],很重要的!!! { s2[i] = s[i]; } printf("已經初始化,如今加密:\n\n"); rc4_crypt(s, (char*)pData, len);//加密 printf("pData=%s\n\n", pData); printf("已經加密,如今解密:\n\n"); //rc4_init(s,(char*)key,strlen(key));//初始化密鑰 rc4_crypt(s2, (char*)pData, len);//解密 printf("pData=%s\n\n", pData); return 0; } //程序完