我正在尝试下面的代码。事情是这样的:有些时候起作用,而有些时候不行!我正在使用OpenSSL库,但我相信我的错误是简单的,C相关的。
int test_c(string to_sign, string key)
{
const void* key_void = (const void*)key.c_str();
int key_size = key.size();
const unsigned char* data_char = (const unsigned char*)to_sign.c_str();
int data_size = to_sign.size();
unsigned int res_f_len = data_size*8;
unsigned char* res_f = (unsigned char*) malloc(sizeof(unsigned char)*res_f_len);
HMAC_CTX ctx;
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, key_void, key_size, EVP_sha256(), NULL);
HMAC_Update(&ctx, data_char, data_size);
HMAC_Final(&ctx, res_f, &res_f_len);
HMAC_CTX_cleanup(&ctx);
return strlen(res_f);
}当我说它不起作用时,我的意思是,对于相同的数据和键,会返回不同的结果!
发布于 2013-12-19 02:42:43
与其将strlen(res_f);作为输出缓冲区的长度返回,还需要返回res_f_len。
代码中的strlen()有三种可能发生的情况:
strlen将返回比HMAC消息摘要更短的长度。strlen将在消息摘要之后读取,从而导致两个结果之一:。strlen在消息摘要之后读取内存中的垃圾,最终在随机0上停止。strlen返回一个太大的值。strlen返回消息摘要的实际长度。
因此,只有在最后一个场景中,您才能得到正确的值。这似乎是不对的。
HMAC_Final似乎确实更新了传递给它的长度参数。(See the example in the top-voted answer to this StackOverflow question.)这就是为什么你传递一个指针到int的原因。您应该只返回这个更新的值。
https://stackoverflow.com/questions/20671301
复制相似问题