RC4加密成的密文出现乱码
#include<iomanip.h>#include<string.h>//后面要用到计数函数strlen()
#include<iostream.h>
typedef unsigned long ULONG;//定义无符号长整形类型ULONG
//参数1是一个256长度的char型数组,定义为: unsigned char sBox;
//参数2是密钥,其内容可以随便定义:char key;
//参数3是密钥的长度,Len = strlen(key);
void rc4_init(unsigned char *s, unsigned char *key, unsigned long Len) //初始化函数,对内部状态S进行随机化
{
int i =0, j = 0;
char k = {0};
unsigned char tmp = 0;
for(i=0;i<256;i++)
{
s=i;//确保S-box的每个元素都得到处理
k=key;//将S-box搅乱
}
for (i=0; i<256; i++)
{
j=(j+s+k)%256;//保证S-box的搅乱是随机的
tmp = s;//交换s和s
s = s;
s = 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)%256;
tmp = s;//交换s和s
s = s;
s = tmp;
t=(s+s)%256;
Data ^= s;//从进行随机化以后的s选取一个随机元素作为密钥流中的一个字节8位对一组明文Data的一个字节8位进行异或加解密
}
}
void main()
{
unsigned char s = {0},s2 = {0}; //S-box
char key = {"just for test"};
char pData = "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的初始化,如下:\n\n";
for (int i=0; i<256; i++)
{
cout<<setiosflags(ios::left)<<setw(3)<<(int)s<<" ";//宽度为3,左对齐,不足三位在右边补空格
}
cout<<endl<<endl;
for(i=0;i<256;i++)//用s2暂时保留经过初始化的s,很重要的,因为解密时要用到未进行改变的s
{
s2=s;
}
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
cout<<"pData="<<pData<<endl<<endl;
}
路过看看下!!!! 小刀鱼 发表于 2013-11-8 10:46 static/image/common/back.gif
路过看看下!!!!
坐等解决。。。加油,我看了好几遍,都没能解决
页:
[1]