Understanding how padding works when using Block Cipher I'm trying to understand how padding works when using block ciphers.


  Padding may be required when the size of the plain text is not a multiple of the block size


If that's so, then I don't understand the results I am getting on my Ubuntu VM.

I created a .txt file in size of 20 bytes, encrypted it using AES128-ECB. I then ran a command to check the encrypted .bin file size and it was 32 bytes as expected.

What I don't understand is the following scenario — I created another .txt file, this time in size of 32 bytes, encrypted it using same method and when I checked the encrypted file's size I got 48 bytes and not 32.

My question is why is it I am getting 48 bytes instead of 32? Obviously this time the plain text's size was a multiple of the block size and yet it treated it as if it wasn't.
The padding scheme being used in your example for the block cipher is PKCS#7 Padding.

This scheme specifies that:


  The value of each added byte is the number of bytes that are added, i.e. N bytes, each of value N are added.


The thing is, if the plaintext is multiple of the block size, then a whole new padding block is added. In this case it will be a block of 16 bytes with value 16.


   This is necessary so the deciphering algorithm can determine with certainty whether the last byte of the last block is a pad byte indicating the number of padding bytes added or part of the plaintext message.


That's why your ciphertext has a size of 48 bytes when the plaintext is 32 bytes. That is one ciphertext byte for each plaintext plus a whole new block of padding