📄 rc4.c
字号:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <fcntl.h> /* Needed only for _O_RDWR definition */
#include <io.h>
typedef unsigned char UINT8;
typedef unsigned short UINT16;
typedef unsigned long UINT32;
UINT8 inputdata[256],outputdata[256];
UINT8 mainkey[16];
void P_RC4(UINT8 * pkey, UINT8 * pin, UINT8 * pout, long len);
void main(void)
{
UINT8 length,i;
UINT8 buff[256];
FILE *fin,*fout,*fp;
int finno,foutno,fno;//file handle
//unsigned int count = 0;//读取的字节数
long filelen=0,count = 0;
memset(inputdata,0,sizeof(inputdata));
memset(outputdata,0,sizeof(outputdata));
memset(mainkey,0,sizeof(mainkey));
//产生16字节的随机数
srand((UINT16)time(NULL));
for(i=0;i<16;i++) mainkey[i] = (UINT8)rand();
fin = fopen("tt.txt","rb");
fout = fopen("cipher.txt","wb");
fp = fopen("plain.txt","wb");
if( (fin == NULL) || (fout == NULL) || (fp == NULL) )
{
printf("file can't be opened\n");
exit(-1);
}
finno = _fileno(fin);//get the file handle
foutno = _fileno(fout);
fno = _fileno(fp);
filelen = _filelength(finno);//get the length of the file
memset(buff,0,sizeof(buff));
while( filelen>0 )
{
count = read(finno,buff,sizeof(buff));
printf("%s \n",buff);
P_RC4(mainkey,buff,outputdata,count); //加密
write(foutno,outputdata,count);
filelen = filelen - count;
memset(buff,0,sizeof(buff));
// printf("%s \n",outputdata);
}
fclose(fout);
fout = fopen("cipher.txt","rb");
//cipher
//rewind(fout);
foutno = _fileno(fout);
filelen = _filelength(foutno);//get the length of the file
count = 0;
memset(buff,0,sizeof(buff));
while( filelen>0 )
{
count = read(foutno,buff,sizeof(buff));
printf("%s \n",buff);
P_RC4(mainkey,buff,outputdata,count); //加密
write(fno,outputdata,count);
filelen = filelen - count;
memset(buff,0,sizeof(buff));
// printf("%s \n",outputdata);
}
fclose(fin);
fclose(fout);
fclose(fp);
}
void P_RC4(UINT8 * pkey, UINT8 * pin, UINT8 * pout, long len)
{
UINT8 S[256],K[256],temp;
UINT32 i,j,t,x;
j = 1;
for(i=0;i<256;i++)
{
S[i] = (UINT8)i;
if(j > 16) j = 1;
K[i] = pkey[j-1];
j++;
}
j = 0;
for(i=0;i<256;i++)
{
j = (j + S[i] + K[i]) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
}
i = j = 0;
for(x=0;x<len;x++)
{
i = (i+1) % 256;
j = (j + S[i]) % 256;
temp = S[i];
S[i] = S[j];
S[j] = temp;
t = (S[i] + (S[j] % 256)) % 256;
pout[x] = pin[x] ^ S[t];
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -