-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmd.cpp
More file actions
52 lines (44 loc) · 1.52 KB
/
md.cpp
File metadata and controls
52 lines (44 loc) · 1.52 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
#include <iostream>
#include <iomanip>
#include <openssl/evp.h>
#include <fstream>
#include <memory>
void computeFileMD5(const std::string& filePath) {
std::ifstream file(filePath, std::ios::binary);
if (!file) {
std::cerr << "Unable to open file: " << filePath << std::endl;
return;
}
EVP_MD_CTX* mdctx = EVP_MD_CTX_new();
if (!mdctx) {
std::cerr << "Failed to create digest context." << std::endl;
return;
}
if (EVP_DigestInit_ex(mdctx, EVP_md5(), nullptr) != 1) {
std::cerr << "Failed to initialize digest context with MD5." << std::endl;
EVP_MD_CTX_free(mdctx);
return;
}
const size_t bufferSize = 32 * 1024 * 1024;
std::unique_ptr<char[]> buffer(new char[bufferSize]);
while (file.read(buffer.get(), bufferSize) || file.gcount() > 0) {
if (EVP_DigestUpdate(mdctx, buffer.get(), file.gcount()) != 1) {
std::cerr << "Failed to update hash." << std::endl;
EVP_MD_CTX_free(mdctx);
return;
}
}
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int hashLength = 0;
if (EVP_DigestFinal_ex(mdctx, hash, &hashLength) != 1) {
std::cerr << "Failed to finalize hash." << std::endl;
EVP_MD_CTX_free(mdctx);
return;
}
EVP_MD_CTX_free(mdctx);
std::cout << "MD5 hash: ";
for (unsigned int i = 0; i < hashLength; i++) {
std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
}
std::cout << std::endl;
}