0

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?

Shuzheng
  • 321
  • 1
  • 2
  • 7

1 Answers1

4

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.

Conrado
  • 6,414
  • 1
  • 29
  • 44
  • 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? – Shuzheng Aug 12 '19 at 11:39
  • 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 – Conrado Aug 12 '19 at 11:54
  • Ohh, nice - I was assuming N-X bytes of padding, nvm. Is the padding scheme for AES (512 bits) similar? – Shuzheng Aug 12 '19 at 11:55
  • @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 – Conrado Aug 12 '19 at 11:58
  • 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..."? – Shuzheng Aug 12 '19 at 12:56
  • @Shuzheng Sorry, I just realized that you specified that the block size is larger than the message. Otherwise, if N is 16 and X is 31, then N-X=-15 but 1 byte of padding is needed. The size of the padding is basically N - (X % N). – Conrado Aug 12 '19 at 13:05
  • Ahh, thanks for clarifying this. – Shuzheng Aug 12 '19 at 13:09
  • Remember, one can use also, M100...000 – kelalaka Aug 12 '19 at 18:05