Cryptopals 9 - Implement PKCS#7 padding

TL;DR

Challenge 9 in Cryptopals.

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);
   return $input . (chr($npad) x $npad);
}

There is really nothing more to add, so stay safe and secure!


Comments? Octodon, , GitHub, Reddit, or drop me a line!