On Sat, Aug 2, 2014 at 12:16 AM, David Li <dlipub...@gmail.com> wrote:

> Hi Thulasi,
>
> You are right! It's a bug on my part.
>
> I have a follow-up question regarding what EVP_DecryptFinal is doing.
>
>  In my case, the original string is 27 bytes long, the ciphertext  length
> is 48 ( I am using AES-CBC-128). The decrypted plaintext before
> finalization is 32 but the finalization added 11 more bytes. So the total
> decrypted len is 43.
>

I guess, you must be feeding 43 byte (>=32 byte) plaintext  for encryption
which outputs 48 byte ciphertext. For 27 byte plaintext, there would only
be 32 byte ciphertext, of which, first 16 byte get decrypted with
DecryptUpdate to result in first 16 bytes of plaintext, and  last 16 bytes
get decrypted with DecryptFinal to result in last 11 bytes of plaintext.
(removes padding that gets applied during encryption)

There might be an issue with encrypt too which may be feeding additional 16
bytes (27 + 16) to EncryptUpdate. Do you apply padding yourself for
plaintext and send 32 bytes for encryption? If so, you should explicitly
tell the encrypt context to skip the padding by calling
EVP_CIPHER_CTX_set_padding(&ctx, 0)


> Can you explain where the 11 more bytes are coming from after
> finalization?  Also It seems OK even if I don't use finalization,
>

You must always call EncryptFinal/DecryptFinal, These functions will take
care of un-aligned last block. EncryptFinal applies the padding and
encrypts, and DecryptFinal decrypts the last block and removes the padding.


>
> David
>
>
> On Thu, Jul 31, 2014 at 8:22 PM, Thulasi Goriparthi <
> thulasi.goripar...@gmail.com> wrote:
>
>>
>>
>>
>> On Fri, Aug 1, 2014 at 5:46 AM, David Li <dlipub...@gmail.com> wrote:
>>
>>> Hi,
>>>
>>> I am using openssl 1.0.1h and AES128 CBC mode to encrypt some arbitrary
>>> long ASCII string.
>>> I encountered an issue at decryption. If I use EVP_DecryptFinal_ex then
>>> the output is unrecognizable. If I remove the following then the output is
>>> OK.
>>>
>>> if ((rc = EVP_DecryptFinal_ex(&ctx, debuf, &tmplen)) == 0) {
>>>     printf (" Finalization error: %d\n", rc);
>>>     return -1;
>>>   }
>>>
>>
>> You are most probably over-writing the decrypted data you have got with
>> EVP_DecryptUpdate.  Skip the the length that you have already decrypted in
>> debuf. i.e If you have got outlen bytes from DecryptUpdate, you should
>> supply "debuf+outlen" as second argument to EVP_DecryptFinal
>>
>>
>>> Can anyone explain why?
>>>
>>> David
>>>
>>>
>>
>

Reply via email to