RSA_new和RSA_generate_key_ex使内存泄漏

时间:2017-05-31 05:38:52

标签: c encryption memory-leaks openssl rsa

我正在开发一个需要RSA密钥来加密某些用户数据的应用。我使用openssl,一切正常。然而,应用程序在RSA_new和RSA_generate_key_ex(我认为它不应该是因为我发布了我创建的所有属性)时一直警告内存泄漏。

以下是我生成RSA密钥的代码:

BIGNUM e;
BN_init(&e);
BN_set_word(&e, 17);
RSA *rsa = RSA_new(); // Direct leak of 191 bytes in 1 object (RSA_new->RSA_new_method->...)
RAS_generate_key_ex(rsa, 1024, &e, NULL); // Indirect leak of 279 bytes in 1 object (RAS_generate_key_ex->rsa_builtin_keygen...)
EVP_PKEY pkey = EVP_PKEY_new();
EVP_PKEY_set1_RSA(pkey, rsa);
RSA_free(rsa);
BN_free(&e);
MINE_COPY_KEY(pkey); // I copy the pkey to other location at here //
EVP_PKEY_free(pkey);

我认为我分配的所有内容(e,pkey,rsa)已经由" RSA_free,EVP_PKEY_free和BN_free"但它仍然抱怨我的Linux x64机器中的内存泄漏

1 个答案:

答案 0 :(得分:2)

我尝试了你的程序(在修复了诸如RAS_generate_key_ex - > RSA_generate_key_exEVP_PKEY pkey = EVP_PKEY_new() - > EVP_PKEY* pkey = EVP_PKEY_new()之类的拼写错误之后。

我现在有这个来源:

#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>

int main() {
  BIGNUM e;
  BN_init(&e);
  BN_set_word(&e, 17);
  RSA *rsa = RSA_new();
  RSA_generate_key_ex(rsa, 1024, &e, NULL);
  EVP_PKEY* pkey = EVP_PKEY_new();
  EVP_PKEY_set1_RSA(pkey, rsa);
  RSA_free(rsa);
  BN_free(&e);
  //MINE_COPY_KEY(pkey); // I copy the pkey to other location at here //
  EVP_PKEY_free(pkey);
  return 0;
}

Valgrind说:

==18061== 
==18061== LEAK SUMMARY:
==18061==    definitely lost: 0 bytes in 0 blocks
==18061==    indirectly lost: 0 bytes in 0 blocks
==18061==      possibly lost: 0 bytes in 0 blocks
==18061==    still reachable: 220 bytes in 6 blocks
==18061==         suppressed: 0 bytes in 0 blocks
==18061== Reachable blocks (those to which a pointer was found) are not shown.
==18061== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==18061== 
==18061== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==18061== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

在程序结束时添加CRYPTO_cleanup_all_ex_data();使得Valgring感到高兴: - )

==18212== HEAP SUMMARY:
==18212==     in use at exit: 0 bytes in 0 blocks
==18212==   total heap usage: 457 allocs, 457 frees, 31,748 bytes allocated
==18212== 
==18212== All heap blocks were freed -- no leaks are possible
==18212== 
==18212== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==18212== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

请参阅:https://stackoverflow.com/a/21533000/6267288