hmac测试

openssl命令:

生成hmac:

验证:

C语言代码实现:

代码如下:

 

` #include #include #include #include

int main() {
// 这个例子中,我们将随机生成一个密钥
unsigned char key[EVP_MAX_MD_SIZE];
int key_len = 32;

// OpenSSL 函数 RAND_bytes 用于生成强随机数
if (!RAND_bytes(key, key_len)) {
    fprintf(stderr, "Unable to generate random key.\n");
    return 1;
}

// 要 HMAC 的数据
unsigned char data[] = "Hello, 20211122";

// 使用 HMAC_CTX 进行 HMAC-SM3
HMAC_CTX *hmac_ctx = HMAC_CTX_new();

// 初始化 HMAC-SM3
if (!HMAC_Init_ex(hmac_ctx, key, key_len, EVP_sm3(), NULL)) {
    fprintf(stderr, "HMAC Init failed.\n");
    return 1;
}

// 输入数据到 HMAC
if (!HMAC_Update(hmac_ctx, data, strlen((char*)data))) {
    fprintf(stderr, "HMAC Update failed.\n");
    return 1;
}

// 完成 HMAC 运算
unsigned char hmac_value[EVP_MAX_MD_SIZE];
unsigned int hmac_length;

if (!HMAC_Final(hmac_ctx, hmac_value, &hmac_length)) {
    fprintf(stderr, "HMAC Final failed.\n");
    return 1;
}

// 清理 HMAC_CTX
HMAC_CTX_free(hmac_ctx);

// 打印 HMAC-SM3 值
printf("HMAC-SM3: ");
for (int i = 0; i < hmac_length; i++) {
    printf("%02x", hmac_value[i]);
}
printf("\n");

return 0;

}
`
运行:

验证:

posted @ 2024-04-29 09:36  天问—九章  阅读(4)  评论(0编辑  收藏  举报