由Windows API实现的一个MD5计算函数,在Windows平台上比其他开源的MD5库快20%以上。
std::string CalcMD5(LPCVOID lpData, DWORD dwSize, BOOL bUpper)
{
if(lpData == NULL || dwSize == 0)
return "";
std::string Str;
HCRYPTPROV hProv = NULL;
if(CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
HCRYPTHASH hHash = NULL;
if(CryptCreateHash(hProv, CALG_MD5, NULL, 0, &hHash))
{
if(CryptHashData(hHash, (PBYTE)lpData, dwSize, 0))
{
DWORD dwLength = 16;
PBYTE pMemory = (PBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength);
if(pMemory != NULL)
{
if(CryptGetHashParam(hHash, HP_HASHVAL, pMemory, &dwLength, 0))
{
CHAR Temp[4] = {};
for(DWORD i = 0; i < dwLength; ++i)
{
sprintf_s(Temp, _countof(Temp), bUpper ? "%02X" : "%02x", pMemory[i]);
Str.append(Temp);
}
}
HeapFree(GetProcessHeap(), 0, pMemory);
}
}
CryptDestroyHash(hHash);
}
CryptReleaseContext(hProv, 0);
}
return Str;
}