RSA_new 和 RSA_generate_key_ex 造成内存泄漏

RSA_new and RSA_generate_key_ex make memory leakage

我正在开发一个需要 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, and BN_free" 释放了,但它仍然抱怨我的 Linux x64 机器

内存泄漏

我试过你的程序(修正了 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)

参见: