0
$\begingroup$

I want to implement AES-CBC mode with PKCS#7 padding, along with a way to validate a correct padding given the ciphertext. My initial understanding was that for an input of size n (where n is less than 16) PKCS#7 pads 16-n until the input becomes divisible by 16 (or equal to 16 in this case). But later I realized that this would make it impossible to validate a correct padding.

Then I found out that you always pad at least 1 byte when doing PKCS#7 padding (with byte 01 if length of input is divisible by the desired amount). Is this understanding correct? If so, should I divide my input into blocks with size of 15 bytes (with 16th byte being the pad byte)?

$\endgroup$
1
  • $\begingroup$ Instead of guessing, did you consider looking at wikipedia or the specification (actually that's CMS, the successor to PKCS7, because it has proper hyperlinks and 2315 doesn't, but this content is the same) $\endgroup$ Dec 22, 2020 at 2:56

1 Answer 1

2
$\begingroup$

Then I found out that you always pad at least 1 byte when doing PKCS#7 padding (with byte 01 if length of input is divisible by the desired amount). Is this understanding correct?

Actually, if the input was already a multiple of 16 bytes, the padding would consist of 16 10 (hex) bytes, which you would append to the end of the input. Then, the padded input will then be a multiple of 16 bytes (which, with this padding method, is always the case, even if the original input was an odd length).

If so, should I divide my input into blocks with size of 15 bytes (with 16th byte being the pad byte)?

No; you need to add padding only to the end of the message - there is no reason (or permission, as far as PKCS#7 is concerned) to add padding to the intermediate blocks.

$\endgroup$
1
  • $\begingroup$ I see, thank you for the answer $\endgroup$
    – Ach113
    Dec 21, 2020 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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