MD5

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

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

#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实现代码