基于Hash的消息认证码HMAC简介及在OpenSSL中使用举例
HMAC(Hash-based Message Authentication Code):基于Hash的消息認(rèn)證碼,是一種通過(guò)特別計(jì)算方式之后產(chǎn)生的消息認(rèn)證碼(MAC),使用密碼散列函數(shù),同時(shí)結(jié)合一個(gè)加密密鑰。它可以用來(lái)保證數(shù)據(jù)的完整性,同時(shí)可以用來(lái)作某個(gè)消息的身份驗(yàn)證。HMAC運(yùn)算利用哈希算法,以一個(gè)密鑰和一個(gè)消息作為輸入,生成一個(gè)消息摘要作為輸出。
使用消息摘要算法MD2、MD4、MD5、SHA-1、SHA-224、SHA-256、SHA-384、SHA-512所構(gòu)造的HMAC,分別稱為HMAC-MD2、HMAC-MD4、HMAC-MD5、HMAC-SHA1、HMAC-SHA-224、HMAC-SHA-384、HMAC-SHA-512。
HMAC主要應(yīng)用在身份驗(yàn)證中,它的使用方法是這樣的:
(1). 客戶端發(fā)出登錄請(qǐng)求(假設(shè)是瀏覽器的GET請(qǐng)求);
(2). 服務(wù)器返回一個(gè)隨機(jī)值,并在會(huì)話中記錄這個(gè)隨機(jī)值;
(3). 客戶端將該隨機(jī)值作為密鑰,用戶密碼進(jìn)行HMAC運(yùn)算,然后提交給服務(wù)器;
(4). 服務(wù)器讀取用戶數(shù)據(jù)庫(kù)中的用戶密碼和步驟2中發(fā)送的隨機(jī)值做與客戶端一樣的HMAC運(yùn)算,然后與用戶發(fā)送的結(jié)果比較,如果結(jié)果一致則驗(yàn)證用戶合法。
以上整理的內(nèi)容主要摘自:https://baike.baidu.com/item/hmac
以下為測(cè)試代碼(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;
}
執(zhí)行結(jié)果如下:
GitHub:https://github.com/fengbingchun/OpenSSL_Test
總結(jié)
以上是生活随笔為你收集整理的基于Hash的消息认证码HMAC简介及在OpenSSL中使用举例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: FFmpeg中可执行文件ffmpeg用法
- 下一篇: 在Windows和Linux上编译gRP