我尝试使用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);
}
}
哈希值计算出现错误。我希望能得到一些反馈或者有人指点我正确的方向。
key
和data
被初始化为字符串字面量,则应该是sizeof(key) - 1
和sizeof(data) - 1
。原因是,使用字符串字面量初始化的字符数组(例如"johndoe"
)会附加上\0
字符。因此,相应的字符数组实际上具有字符序列johndoe\0
。通常不应将\0
哈希进去,因为这是C/C++特定的行为。 - nuiun