gpt4 book ai didi

c - 带 OpenSSL 的 MD5 HMAC

转载 作者:太空狗 更新时间:2023-10-29 15:39:03 26 4
gpt4 key购买 nike

我试图用 OpenSSL 生成 MD5 HMAC,大部分代码都是借来的。正在生成的 hmac 不正确:

#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <syslog.h>
#include <string.h>

#include <openssl/engine.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
unsigned char* key = (unsigned char*) "2012121220121212201212122012121220121212201212122012121220121212";
unsigned char* data = (unsigned char*) "johndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoejohndoe";
unsigned char* expected = (unsigned char*) "abcd1d87dca34f334786307d0da4fcbd";
unsigned char* result;
// unsigned int result_len = 16;
unsigned int result_len = 16;
int i;
static char res_hexstring[32];

// result = HMAC(EVP_sha256(), key, 4, data, 28, NULL, NULL);
result = HMAC(EVP_md5(), key, 32, data, 28, NULL, NULL);
for (i = 0; i < result_len; i++) {
sprintf(&(res_hexstring[i * 2]), "%02x", result[i]);
}

if (strcmp((char*) res_hexstring, (char*) expected) == 0) {
printf("Test ok, result length %d\n", result_len);
} else {
printf("Got %s instead of %s\n", res_hexstring, expected);
}
}

生成的散列不正确。我会很感激一些反馈或有人指出我正确的方向。

最佳答案

HMAC 的第三个和第五个参数是错误的。您必须传递 key 的长度和数据的长度。在您的示例中,这分别是 64 和 84,而不是 32 和 28。

所以:

-    result = HMAC(EVP_md5(), key, 32, data, 28, NULL, NULL);                                                                                                                                                                         
+ result = HMAC(EVP_md5(), key, 64, data, 84, NULL, NULL);

经过这次修改,它似乎工作正常。

关于c - 带 OpenSSL 的 MD5 HMAC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13555962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com