TL;DR

Aaaaand weâ€™re at the beginning of the second wave of challenges. Weâ€™re starting with some preparatory work, i.e. implement a padding scheme.

So whatâ€™s padding? If you have 30 centimers long boxes and you want to fit 20 centimeters things, youâ€™ll have to fit some 10 centimeters of stuff to avoid bouncing. Thatâ€™s padding.

So, in our case, we have fixed-size blocks and a generic message to send. We can cut it into blocks, and we will be left with some that will need some padding to fit the final block.

The fun thing is that PKCS#7 is actually not about padding. I mean, it contains a padding algorithm, but itâ€™s much more! Anyway, this is padding:

the input is padded at the trailing end with one of the following strings:

``````         01 -- if lth mod k = k-1
02 02 -- if lth mod k = k-2
.
.
.
k k ... k k -- if lth mod k = 0
``````

`lth` represents the length of the payload.

Itâ€™s mildly interesting that padding is always present, even if the message fit exactly in an integer number of blocks in the first place. In this case, we add a full block of padding, just like sending an empty box (or, better, a box without anything of interest). This lets us distinguish the case in which we would actually want to send something that might be misinterpreted as padding.

Soâ€¦ letâ€™s remember that with this padding scheme we might end up with tossing away the entire last block.

Well, easy done with Perl:

``````sub pkcs7_pad (\$input, \$blen) {
die "unsupported block length\n" if \$blen >= 256;
my \$ilen = length \$input;
my \$npad = \$blen - (\$ilen % \$blen);