Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
hash.h File Reference
#include <Windows.h>
#include <string>

Go to the source code of this file.

Functions

std::string GenerateMD5 (std::string filePath)
 Generate an MD5 hash of a file using the Windows Crypto API https://learn.microsoft.com/en-us/windows/win32/seccrypto/example-c-program&ndash;creating-an-md-5-hash-from-file-content.

Function Documentation

◆ GenerateMD5()

std::string GenerateMD5 ( std::string filePath)

Generate an MD5 hash of a file using the Windows Crypto API https://learn.microsoft.com/en-us/windows/win32/seccrypto/example-c-program&ndash;creating-an-md-5-hash-from-file-content.

Parameters
filePathThe path to the file to hash
Returns
The MD5 hash of the file

Definition at line 8 of file hash.cpp.

9{
10 if (filePath.empty())
11 {
12 return "";
13 }
14 WCHAR fileHash[33];
15 // Share write and delete as well, so files another process still has open for writing can be hashed
16 HANDLE hFile = CreateFileA(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
17 if (hFile == INVALID_HANDLE_VALUE) {
18 return "";
19 }
20
21 HCRYPTPROV hProv = 0;
22 HCRYPTHASH hHash = 0;
23 BYTE rgbHash[16];
24 DWORD cbHash = 0;
25 WCHAR rgbDigits[] = L"0123456789abcdef";
26
27 if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) ||
28 !CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) {
29 CloseHandle(hFile);
30 return "";
31 }
32
33 BYTE rgbFile[1024];
34 DWORD bytesRead = 0;
35 while (ReadFile(hFile, rgbFile, sizeof(rgbFile), &bytesRead, NULL)) {
36 if (bytesRead == 0) break;
37 if (!CryptHashData(hHash, rgbFile, bytesRead, 0)) {
38 CryptReleaseContext(hProv, 0);
39 CryptDestroyHash(hHash);
40 CloseHandle(hFile);
41 return "";
42 }
43 }
44
45 cbHash = 16;
46 if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)) {
47 for (DWORD i = 0; i < cbHash; i++) {
48 fileHash[i * 2] = rgbDigits[rgbHash[i] >> 4];
49 fileHash[i * 2 + 1] = rgbDigits[rgbHash[i] & 0xf];
50 }
51 fileHash[32] = L'\0';
52 }
53
54 int size_needed = WideCharToMultiByte(CP_UTF8, 0, fileHash, -1, NULL, 0, NULL, NULL);
55 std::string result(size_needed, 0);
56 WideCharToMultiByte(CP_UTF8, 0, fileHash, -1, &result[0], size_needed, NULL, NULL);
57 std::string test = std::string(result.begin(), result.end());
58 CryptReleaseContext(hProv, 0);
59 CryptDestroyHash(hHash);
60 CloseHandle(hFile);
61 return result;
62}