Cryptopals 15 - PKCS#7 padding violation


Challenge 15 in Cryptopals.

This challenge gets us back on building some additional tools that will be useful at a later stage. In this case, it’s the missing part that we didn’t code for CBC-mode decryption, i.e. the validation and removal of the PCKS#7 padding at the end.

Here’s the implementation in Perl:

sub validate_pkcs7_pad ($input, $blen) {
   my $exception = "invalid padding\n";
   my $len = length $input;
   die $exception if $len == 0 || $len % $blen;
   my $lastc = substr $input, -1, 1;
   my $npad = ord($lastc);
   die $exception if $npad == 0 || $npad > $blen;
   my $trail = $lastc x $npad;
   die $exception if substr($input, -$npad, $npad) ne ($lastc x $npad);
   substr $input, 0, $len - $npad;

I admit on getting it wrong in the first place, because I didn’t account for an all-padding block at the end.

The text for the exception is, defensively, always the same and we’re using a variable to make sure of it. You know, with all these oracle attacks around, we can never be sure of how much info we’re giving out by just providing different error messages for different error conditions.

There are three ways to fail the validation:

  • the input’s length is 0 or not a multiple of the block size, OR
  • the length of the padding is invalid (i.e. 0 or greater than the block size), OR
  • the padding itself is invalid, i.e. not formed according to the rules.

Stay safe and secure!

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