如何利用openssl来计算md4, md5, sha1, sha256, sha384, sha512等常用哈希值?

       openssl的库的用法, 前面已经介绍了, 所以不再啰嗦, 直接给出代码:

// openssl的库的用法, 前面已经介绍了, 所以不再啰嗦, 直接给出代码

#include <iostream>
#include <openssl/evp.h>
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib") // 可以注释掉
using namespace std;


int main()
{
	char digestType[][20] = 
	{
		"xxx", // 非法
		"md4",
		"md5",
		"sha1",
		"sha256",
		"sha384",
		"sha512",
	};

	int size = sizeof(digestType) / sizeof(digestType[0]);
	int i = 0;
	for(i = 0; i < size; i++)
	{	
		EVP_MD_CTX mdctx;
		const EVP_MD *md = NULL;
		char str[] = "testOpenssl";
		unsigned char mdValue[EVP_MAX_MD_SIZE] = {0};
		unsigned int mdLen = 0;

		OpenSSL_add_all_digests();
		md = EVP_get_digestbyname(digestType[i]);
		if(!md) // 不支持的格式
		{
			printf("Unknown message digest %s\n", digestType[i]);
			continue;
		}

		EVP_MD_CTX_init(&mdctx);
		EVP_DigestInit_ex(&mdctx, md, NULL);
		EVP_DigestUpdate(&mdctx, str, strlen(str));
		EVP_DigestFinal_ex(&mdctx, mdValue, &mdLen);
		EVP_MD_CTX_cleanup(&mdctx);

		printf("%s is ",  digestType[i]);
		int j = 0;
		for(j = 0; j < mdLen; j++)
		{
			printf("%02X", mdValue[j]);
		}

		printf("\n");
	}

	return 0;
}
      结果为:

Unknown message digest xxx
md4 is 3F1DED43A61E531EB49771D7519741A6
md5 is BD9A9CAE3D300EC608C217658E20F934
sha1 is 842CC44DB178A7A73BDB2BCDB7386BCABD56A5CB
sha256 is DB22DB9C451E72D85ED9348A736A69A66451593598C2CABACC949C6E33D844DF
sha384 is 707F730102F9C512C53348BE2C0A80D5B5CB8C67CC7A4A4602E99710CD37466BC3ED4F076BA9B77428D1C2EC35A7F261
sha512 is DAE45250C34FCF0860D02F692B9FC79FEA7E6D82C342EB7C402C71959D1B8CABCFFBC61142FFA21344130E809F0AE87AA002C24DB3F1542BA8331A6E82743C7F

       与其他软件生成的值进行对比, 发现完全一致。 openssl太厉害了啊闭嘴



你可能感兴趣的:(如何利用openssl来计算md4, md5, sha1, sha256, sha384, sha512等常用哈希值?)