当前位置:   article > 正文

基于Hash的消息认证码HMAC简介及在OpenSSL中使用举例_c语言 hmac()定义

c语言 hmac()定义

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):

  1. #include "funset.hpp"
  2. #include <string.h>
  3. #include <string>
  4. #include <vector>
  5. #include <memory>
  6. #include <algorithm>
  7. #include <openssl/des.h>
  8. #include <openssl/rc4.h>
  9. #include <openssl/md5.h>
  10. #include <openssl/rsa.h>
  11. #include <openssl/pem.h>
  12. #include <openssl/aes.h>
  13. #include <openssl/hmac.h>
  14. #include <b64/b64.h>
  15. HMAC ///
  16. int test_openssl_hmac()
  17. {
  18. HMAC_CTX ctx;
  19. HMAC_CTX_init(&ctx);
  20. const EVP_MD* engine = EVP_sha256(); // it can also be: EVP_md5(), EVP_sha1, etc
  21. const char* key = "https://github.com/fengbingchun";
  22. const char* data = "https://blog.csdn.net/fengbingchun";
  23. std::unique_ptr<unsigned char[]> output(new unsigned char[EVP_MAX_MD_SIZE]);
  24. unsigned int output_length;
  25. HMAC_Init_ex(&ctx, key, strlen(key), engine, nullptr);
  26. HMAC_Update(&ctx, reinterpret_cast<const unsigned char*>(data), strlen(data));
  27. HMAC_Final(&ctx, output.get(), &output_length);
  28. HMAC_CTX_cleanup(&ctx);
  29. fprintf(stdout, "output length: %d\noutput result:", output_length);
  30. std::for_each(output.get(), output.get() + output_length, [](unsigned char v) { fprintf(stdout, "%02X", v); });
  31. fprintf(stdout, "\n");
  32. return 0;
  33. }

执行结果如下:

GitHubhttps://github.com/fengbingchun/OpenSSL_Test

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/390677?site
推荐阅读
相关标签
  

闽ICP备14008679号