阅读:1203回复:0
可以用在透明加密,RC4算法的实现#define xorswap(a,b) do{a^=b;b^=a;a^=b;}while(0) struct rc4 { unsigned char sbox[256]; unsigned char kbox[256]; int i, j; }; typedef struct rc4 rc4_t; rc4_t * rc4open(const void *key, int len) { rc4_t *rc4; if (!key) return (NULL); rc4 = (rc4_t *) malloc(sizeof(*rc4)); if (!rc4) return (NULL); for (rc4->i = 256; rc4->i--;) { rc4->sbox[rc4->i] = rc4->i; rc4->kbox[rc4->i] = ((unsigned char *) key)[rc4->i % len]; } rc4->j = 0; for (rc4->i = 0; rc4->i <= 255; rc4->i++) { rc4->j = (rc4->j + rc4->sbox[rc4->i] + rc4->kbox[rc4->i]) % 256; xorswap(rc4->sbox[rc4->i], rc4->sbox[rc4->j]); } return (rc4); } unsigned char rc4getc(rc4_t * rc4) { int t; if (!rc4) return (-1); rc4->i++; rc4->i %= 256; rc4->j += rc4->sbox[rc4->i]; rc4->j %= 256; xorswap(rc4->sbox[rc4->i], rc4->sbox[rc4->j]); t = (rc4->sbox[rc4->i] + rc4->sbox[rc4->j]) % 256; return (rc4->sbox[t]); } int rc4close(rc4_t * rc4) { if (!rc4) return (-1); free(rc4); return (0); } int rc4crypt(void *key, int keylen, void *buffer, int len) { int i; rc4_t *rc4; rc4 = rc4open(key, keylen); if (!rc4) return (-1); for (i = 0; i < len; i++) ((unsigned char *) buffer) ^= rc4getc(rc4); return (rc4close(rc4)); } int main(int argc, char* argv[]) { if(argc != 3) return -1; unsigned char buf[4096]; DWORD nByteRead = 0; DWORD nByteWrite = 0; if(argv[1][1] == 'e') { HANDLE hFileRead = CreateFile(argv[2], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFileRead == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); //char ERR[100]; //itoa(err, ERR, 10); ////printf(NULL, ERR, "Error", MB_ICONERROR); } HANDLE hFileWrite = CreateFile("newFile.txt", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFileWrite == INVALID_HANDLE_VALUE) { //MessageBox(NULL, "Could not create the file!", "Error", MB_ICONERROR); return -1; } while(ReadFile(hFileRead, buf, 4096, &nByteRead, NULL)) { if(nByteRead <= 0) break; rc4crypt("asdfsadf", 8, buf, nByteRead); WriteFile(hFileWrite, buf, nByteRead, &nByteWrite, NULL); } CloseHandle(hFileRead); CloseHandle(hFileWrite); } else if(argv[1][1] == 'd') { HANDLE hFileRead = CreateFile(argv[2], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFileRead == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); } HANDLE hFileWrite = CreateFile("newFile.txt", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFileWrite == INVALID_HANDLE_VALUE) { //MessageBox(NULL, "Could not create the file!", "Error", MB_ICONERROR); return -1; } while(ReadFile(hFileRead, buf, 4096, &nByteRead, NULL)) { if(nByteRead <= 0) break; rc4crypt("asdfsadf", 8, buf, nByteRead); WriteFile(hFileWrite, buf, nByteRead, &nByteWrite, NULL); } CloseHandle(hFileRead); CloseHandle(hFileWrite); } else return -1; return 0; } |
|
最新喜欢:ljmwor...
|