基于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, etcconst 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;
}
執行結果如下:
GitHub:https://github.com/fengbingchun/OpenSSL_Test
總結
以上是生活随笔為你收集整理的基于Hash的消息认证码HMAC简介及在OpenSSL中使用举例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FFmpeg中可执行文件ffmpeg用法
- 下一篇: 在Windows和Linux上编译gRP