当前位置: 首页 > article >正文

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;
}
http://www.lryc.cn/news/2402988.html

相关文章:

  • Python打卡第46天
  • Unity优化篇之DrawCall
  • SpringCloud学习笔记-2
  • C++.OpenGL (9/64)复习(Review)
  • Spring Boot-面试题(52)
  • 从混乱到秩序:探索管理系统如何彻底改变工作流程
  • 最新研究揭示云端大语言模型防护机制的成效与缺陷
  • HTML5+CSS3+JS小实例:具有粘性重力的磨砂玻璃导航栏
  • CVAT标注服务
  • SpringBoot+Mybatisplus配置多数据源(超级简单!!!!)
  • Git Svn
  • Python爬虫伪装
  • Webpack的基本使用 - babel
  • LLaMA-Factory的5种推理方式总结
  • 链游技术破壁:NFT资产确权与Play-to-Earn经济模型实战
  • 为什么HDI叠孔比错孔设计难生产
  • 数据分析实战2(Tableau)
  • 游戏开发中的CI/CD优化案例:知名游戏公司Gearbox使用TeamCity简化CI/CD流程
  • Linux --TCP协议实现简单的网络通信(中英翻译)
  • LlamaIndex 工作流简介以及基础工作流
  • 如何利用Elastic Stack(ELK)进行安全日志分析
  • 创客匠人:以 AI 利器赋能创始人 IP 打造,加速知识变现新路径
  • Opencv中的copyto函数
  • TeamCity Agent 配置完整教程(配合 Docker Compose 快速部署)
  • 基于深度强化学习的Scrapy-Redis分布式爬虫动态调度策略研究
  • 在 Ubuntu 24.04 LTS 上安装 Jenkins 并配置全局工具(Git、JDK、Maven)
  • Tika Server:企业级文档内容解析的轻量级服务化方案
  • LMG1020YFFR 电子元器件详解
  • 防爆型断链保护器的应用场景有哪些?
  • leetcode_206 反转链表