#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void swap(char *s1,char *s2)
{
char temp;
temp=*s1;
*s1=*s2;
*s2=temp;
}
void re_S(char *S)
{
int i;
for(i=0;i<256;i++)
S[i]=i;
}
void re_T(char *T,char *key)
{
int i;
int keylen;
keylen=strlen(key);
for(i=0;i<256;i++)
T[i]=key[i%keylen];
}
void re_Sbox(char *S,char *T)
{
int i;
int j=0;
for(i=0;i<256;i++)
{
j=(j+S[i]+T[i])%256;
swap(&S[i],&S[j]);
}
}
void RC4(FILE *readfile,FILE *writefile,char *key)
{
char S[256]={0};
char readbuf[1];
int i,j,t;
char T[256]={0};
re_S(S);
re_T(T,key);
re_Sbox(S,T);
i=j=0;
while(fread(readbuf,1,1,readfile))
{
i = (i + 1) % 256;
j = (j + S[i]) % 256;
swap(&S[i],&S[j]);
t = (S[i] + (S[j] % 256)) % 256;
readbuf[0]=readbuf[0]^S[t];
fwrite(readbuf,1,1,writefile);
memset(readbuf,0,1);
}
printf("加密|解密成功!!!\n");
}
void main()
{
char key[]="311";
FILE *file1,*file2;
file1= fopen("1.txt","r");
file2 = fopen("2.txt","w");
RC4(file1,file2,key);
fclose(file1);
fclose(file2);
}
转载于:https://my.oschina.net/u/2276921/blog/529591