Cryptographic API(CryptoAPI、CAPI)を使ってMD5などのハッシュ値を求める
Cryptographic API(CryptoAPI、CAPI)
http://msdn.microsoft.com/en-us/library/aa380256.aspx
//---------------------------------------------------------------------------
UnicodeString __fastcall CalcHash(UnicodeString Str)
{
UnicodeString Result="";
HCRYPTPROV hCryptProv = NULL;
HCRYPTHASH hHash = NULL;
if (!::CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0)) {
if(!::CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
return Result;
}
}
try {
if (!::CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) return Result;
try {
AnsiString TmpStr=Str;
if (!::CryptHashData(hHash, (BYTE*)TmpStr.c_str(), (DWORD)TmpStr.Length(), 0)) return Result;
BYTE bData[1024];
memset(bData, 0, sizeof(bData));
CHAR Digits[] = "0123456789abcdef";
DWORD dwDataLen = 16;
if (!::CryptGetHashParam(hHash, HP_HASHVAL, bData, &dwDataLen, 0)) return Result;
Result="";
for (DWORD i = 0; i < dwDataLen; ++i) {
Result+=Digits[bData[i] >> 4];
Result+=Digits[bData[i] & 0xf];
}
} __finally {
if (hHash) ::CryptDestroyHash(hHash);
}
} __finally {
if (hCryptProv) ::CryptReleaseContext(hCryptProv,0);
}
return Result;
}
