c++ openssl 计算文件 md5

创建日期: 2023-05-27 16:17 | 作者: 风波 | 浏览次数: 15 | 分类: C++

openssl 接口文档:https://www.openssl.org/docs/man3.1/man3/MD5.html 这几个函数在 OpenSSl3.0 里面被废弃了

The following functions have been deprecated since OpenSSL 3.0, and can be hidden entirely by defining OPENSSL_API_COMPAT with a suitable version value, see openssl_user_macros(7):

unsigned char *MD5(const unsigned char *d, unsigned long n, unsigned char *md);

int MD5_Init(MD5_CTX *c);
int MD5_Update(MD5_CTX *c, const void *data, unsigned long len);
int MD5_Final(unsigned char *md, MD5_CTX *c);

计算文件 MD5

安装依赖

yum install -y openssl-devel

编译

g++ --std=c++11 -o main main.c -lssl -lcrypto

函数参数

  1. filepath - 文件路径

返回值

  1. md5 字符串。如果失败,则返回空字符串 ""

函数

#include <openssl/md5.h>

std::string md5sum(const std::string &filepath) {
    unsigned char outmd[MD5_DIGEST_LENGTH];
    unsigned char buffer[4096];
    auto fp = fopen(filepath.c_str(), "rb");
    if(!fp) {
        return "";
    }
    MD5_CTX ctx;
    MD5_Init(&ctx);
    int len = 0;
    while((len = fread(buffer, sizeof(unsigned char), sizeof(buffer), fp)) > 0) {
        MD5_Update(&ctx, buffer, len);
    }
    MD5_Final(outmd, &ctx);
    fclose(fp);

    unsigned char low_mask = 0b00001111;
    unsigned char high_mask = 0b11110000;
    std::stringstream stream;
    for (size_t idx = 0; idx < MD5_DIGEST_LENGTH; idx++) {
        stream << std::hex << (size_t)((outmd[idx] & high_mask) >> 4)
            << std::hex << (size_t)(outmd[idx] & low_mask);
    }
    auto md5sum = stream.str();

    return md5sum;
}
15 浏览
9 爬虫
0 评论