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

来源:互联网 发布:查看linux下所有用户 编辑:程序博客网 时间:2024/05/17 09:35

       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,  就这样吧。

0 0