What is PKCS#5 padding?

Ciphers process data in blocks, for example 8 byte blocks. If the length of the data that you want to encrypt is not evenly divisible by the blocksize that your encryption algorithm uses, the data needs to be padded. PKCS#5 is one way of padding. It appends to every message a block of data varying from 1 to 8 bytes where each bytes contain the number of bytes that are padded.

For instance, if the length of the data is 10, then 6 bytes need to be padded. The last block of 8 bytes will look like this:

 +---+---+---+---+---+---+---+---+
 | D | D | 6 | 6 | 6 | 6 | 6 | 6 |
 +---+---+---+---+---+---+---+---+

If the length of your data happens to be evenly divisible by 8, an extra 8 bytes will be added looking like this:

 +---+---+---+---+---+---+---+---+
 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 |
 +---+---+---+---+---+---+---+---+

This is because PKCS5Padding always assumes there is a pad.