Vanya Vanya - 2 months ago 20
C Question

Correct way to free/allocate the context in the OpenSSL

I'am using the Open SSL in my program, to encrypt and decrypt the data using aes ciphers. At the moment there is a little memory leak, so i'm looking for a way to fix that. In my encrypt decrypt routines, i have the contexts free like so

EVP_CIPHER_CTX_free(ctx);


And created by:

EVP_CIPHER_CTX_new


This was on the OpenSSL wiki page in the examples

But! On the MAN page, there is a suggestion for using
EVP_CIPHER_CTX_cleanup
and
EVP_CIPHER_CTX_init
functions. So basically what should be correct to use, is the
EVP_CIPHER_CTX_new
/
EVP_CIPHER_CTX_free
is somehow deprecated? And is there any big difference between
EVP_CIPHER_CTX_new
/
EVP_CIPHER_CTX_free
and
EVP_CIPHER_CTX_init
/
EVP_CIPHER_CTX_cleanup
?

if(!(ctx = EVP_CIPHER_CTX_new())) return -1;


if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}

if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}
ciphertext_len = len;


if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) { EVP_CIPHER_CTX_free(ctx); return -1; }
ciphertext_len += len;


EVP_CIPHER_CTX_free(ctx);

Answer

Allright, i think it's cleared now. If you do EVP style encryption/decryption, make sure you create the context like so:

  EVP_CIPHER_CTX ctx;
  EVP_CIPHER_CTX_init(&ctx);

And free it like so:

EVP_CIPHER_CTX_cleanup(&ctx); 

Don't use EVP_CIPHER_CTX_new/EVP_CIPHER_CTX_free to create/free the context, they are deprecated!