std::string WinMD5(const void * data, const size_t data_size)
{
HCRYPTPROV hProv = NULL;
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
return std::string();
}
HCRYPTPROV hHash = NULL;
BOOL hash_ok = CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
if (!hash_ok) {
CryptReleaseContext(hProv, 0);
return std::string();
}
if (!CryptHashData(hHash, static_cast<const BYTE *>(data), static_cast<DWORD>(data_size), 0)) {
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return std::string();
}
DWORD cbHashSize = 0, dwCount = sizeof(DWORD);
if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashSize, &dwCount, 0)) {
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return std::string();
}
std::vector<BYTE> buffer(cbHashSize);
if (!CryptGetHashParam(hHash, HP_HASHVAL, reinterpret_cast<BYTE*>(&buffer[0]), &cbHashSize, 0)) {
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return std::string();
}
std::ostringstream oss;
for (auto item: buffer) {
oss << static_cast<unsigned int>(item);
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return oss.str();
}
string ToBytes(const wstring& str) {
const char* d = reinterpret_cast<const char*>(&str[0]);
string result(d, d+str.size()*2);
return result;
}
int main() {
wstring data = L"876c0e09-70f7-4190-ab3a-254b6e5f461e";
cout << WinMD5(data.data(), data.size()* sizeof(wchar_t));
system("pause");
}