/**
* 来源:百度百科
* 运行环境:kaliLinux
*/
//程序开始
#include
#include
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 &#61; 0; i<256; i&#43;&#43;)
{
s[i] &#61; i;
k[i] &#61; key[i%Len];
}
for (i &#61; 0; i<256; i&#43;&#43;)
{
j &#61; (j &#43; s[i] &#43; k[i]) % 256;
tmp &#61; s[i];
s[i] &#61; s[j];//交换s[i]和s[j]
s[j] &#61; tmp;
}
}
/*加解密*/
void rc4_crypt(char*s, char*Data,long Len)
{
int i &#61; 0, j &#61; 0, t &#61; 0;
long k &#61; 0;
char tmp;
for (k &#61; 0; k
{
i &#61; (i &#43; 1) % 256;
j &#61; (j &#43; s[i]) % 256;
tmp &#61; s[i];
s[i] &#61; s[j];//交换s[x]和s[y]
s[j] &#61; tmp;
t &#61; (s[i] &#43; s[j]) % 256;
Data[k] ^&#61; s[t];
}
}
int main()
{
char s[256] &#61; { 0 }, s2[256] &#61; { 0 };//S-box
char key[256] &#61; { "justfortest" };
char pData[512] &#61; "这是一个用来加密的数据Data";
long len &#61; strlen(pData);
int i;
printf("pData&#61;%s\n", pData);
printf("key&#61;%s,length&#61;%d\n\n", key, strlen(key));
rc4_init(s, (char*)key, strlen(key));//已经完成了初始化
printf("完成对S[i]的初始化&#xff0c;如下&#xff1a;\n\n");
for (i &#61; 0; i<256; i&#43;&#43;)
{
printf("%02X", s[i]);
if (i && (i &#43; 1) % 16 &#61;&#61; 0)putchar(&#39;\n&#39;);
}
printf("\n\n");
for (i &#61; 0; i<256; i&#43;&#43;)//用s2[i]暂时保留经过初始化的s[i]&#xff0c;很重要的&#xff01;&#xff01;&#xff01;
{
s2[i] &#61; s[i];
}
printf("已经初始化&#xff0c;现在加密:\n\n");
rc4_crypt(s, (char*)pData, len);//加密
printf("pData&#61;%s\n\n", pData);
printf("已经加密&#xff0c;现在解密:\n\n");
//rc4_init(s,(char*)key,strlen(key));//初始化密钥
rc4_crypt(s2, (char*)pData, len);//解密
printf("pData&#61;%s\n\n", pData);
return 0;
}
//程序完