rc4算法c语⾔实现编程,RC4C语⾔实现#include
#include
#include
#define MAX 1024
FILE *fp;
char ch[1024],ch1,ch2;
char filename1[20],filename2[20];
typedef unsigned long ULONG;
void rc4_init(unsigned char *s, unsigned char *key, unsigned long Len) //初始化函数
{
int i =0, j = 0;
char k[256] = {0};
unsigned 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])%6;
tmp = s[i];
s[i] = s[j]; //交换s[i]和s[j]
s[j] = tmp;
}
}
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
{
i=(i+1)%6;
j=(j+s[i])%6;
tmp = s[i];
s[i] = s[j]; //交换s[x]和s[y]
s[j] = tmp;
t=(s[i]+s[j])%6;
Data[k] ^= s[t];
}
}//加解密函数//
puttext(char filename[],char *ch)
{
if((fp=fopen(filename2,"w"))==NULL) printf("打开错误!\n\n");
fputs(ch,fp);
fclose(fp);
exit(0);
}
gettext(char filename[])
{
if((fp=fopen(filename,"rt"))==NULL) printf("打开错误!\n\n");
ch1=fgetc(fp);
while(ch1!=EOF)
ch1=fgetc(fp);
printf("\n\n");
fclose(fp);
fp=fopen(filename,"r");
fgets(ch,MAX,fp);
fclose(fp);
printf("\n");
printf("⽂件打开完成!\n\n");
}//⽂件输⼊输出函数//
int main()
{
unsigned char s[256] = {0},s2[256] = {0}; //S-box
char key[256];
int i,n;
ULONG len;
printf("请输⼊密钥:\n");
gets(key);
printf("请输⼊数字选择相应功能:\n");
printf("**************************\n");
printf("1------加密⽂件。\n");
printf("2------解密⽂件。\n");
printf("3------动态输⼊。\n");
printf("0------退出。\n");
printf("**************************\n");
scanf("%d",&n);
if(n==0)
{
printf("谢谢使⽤!再见!\n");
exit(0);
system("pause");
}
else if(n>3)
{
printf("输⼊错误!\n");
exit(0);
}
printf("key = %s, length = %d\n\n",key,strlen(key));
rc4_init(s,(unsigned char *)key,strlen(key)); //已经完成了初始化printf("完成对S[i]的初始化!");
printf("\n\n");
for(i=0;i<256;i++)//⽤s2[i]暂时保留经过初始化的s[i]
s2[i]=s[i];
printf("请输⼊需要加(解)密⽂件的路径及⽂件名:");
scanf("%s",filename1);
printf("\n\n");
switch(n)
{
case 1:
{
gettext(filename1);
len=strlen(ch);
printf("⽂件内容为%s;\n长度为%d。\n\n",ch,len);
printf("已经初始化,现在加密:\n\n");
rc4_crypt(s,(unsigned char *)ch,len);//加密
printf("加密后的内容为%0x\n\n",ch);
printf("请输⼊输出⽂件地址和名称:");
scanf("%s",filename2);
puttext(filename2,ch);
printf("⽂件输出完毕!");
}
case 2:
{
gettext(filename1);
len = strlen(ch);
printf("现在解密:\n");
rc4_init(s,(unsigned char *)key, strlen(key)); //初始化rc4_crypt(s2,(unsigned char *)ch,len);//解密
printf("解密后的内容为%s\n\n",ch);
printf("请输⼊输出⽂件地址和名称:");
scanf("%s",filename2);
puttext(filename2,ch);
printf("⽂件输出完毕!");
}
case 3:
{
printf("请输⼊加密内容:\n");
scanf("%s",ch);
len=strlen(ch);
printf("输⼊内容为%s;\n长度为%d。\n\n",ch,len);
printf("已经初始化,现在加密:\n\n");
rc4_crypt(s,(unsigned char *)ch,len);//加密
printf("加密后的内容为%0x\n\n",ch);
printf("现在解密:\n");
rc4_init(s,(unsigned char *)key, strlen(key)); //初始化rc4_crypt(s2,(unsigned char *)ch,len);//解密
printf("解密后的内容为%s\n\n",ch);编程语言下载
}
}
return 0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论