我試着下面的代碼。事情是:有些時候工作,有些時候不工作!我正在使用OpenSSL庫,但我相信我的錯誤是簡單的,與C有關。初學者的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);
}
當我說這是行不通的,我的意思是,對於相同的數據和關鍵,不同的結果返回!
如果這是C,那麼你不需要在'void *'s(包括'malloc()')的返回值。如果這是C++,請不要用'c'標記。 – 2013-12-19 00:29:35
對不起,它的C++ – Blazer
您使用strlen(res_f)表示結果字符串大小未知。 HMAC函數是否填充/零res_f?如果不是,malloc會返回一個指向充滿未定義值(如in,garbage)的內存的指針,strlen通過查找0來工作。 – Warty