c++ 基于openssl MD5用法 - 指南
基于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
;
}

浙公网安备 33010602011771号