- 论坛徽章:
- 39
|
回复 47# OwnWaterloo - #include <stdio.h>
- #include <string.h>
- unsigned char* get_S(const unsigned char* key);
- {
- int i,j;
- unsigned char* S;
- S = malloc(256*sizeof(unsigned char));
- size_t len = strlen(key);
- for (i=0; i<256; ++i) S[i] = i;
- for (i=0, j=0; i<256; ++i)
- {
- unsigned k;
- j = (j+key[i%len]+S[i]) % 256;
- k = S[i]; S[i] = S[j]; S[j] = k;
- }
- return S;
- }
- int* rc4(const int* iBuf, int ilen, const unsigned char* S)
- {
- size_t len = strlen(key);
- set_S(len);
- int i,j,c;
- i = j = 0;
- int n;
- int* oBuf;
- malloc(oBuf, ilen*sizeof(int));
- for (n=0; n<iLen; ++n)
- {
- unsigned k, byte;
- c = iBuf[n];
- i = (i+1) % 256;
- j = (j+S[i]) % 256;
- k = S[i]; S[i] = S[j]; S[j] = k;
- byte = S[ (S[i]+S[j]) % 256 ];
- oBuf[n] = c ^ byte;
- }
- return oBuf;
- }
- void rc4_file(const char* iFilename, const char* oFilename, const unsigned char* key)
- {
- unsigned char* S;
- S = get_S(key);
- int iBuf[256];
- int bufLen;
- FILE* ifile = fopen(iFilename, "rb");
- FILE* ofile = fopen(oFilename, "wb");
- int off = -1;
- int* oBuf = NULL;
- do
- {
- off++;
- if(off > 256)
- {
- oBuf = rc4(iBuf, 256, S);
- fwrite(oBuf, sizeof(int), 256, ofile);
- free(oBuf);
- oBuf = NULL;
- off =0;
- }
-
- iBuf[off] = getc(ifile);
- }
- while (iBuf[off] != EOF);
- if(off > 0)
- {
- oBuf = rc4(iBuf, off, S);
- fwrite(oBuf, sizeof(int), off, ofile);
- free(oBuf);
- oBuf = NULL;
- }
- fclose(ofile);
- fclose(ifile);
- free(S);
- }
复制代码 如果这样会不会好些?
不是很明白你们要讨论的问题要旨。我只是按我的理解写,纯属凑热闹~~~ |
|