OpenSSL EVP API实现MD5加密C++代码

网上找到的大部分都是旧API,新版OpenSSL推荐使用EVP系列接口,在此记录下EVP方式的MD5哈希实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "openssl/conf.h"
#include "openssl/evp.h"
#include "openssl/err.h"
#include "openssl/engine.h"
 
void handle_errors()
{
    ERR_print_errors_fp(stderr);
    abort();
}
 
std::string md5_str(const std::string & str)
{
    const auto * md = EVP_get_digestbyname("MD5");
    if (nullptr == md)
    {
        std::cerr << "Failed to EVP_get_digestbyname MD5!" << std::endl;
        return "";
    }
 
    unsigned char buf[EVP_MAX_MD_SIZE] = {};
    unsigned int olen = EVP_MAX_MD_SIZE;
 
    EVP_MD_CTX * ctx = EVP_MD_CTX_new();
    if (nullptr == ctx)
    {
        std::cerr << "Failed to EVP_MD_CTX_new!" << std::endl;
        return "";
    }
    if (1 != EVP_DigestInit(ctx, md))
    {
        handle_errors();
        return "";
    }
    if (1 != EVP_DigestUpdate(ctx, str.data(), str.length()))
    {
        handle_errors();
        return "";
    }
    if (1 != EVP_DigestFinal(ctx, buf, &olen))
    {
        handle_errors();
        return "";
    }
    EVP_MD_CTX_free(ctx);
 
    return { reinterpret_cast<char*>(buf), olen };
}
 
int main()
{
    OpenSSL_add_all_digests();
    const std::string plain = "test1234";
    const std::string hash = md5_str(plain);
    std::cout << "plain: " << plain << " md5 hash: " << hash << std::endl;
    return EXIT_SUCCESS;
}

后面有时间再增加AES等的EVP实现代码

博主友情提示:

如您在评论中需要提及如QQ号、电子邮件地址或其他隐私敏感信息,欢迎使用>>博主专用加密工具v3<<处理后发布,原文只有博主可以看到。