How can padding be disambiguated from data, when encrypting using a block cipher?

I'm by no means an expert in cryptography, but rather a programmer with a keen interest.

Suppose, I've X bytes of data, message M, that I want to encrypt using an N-byte block cipher, where N >> X.

How can M be padded using N-X bytes of padding O, such that there would be no ambiguity between decrypting the padded message and the (concatenated) message M|O?

How is this done in practice? Normally, when encrypting using a block cipher, I don't see a header being output describing the original length of the message M?


The usual padding for block ciphers ("PKCS#7 padding") is not a sequence of zeroes, but a sequence of P = N - (X % N) bytes each with value P.

If the message is a multiple of the block size, then a full block of padding is added (where each byte value is the block size).

For example, is the message is 15-byte long and the block size is 16 bytes, than one byte of padding will be added, and the value of the byte is 1. If the message is 14-byte long, two bytes with value 2 will be added. If the message is 16-byte long, sixteen bytes with value 16 will be added.

With these rules, the padding is unambiguous.

  • $\begingroup$ Thanks. But why M|1? And what if the block size is >= 256 bits :-) ? Is your padding scheme the one used for all block ciphers, like AES? $\endgroup$
    – Shuzheng
    Aug 12 '19 at 11:39
  • $\begingroup$ I'm assuming there needs to be 1 byte of padding, thus that padding byte will have value 1. Yes, that doesn't work for block sizes larger than 256 bytes, but most block ciphers have 16-byte block sizes. And yes, this is the PKCS#7 padding, also called PKCS#5 padding $\endgroup$
    – Conrado
    Aug 12 '19 at 11:54
  • $\begingroup$ Ohh, nice - I was assuming N-X bytes of padding, nvm. Is the padding scheme for AES (512 bits) similar? $\endgroup$
    – Shuzheng
    Aug 12 '19 at 11:55
  • $\begingroup$ @Shuzheng it's not exactly N-X, it's the smaller number larger than zero that makes the result size a multiple of the block size. AES has 128-bit block size (e.g. 16 bytes), and it indeed works as described $\endgroup$
    – Conrado
    Aug 12 '19 at 11:58
  • $\begingroup$ Yes, but here N is the block size in bytes, while X is the length of the message to be encrypted. Then indeed, N-X bytes of padding is needed, right? What do you mean by "it's the smaller number larger than..."? $\endgroup$
    – Shuzheng
    Aug 12 '19 at 12:56

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.