ARC4算法(加密)

#include "StdAfx.h" #include "Arc4EnDe.h" CArc4EnDe::CArc4EnDe(void) { } CArc4EnDe::~CArc4EnDe(void) { } void CArc4EnDe::fz_arc4init(fz_arc4 *arc4, BYTE *key, DWORD keylen) { unsigned int t, u; unsigned int keyindex; unsigned int stateindex; BYTE *state; unsigned int counter; state = arc4->state; arc4->x = 0; arc4->y = 0; for (counter = 0; counter < 256; counter++) { state[counter] = counter; } keyindex = 0; stateindex = 0; for (counter = 0; counter < 256; counter++) { t = state[counter]; stateindex = (stateindex + key[keyindex] + t) & 0xff; u = state[stateindex]; state[stateindex] = t; state[counter] = u; if (++keyindex >= keylen) { keyindex = 0; } } } BYTE CArc4EnDe::fz_arc4next(fz_arc4 *arc4) { unsigned int x; unsigned int y; unsigned int sx, sy; BYTE *state; state = arc4->state; x = (arc4->x + 1) & 0xff; sx = state[x]; y = (sx + arc4->y) & 0xff; sy = state[y]; arc4->x = x; arc4->y = y; state[y] = sx; state[x] = sy; return state[(sx + sy) & 0xff]; } void CArc4EnDe::fz_arc4encrypt(fz_arc4 *arc4, BYTE *dest, BYTE *src, DWORD len) { try { unsigned int i; for (i = 0; i < len; i++) { BYTE x; x = fz_arc4next(arc4); dest[i] = src[i] ^ x; } } catch(...) { } } void CArc4EnDe::fz_arc4decrypt(fz_arc4 *arc4, BYTE *dest, BYTE *src, DWORD len) { fz_arc4encrypt(arc4,dest,src,len); } BOOL CArc4EnDe::Arc4Encrypt(BYTE *dest, BYTE *src, DWORD len, BYTE* key, DWORD keylen) { try { fz_arc4 arc4; fz_arc4init(&arc4, key, keylen); fz_arc4encrypt(&arc4, dest, src, len); return TRUE; } catch(...) { } return FALSE; } BOOL CArc4EnDe::Arc4Decrypt(BYTE *dest, BYTE *src, DWORD len, BYTE* key, DWORD keylen) { return Arc4Encrypt(dest, src, len, key, keylen); } BOOL CArc4EnDe::Arc4EncryptFile(char* sFile, char* dFile, char* key) { BYTE *s = NULL; HANDLE hFileS = NULL; HANDLE hFileD = NULL; DWORD iReVal; DWORD iFileSize = 0; BOOL retV = FALSE; try { hFileS=::CreateFileA(sFile,GENERIC_READ,FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFileS!=NULL && hFileS != INVALID_HANDLE_VALUE) { iFileSize = ::GetFileSize(hFileS,&iReVal); s = new BYTE[iFileSize]; ::ReadFile(hFileS,s,iFileSize,&iReVal,NULL); } else goto ERROR_POS; hFileD=::CreateFileA(dFile,GENERIC_WRITE,FILE_SHARE_WRITE, NULL,CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFileD!=NULL && hFileD != INVALID_HANDLE_VALUE) { Arc4Encrypt(s, s, iFileSize, (BYTE*)key, (unsigned int)strlen(key)); ::WriteFile(hFileD,s,iFileSize,&iReVal,NULL); retV = TRUE; } else goto ERROR_POS; ERROR_POS: ; } catch(...) { } try{ if(s) delete []s; if(hFileS!=NULL && hFileS != INVALID_HANDLE_VALUE) ::CloseHandle(hFileS); if(hFileD!=NULL && hFileD != INVALID_HANDLE_VALUE) ::CloseHandle(hFileD); } catch(...) { } return retV; } BOOL CArc4EnDe::Arc4DecryptFile(char* sFile, char* dFile, char* key) { return Arc4EncryptFile(sFile, dFile, key); }

你可能感兴趣的:(加密,算法,File,null,include,byte)