基于openssl MD5用法
#include <iostream>
#include <openssl/md5.h>
using namespace std;
int main(int argc, char* argv[])
{
cout << "Test Hash!" << endl;
unsigned char data[] = "測試md5數據";
unsigned char out[1024] = { 0 };
int len = sizeof(data);
MD5_CTX c;
MD5_Init(&c);
MD5_Update(&c, data, len);
MD5_Final(out, &c);
for (int i = 0; i < 16; i++)
cout << hex << (int)out[i];
cout << endl;
data[1] = 9;
MD5(data, len, out);
for (int i = 0; i < 16; i++)
cout << hex << (int)out[i];
cout << endl;
getchar();
return 0;
}
關鍵函數:
- MD5_Init: 初始化 MD5 哈希計算上下文。
- MD5_Update: 更新 MD5 哈希計算的中間結果。
- MD5_Final: 完成哈希計算,生成最終的哈希值。
- MD5: 直接計算數據的 MD5 哈希值。
注意:
1.sizeof(data) 返回的是指針的大小,不是數據字符串的實際長度。如果需要計算字符串的實際長度,應使用 strlen(data)。
2. data[1] = 9; 修改了原始數據 data 中的第二個字符,所以第二次的 MD5 哈希值會與第一次不同。
編譯命令:
確保 OpenSSL 已經正確安裝并鏈接到你的程序中,使用以下命令進行編譯:
g++ -o md5_example md5_example.cpp -lssl -lcrypto
計算和驗證文件以及字符串的 MD5 哈希,用于檢測文件完整性變化。
#include <iostream>
#include <openssl/md5.h>
#include <fstream>
#include <thread>
using namespace std;string GetFileListHash(string filepath)
{MD5_CTX c;MD5_Init(&c);ifstream ifs(filepath, ios::binary);if (!ifs) return "";unsigned char buf[1024];while (ifs.read(reinterpret_cast<char*>(buf), sizeof(buf))){MD5_Update(&c, buf, ifs.gcount());}ifs.close();unsigned char out[MD5_DIGEST_LENGTH];MD5_Final(out, &c);return string(reinterpret_cast<char*>(out), MD5_DIGEST_LENGTH);
}void PrintHex(const string& data)
{for (auto c : data)printf("%02X", (unsigned char)c);cout << endl;
}int main(int argc, char* argv[])
{cout << "Test Hash!" << endl;// 文件哈希測試string filepath = "../../src/test_hash/test_hash.cpp";auto hash1 = GetFileListHash(filepath);PrintHex(hash1);// 監控文件變化for (;;){auto hash = GetFileListHash(filepath);if (hash != hash1){ cout << "文件被修改" ;PrintHex(hash);} this_thread::sleep_for(1s);}return 0;
}