|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<iomanip.h>
#include<string.h>//后面要用到计数函数strlen()
#include<iostream.h>
typedef unsigned long ULONG;//定义无符号长整形类型ULONG
//参数1是一个256长度的char型数组,定义为: unsigned char sBox[256];
//参数2是密钥,其内容可以随便定义:char key[256];
//参数3是密钥的长度,Len = strlen(key);
void rc4_init(unsigned char *s, unsigned char *key, unsigned long Len) //初始化函数,对内部状态S进行随机化
{
int i =0, j = 0;
char k[256] = {0};
unsigned char tmp = 0;
for(i=0;i<256;i++)
{
s[i]=i;//确保S-box的每个元素都得到处理
k[i]=key[i%Len];//将S-box搅乱
}
for (i=0; i<256; i++)
{
j=(j+s[i]+k[i])%256;//保证S-box的搅乱是随机的
tmp = s[i]; //交换s[i]和s[j]
s[i] = s[j];
s[j] = tmp;
}
}
//参数1是上边rc4_init函数中,被搅乱的S-box;
//参数2是需要加密的数据data;
//参数3是data的长度.
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=0;k<Len;k++)
{
i=(i+1)%256;
j=(j+s[i])%256;
tmp = s[i];//交换s[x]和s[y]
s[i] = s[j];
s[j] = tmp;
t=(s[i]+s[j])%256;
Data[k] ^= s[t];//从进行随机化以后的s[t]选取一个随机元素作为密钥流中的一个字节8位对一组明文Data[k]的一个字节8位进行异或加解密
}
}
void main()
{
unsigned char s[256] = {0},s2[256] = {0}; //S-box
char key[256] = {"just for test"};
char pData[512] = "abcdefg";
ULONG len = strlen(pData);//定义无符号长整型变量len,赋值为pData字符串的个数
cout<<"pData="<<pData<<endl;
cout<<"key="<<key<<","<<"length="<<strlen(key)<<endl;
rc4_init(s,(unsigned char *)key,strlen(key)); //初始化密钥,调用初始化函数进行初始化,随机化内部状态s
cout<<endl<<"完成对S[i]的初始化,如下:\n\n";
for (int i=0; i<256; i++)
{
cout<<setiosflags(ios::left)<<setw(3)<<(int)s[i]<<" ";//宽度为3,左对齐,不足三位在右边补空格
}
cout<<endl<<endl;
for(i=0;i<256;i++)//用s2[i]暂时保留经过初始化的s[i],很重要的,因为解密时要用到未进行改变的s[i]
{
s2[i]=s[i];
}
cout<<"已经初始化,现在加密:\n\n";
rc4_crypt(s,(unsigned char *)pData,len);//加密
cout<<"pData="<<pData<<endl<<endl;
cout<<"已经加密,现在解密:\n\n";
rc4_init(s,(unsigned char *)key, strlen(key)); //初始化密钥
rc4_crypt(s2,(unsigned char *)pData,len);//解密,此处就要用到刚才保存下来的s2[i]
cout<<"pData="<<pData<<endl<<endl;
}
|
|