1
$\begingroup$

PKCS5/7 pads the remaining data elements with a binary representation of how many space requires padding. This is useful and compact but what should I do in the following sample scenario below ?

Example: Use case scenario is to use AES or any fixed length 128 bit block cipher to encrypt user supplied data where the user can have control over the bytes sent and not limited to any sort of language format (i.e. UTF-8).

The user send the following bytes 05 05 05 05 05 05 05 05 05 05 05 05 05 05 05 05 (16 pieces of 0x05 bytes) to be PKCS5/7 encoded before AES encrypted. The PKCS 5/7 encoder would not do anything since it has all 16 bytes (1 block size required by AES cipher).

When the user wants to decrypt the data, the AES decryption succeed but the PKCS5/7 padding engine see 05 05 05 05 05 05 05 05 05 05 05 05 05 05 05 05 (16 pieces of 0x05 bytes).

If 5 pieces of 0x05 bytes are removed and simply returns 11 pieces of 0x05 bytes, this will mean the original data which is 05 05 05 05 05 05 05 05 05 05 05 05 05 05 05 05 would be corrupted at the PKCS decoder level.

What is the best way to handle data arrays that have all the same elements in a PKCS5/7 padding scheme when decoding data ?

$\endgroup$
5
$\begingroup$

The PKCS 5/7 encoder would not do anything since it has all 16 bytes (1 block size required by AES cipher).

That's where you're wrong.

Padding should be always applied. If the user is encrypting a plaintext that is already a multiple of the block size, then the PKCS#5/#7 padding schemes will add an additional full block of padding, so that there is no ambiguity when decrypting.

In your example, that would mean this is the padded plaintext that is encrypted:

05 05 05 05 05 05 05 05 05 05 05 05 05 05 05 05 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10

There are of course padding schemes that don't add an additional block (for example PHP's zero padding), but that's not how PKCS#5 or PKCS#7 works.

$\endgroup$
  • $\begingroup$ Since it's adding 16 bytes wouldn't the padding be 16 then? $\endgroup$ – Fleur Andersen Sep 14 '18 at 14:56
  • $\begingroup$ @FleurAndersen 10 is $16$ in hexadecimal. $\endgroup$ – SEJPM Sep 14 '18 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.