-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhashing.cpp
More file actions
59 lines (49 loc) · 1.56 KB
/
hashing.cpp
File metadata and controls
59 lines (49 loc) · 1.56 KB
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
59
#include "hashing.h"
#if WIN32
#include <Windows.h>
#include <bcrypt.h>
#endif
#include <sstream>
#include <iomanip>
#if WIN32
#pragma comment(lib, "bcrypt.lib")
#endif
namespace hashing {
#if WIN32
std::string md5(const std::string& input) {
BCRYPT_ALG_HANDLE alg = nullptr;
BCRYPT_HASH_HANDLE hash_handle = nullptr;
std::string result;
if(BCryptOpenAlgorithmProvider(&alg, BCRYPT_MD5_ALGORITHM, nullptr, 0) != 0) {
return result;
}
if(BCryptCreateHash(alg, &hash_handle, nullptr, 0, nullptr, 0, 0) != 0) {
BCryptCloseAlgorithmProvider(alg, 0);
return result;
}
if(BCryptHashData(hash_handle,
reinterpret_cast<PUCHAR>(const_cast<char*>(input.data())),
static_cast<ULONG>(input.size()), 0) != 0) {
BCryptDestroyHash(hash_handle);
BCryptCloseAlgorithmProvider(alg, 0);
return result;
}
UCHAR digest[16]; // MD5 is always 16 bytes
if(BCryptFinishHash(hash_handle, digest, sizeof(digest), 0) != 0) {
BCryptDestroyHash(hash_handle);
BCryptCloseAlgorithmProvider(alg, 0);
return result;
}
BCryptDestroyHash(hash_handle);
BCryptCloseAlgorithmProvider(alg, 0);
// convert to hex string
std::ostringstream oss;
oss << std::hex << std::setfill('0');
for(int i = 0; i < 16; ++i) {
oss << std::setw(2) << static_cast<int>(digest[i]);
}
result = oss.str();
return result;
}
#endif
}