在前面《网络安全-常用安全算法简介》说明过 HMAC 算法的用途,下面具体说下 openssl 命令操作及代码实现。
一、openssl命令 HMAC
$ echo -n "12345678" > in.file
$ openssl dgst -sha256 -hmac "12345" in.file
HMAC-SHA256(in.file)= 0f1564aaf4ca8e0dc663325a9a3782ca4c9c9507a689821e609c572a59c2fd67
二、openssl编程实现 HMAC
#include "openssl/hmac.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 省去了接口错误判断处理
int hmac(char *key, int key_len, char *buf, int buf_len) {
HMAC_CTX *ctx = NULL;
unsigned int len = 0;
unsigned char hmac_buf[32] = {0};
ctx = HMAC_CTX_new();
HMAC_Init_ex(ctx, key, key_len, EVP_sha256(), NULL);
HMAC_Update(ctx, buf, buf_len);
HMAC_Final(ctx, hmac_buf, &len);
HMAC_CTX_free(ctx);
printf("hmac buf:\n");
int i = 0, j = 0;
for (i = 0; i < len; i++)
{
printf("%02x ", hmac_buf[i]);
j++;
if (j % 16 == 0)
{
j = 0;
printf("\n");
}
}
printf("\n");
return 0;
}
int main(int argc, char const *argv[]) {
hmac("12345", 5, "12345678", 8);
return 0;
}
运行结果:
$ ./a.out
hmac buf:
0f 15 64 aa f4 ca 8e 0d c6 63 32 5a 9a 37 82 ca
4c 9c 95 07 a6 89 82 1e 60 9c 57 2a 59 c2 fd 67
和命令一致。
三、HMAC使用的补充说明
一般HMAC会和加密一块使用,即处理数据即要做加密保护,也要做防篡改保护。这个提供机密性和完整性的模式也叫做 Authenticated Encryption(AE)加密模式,处理上会有三种操作模式:
1、Encrypt-and-MAC (对明文分别进行加密和MAC计算后拼接)
2、MAC-then-Encrypt (先计算MAC,再跟明文一起加密)
3、Encrypt-the-MAC (先对明文进行加密,然后针对密文进行MAC计算)
目前模式1和2如果使用不当会存在安全问题,推荐使用模式3。
而现在常听到的 AEAD(Authenticated Encryption with Associated Data) 加密模式则结合了加密和MAC计算,避免使用者单独处理操作引起安全问题,常见的算法如 AES-GCM。