如何利用openssl来计算一个文件的MD5值?

       openssl环境的配置, 我就不再说了, 可以参考之前的的博文。 前面, 我们计算过字符串的md5值, 在本文中, 我们来讨论一个文件的md5值, 废话少说, 直接给大家代码, 上点干货:

#include <iostream>
#include <openssl/md5.h> // 如果你直接拷贝我的程序运行, 那注定找不到md5.h
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")  // 在本程序中, 可以注释掉这句
using namespace std;

int main()
{
	MD5_CTX ctx;
	int len = 0;
	unsigned char buffer[1024] = {0};
	unsigned char digest[16] = {0};
	
	FILE *pFile = fopen ("test.db", "rb"); // 我没有判断空指针
	
	MD5_Init (&ctx);

	while ((len = fread (buffer, 1, 1024, pFile)) > 0)
	{
		MD5_Update (&ctx, buffer, len);
	}

	MD5_Final (digest, &ctx);
	
	fclose(pFile);
	

	int i = 0;
	char buf[33] = {0};
    char tmp[3] = {0};
    for(i = 0; i < 16; i++ )
	{
		sprintf(tmp,"%02X", digest[i]); // sprintf并不安全
		strcat(buf, tmp); // strcat亦不是什么好东西
    }
	
	cout << buf << endl;  // 文件的md5值

    return 0;
}
      经与其他工具软件进行对比, 发现结果完全一致, ok,  就这样吧。

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值