对称加密算法
对称加密算法是一个比较传统的加密算法,其加解密都是基于一个密钥进行操作的。也称之为单钥加密算法。
int size;
BYTE* pByte;
}ENCRYPBYTE, *PENCRYPBYTE;
BOOL Encrypt(LPCTSTR strSrc,LPCTSTR strKey,PENCRYPBYTE pEncryptByte)
{
int ret;
HCRYPTPROV hCryptProv = NULL;
// Handle to the cryptography key.
HCRYPTKEY hKey = NULL;
// Handle to the hash object.
HCRYPTHASH hHash = NULL;
pEncryptByte->size = 0;
pEncryptByte->pByte = NULL;
if(!::CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
return FALSE ;
}
// Create an empty hash object.
if(!::CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) {
::CryptDestroyHash(hHash);
::CryptReleaseContext(hCryptProv,0);
return FALSE ;
}
if(!CryptHashData(hHash, (const BYTE*)strKey, _tcslen(strKey) * sizeof(TCHAR), 0))
{
::CryptDestroyHash(hHash);
::CryptReleaseContext(hCryptProv,0);
return FALSE;
}
// Create a session key based on the hash of the password.
if(!CryptDeriveKey(hCryptProv, CALG_RC2, hHash, CRYPT_EXPORTABLE, &hKey)){
::CryptDestroyHash(hHash);
::CryptReleaseContext(hCryptProv,0);
return FALSE;
}
BYTE* pData;
DWORD dwDataLength;
dwDataLength = (_tcslen(strSrc)+1)*sizeof(TCHAR);
ULONGLONG uCapacity = dwDataLength*2;
pData = (BYTE*)malloc(uCapacity);
if(pData == NULL){
::CryptDestroyHash(hHash);
::CryptReleaseContext(hCryptProv,0);
return FALSE;
}
memcpy(pData,strSrc,dwDataLength);
if(!::CryptEncrypt(hKey, NULL, TRUE, 0, pData, &dwDataLength, uCapacity)){
ret = GetLastError();
}
else{
ret = 0;
}
if(hHash)
::CryptDestroyHash(hHash);
if(hKey)
::CryptDestroyKey(hKey);
if(hCryptProv)
:ryptReleaseContext(hCryptProv, 0);
if(ret != 0){
free(pData);
return FALSE;
}
pEncryptByte->size = dwDataLength;
pEncryptByte->pByte = (BYTE*)pData;
return TRUE;
}
解密算法与此流程一样,就不写了