The 'junk' on the end is PKCS padding. Since AES is a block cipher, it needs to operate on multiples of the block size (16 bytes, or 128 bits). PKCS padding specifies that the final set of bytes are each set to the number of bytes of padding -- in the 0c case, that's 12 bytes of padding; in the 0b case, that's 11 bytes of padding; in the 0a case, that's 10 bytes of padding. If the number of bytes of padding specified by the last byte is repeated that number of times prior (including itself), then those are all padding bytes.

31 32 33 34 35 36 37 38 39 30 06 06 06 06 06 06

That would be:
1234567890[pad*6]

However:

30 31 32 33 34 35 36 37 38 39 03 03 03 01 06 05

would be:

0 1 2 3 4 5 6 7 8 9 ^c ^c ^c ^a ^f ^e

because the last 5 bytes don't match. (In such a case, there will often -- but not always -- be a full block of padding afterward:

0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f

This is to prevent a truncation attack.)

I'm pretty sure there's a way to disable this form of padding, but the block must be padded with *something* (either NUL bytes [0x00], or the number of bytes of padding inserted) or else the block cannot be encrypted.

-Kyle H

On Apr 1, 2009, at 3:37 AM, m r wrote:

I'm looking to migrate AES encryption code from BSAFE to openSSL. As a test,
I encrypted a string using BSAFE AES & tried to decrypt using AES of
openSSL. The openSSL manages to decrypt, but it adds some junk (mostly
unprintable characters) in the end. For example, if my input is 1234, the
decrypted output in hex form is [313233340c0c0c0c0c0c0c0c0c0c0c0c],
(31323334 is 1234 in hex form).
For 12345 ->   [31323334350b0b0b0b0b0b0b0b0b0b0b]
For 123456 -> [3132333435360a0a0a0a0a0a0a0a0a0a]

Basically, the junk after the decrypted text is 16 - (string length of
decrypted text)

For example, 1234's  length is 4, 16 - 4 = 12 = 0c in hex & so it gets
filled with that. (313233340c0c0c0c0c0c0c0c0c0c0c0c)
For example, 12345's length is 5, 16 - 5 = 11 = 0b in hex & so it gets
filled with that.(31323334350b0b0b0b0b0b0b0b0b0b0b)

So what needs to be done to prevent openSSL API [I'm
using AES_cbc_encrypt()] to prevent it from writing this strange junk at the
end?

Thanks
-Mahesh

Attachment: smime.p7s
Description: S/MIME cryptographic signature

Reply via email to