点击(此处)折叠或打开
- // GetMd5Hash()
- // #include <wincrypt.h>
- // 功能:用MD5计算Hash
- // 参数:CONST BYTE *pbData, // 输入数据
- // DWORD dwDataLen, // 输入数据字节长度
- // LPTSTR pszHash, // 输出16进制Hash字符串,长度为32+1
- // 返回:成功返回TRUE, 失败返回FALSE, err内容为GetLastError()的值
- BOOL GetMd5Hash(CONST BYTE *pbData, DWORD dwDataLen, CString &strHash, DWORD &err)
- {
- HCRYPTPROV hProv;
- if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
- {
- err = GetLastError();
- return FALSE;
- }
- HCRYPTHASH hHash;
- if(!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
- {
- err = GetLastError();
- CryptReleaseContext(hProv, 0);
- return FALSE;
- }
- if(!CryptHashData(hHash, pbData, dwDataLen, 0))
- {
- err = GetLastError();
- CryptDestroyHash(hHash);
- CryptReleaseContext(hProv, 0);
- return FALSE;
- }
- DWORD dwSize;
- DWORD dwLen = sizeof(dwSize);
- CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE*)(&dwSize), &dwLen, 0);
- BYTE* pHash = new BYTE[dwSize];
- dwLen = dwSize;
- CryptGetHashParam(hHash, HP_HASHVAL, pHash, &dwLen, 0);
- strHash = _T("");
- for(DWORD i=0; i<dwLen; i++)
- strHash.AppendFormat(_T("%02X"), pHash[i]);
- delete [] pHash;
- CryptDestroyHash(hHash);
- CryptReleaseContext(hProv, 0);
-
- return TRUE;
- }
- CString authCodeHash;
- DWORD getHashErr = 0;
- BOOL getHashResult = GetMd5Hash((BYTE *)mAuthCode.GetString(), mAuthCode.GetLength() * sizeof(TCHAR), authCodeHash, getHashErr);
注意字符串UNICODE编码和非UNICODE编码计算结果是不一样的。
参考:
VC 使用CryptoAPI计算Hash值:MD5, SHA