我有以下功能:
static int my_hmac(unsigned char *data, int len, char *password, unsigned char *hmac)
{
unsigned char* digest;
digest = HMAC(EVP_sha1(), password, strlen(password), data, len, NULL, NULL);
memcpy(hmac, digest, 20);
return 0;
}
我以这种方式在main()
中称呼它
unsigned char buffer[20]
my_hmac(str, strlen(str), "password", buffer)
使用HMAC()
函数后,我应该调用libcrypto / libopenssl的一些空闲内存api吗?
答案 0 :(得分:1)
由于您标记了帖子,我将假设您正在使用该帖子。
根据documentation,因为你传递了openssl
作为NULL
(倒数第二个参数)的参数,所以结果放在一个静态数组中,所以不需要你担心那里的解除分配。
至于返回值,
md
返回指向消息验证码的指针,如果发生错误则返回HMAC()
。
此消息验证代码不是您拥有的内存,因此您不应尝试释放它。
答案 1 :(得分:0)
使用valgrind测试,使用HMAC()
<强>样本强>
test.c的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/hmac.h>
static int my_hmac(unsigned char *data, int len, char *password, unsigned char *hmac)
{
unsigned char* digest;
digest = HMAC(EVP_sha1(), password, strlen(password), data, len, NULL, NULL);
memcpy(hmac, digest, 20);
return 0;
}
int main(int argc, char **argv) {
unsigned char buf[20];
char *txt = "kallel";
my_hmac(txt, strlen(txt), "password", buf);
return 0;
}
使用valgrind构建并运行:
mylinux ~ $ gcc -o test test.c -lcrypto
mylinux ~ $ valgrind ./test
==5447== Memcheck, a memory error detector
==5447== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==5447== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==5447== Command: ./test
==5447==
==5447==
==5447== HEAP SUMMARY:
==5447== in use at exit: 0 bytes in 0 blocks
==5447== total heap usage: 3 allocs, 3 frees, 312 bytes allocated
==5447==
==5447== All heap blocks were freed -- no leaks are possible
==5447==
==5447== For counts of detected and suppressed errors, rerun with: -v
==5447== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)