基于Hash的消息认证码HMAC简介及在OpenSSL中使用举例

HMAC(Hash-based Message Authentication Code):基于Hash的消息认证码,是一种通过特别计算方式之后产生的消息认证码(MAC),使用密码散列函数,同时结合一个加密密钥。它可以用来保证数据的完整性,同时可以用来作某个消息的身份验证。HMAC运算利用哈希算法,以一个密钥和一个消息作为输入,生成一个消息摘要作为输出

使用消息摘要算法MD2、MD4、MD5、SHA-1、SHA-224、SHA-256、SHA-384、SHA-512所构造的HMAC,分别称为HMAC-MD2、HMAC-MD4、HMAC-MD5、HMAC-SHA1、HMAC-SHA-224、HMAC-SHA-384、HMAC-SHA-512。

HMAC主要应用在身份验证中,它的使用方法是这样的:

(1). 客户端发出登录请求(假设是浏览器的GET请求);

(2). 服务器返回一个随机值,并在会话中记录这个随机值;

(3). 客户端将该随机值作为密钥,用户密码进行HMAC运算,然后提交给服务器;

(4). 服务器读取用户数据库中的用户密码和步骤2中发送的随机值做与客户端一样的HMAC运算,然后与用户发送的结果比较,如果结果一致则验证用户合法。

以上整理的内容主要摘自:https://baike.baidu.com/item/hmac

以下为测试代码(test_openssl_hmac):

#include "funset.hpp"
#include <string.h>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <openssl/des.h>
#include <openssl/rc4.h>
#include <openssl/md5.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/aes.h>
#include <openssl/hmac.h>
#include <b64/b64.h>

//////////////////////////// HMAC ///////////////////////////////
int test_openssl_hmac()
{
	HMAC_CTX ctx;
	HMAC_CTX_init(&ctx);
	
	const EVP_MD* engine = EVP_sha256(); // it can also be: EVP_md5(), EVP_sha1, etc
	const char* key = "https://github.com/fengbingchun";
	const char* data = "https://blog.csdn.net/fengbingchun";
	std::unique_ptr<unsigned char[]> output(new unsigned char[EVP_MAX_MD_SIZE]);
	unsigned int output_length;

	HMAC_Init_ex(&ctx, key, strlen(key), engine, nullptr);
	HMAC_Update(&ctx, reinterpret_cast<const unsigned char*>(data), strlen(data));

	HMAC_Final(&ctx, output.get(), &output_length);
	HMAC_CTX_cleanup(&ctx);

	fprintf(stdout, "output length: %d\noutput result:", output_length);
	std::for_each(output.get(), output.get() + output_length, [](unsigned char v) { fprintf(stdout, "%02X", v); });
	fprintf(stdout, "\n");

	return 0;
}

执行结果如下:

GitHubhttps://github.com/fengbingchun/OpenSSL_Test

发布了718 篇原创文章 · 获赞 1131 · 访问量 609万+

猜你喜欢

转载自blog.csdn.net/fengbingchun/article/details/100176887