Why do we have to always attach a 16x 0x10 pad even though the last block is already at block-length?
1 Answer
You are talking about the PKCS#7 padding. There is a simple reason; assume that when the last block is full and you don't apply the padding before encryption and then send the message.
When decrypting, the receiver needs to see a padding pattern to remove the padding. What if the last byte is 01
of the message? is it padding or the message itself? Similarly with low probability same if the last bytes are 0202
, and so on.
Instead of this, padding with 10
for an additional extra plaintext block solves the problem.
There are no reasons to perform this particular kind of padding if the plaintext size is known in advance. It may also not be required if the size of the plaintext can be determined by other means. For instance, ASCII encoded text will generally not contain a byte set to zero, so zero-byte padding may be used if the text is not a multiple of the block size. PKCS#7 padding can however always be removed deterministically, independently of the contents of the message.
Many modes, especially streaming modes such as the popular CTR (counter) mode and derivatives - such as the authenticated GCM mode - do not require padding at all; they operate on plaintext bytes rather than plaintext blocks.
-
$\begingroup$ Do we attach that to every message or only on those which are the multiple of the blocksize? $\endgroup$– NimeJan 21, 2019 at 17:10
-
2$\begingroup$ @Nime Take a look at the link in kelalaka's answer, the padding is explained. Short answer : The value of the bytes you add is the number of bytes you need to add in hexa (so
10
is only for message who are multiple of the blocksize, but other messages are also padded, with other values) $\endgroup$– FaulstJan 21, 2019 at 17:18 -
1$\begingroup$ @kelalaka I think there is a typo in your answer, it's not PKCS1.5 padding, but PKCS#5 (or PKCS#7, depending on who you asked) $\endgroup$– FaulstJan 21, 2019 at 17:19
-
3$\begingroup$ And corrected again, PKCS#5 is for 8 byte block ciphers only, as explained here - changed it into PKCS#7 and put some reasons down below when PKCS#7 compatible padding is not required. @Faulst No, for AES it is always PKCS#7; if you'd ask this and they'd reply PKCS#5 compatible padding they'd be wrong. $\endgroup$– Maarten Bodewes ♦Jan 21, 2019 at 17:50
-
$\begingroup$ @MaartenBodewes yes, it is my hex mistake :). Thanks for the nice additions. $\endgroup$– kelalakaJan 21, 2019 at 17:55