-
Notifications
You must be signed in to change notification settings - Fork 6
/
crypt.cpp
58 lines (47 loc) · 1.5 KB
/
crypt.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "stdafx.h"
#include <Wincrypt.h>
#include <sstream>
std::string GetHashText(const void * data, const size_t data_size, HashType hashType)
{
HCRYPTPROV hProv = NULL;
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
return "";
}
BOOL hash_ok = FALSE;
HCRYPTPROV hHash = NULL;
switch (hashType) {
case HashSha1: hash_ok = CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash); break;
case HashMd5: hash_ok = CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash); break;
case HashSha256: hash_ok = CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash); break;
}
if (!hash_ok) {
CryptReleaseContext(hProv, 0);
return "";
}
if (!CryptHashData(hHash, static_cast<const BYTE *>(data), data_size, 0)) {
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return "";
}
DWORD cbHashSize = 0, dwCount = sizeof(DWORD);
if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashSize, &dwCount, 0)) {
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return "";
}
std::vector<BYTE> buffer(cbHashSize);
if (!CryptGetHashParam(hHash, HP_HASHVAL, reinterpret_cast<BYTE*>(&buffer[0]), &cbHashSize, 0)) {
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return "";
}
std::ostringstream oss;
for (std::vector<BYTE>::const_iterator iter = buffer.begin(); iter != buffer.end(); ++iter) {
oss.fill('0');
oss.width(2);
oss << std::hex << static_cast<const int>(*iter);
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return oss.str();
}