Vanya
Vanya

Reputation: 439

OpenSSL EVP_DecryptFinal_ex generating the garbage at the end of the output buffer

I am decrypting some data with openssl functions and i have some problems with the final result of the decryption.

 EVP_DecryptInit_ex(ctx, EVP_aes_192_cbc(), NULL, myKey, myVector);

    int iPos = 0;

    EVP_DecryptUpdate(ctx, decryptedData, &outLength, cryptedData,216);

    INFO_NET_HEADER * header = (INFO_NET_HEADER)decryptedData;
    iPos += outLength;

    //...

    int  nStreamLength =  ((header->incoming_audio_len / 16 +1) *16) - 16; //adjusting the length to the block size, incoming_audio_len is a length of the plain audio stream non-crypted data

   char *rest =  malloc(nStreamLength+48);
   char *decryptedStream = malloc(nStreamLength+48);
   int size =  receiveRemaining(nStreamLength,rest);
   memcpy(decryptedStream,0,nStreamLength+48);

   EVP_DecryptUpdate(ctx, decryptedStream, &outLength, rest,size);

    EVP_DecryptFinal_ex(ctx, decryptedStream+outLength, &loutLength);

I am decrypting by parts, first i need to decrypt the 200 bytes because they contain some names and data length that i need to get and the receive this data. Both first 200 bytes and the rest of the data are encrypted with the same key. Then i take the amount of data which i need to decrypt to receive the full stream, i successfully receive those, and everything is all right but in the output buffer there is always remains some garbage in the end like "somedataend\x14\x14\x14..." etc, the garbage size is from 14 to 16 bytes length, is it the normal behavior of the EVP openssl functions?

Upvotes: 0

Views: 656

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93948

Not seen in the sample code, but I presume you've put in EVP_CIPHER_CTX_set_padding to disable the padding when you are decrypting your "parts". You need to reenable it when decrypting the last part of ciphertext, otherwise the padding will remain.

Also beware that you take heed of the &loutLength returned at the end. After removal of the padding there will be less bytes left in the plaintext than the ciphertext contained.

Upvotes: 0

Related Questions