lockdown
lockdown

Reputation: 1496

In PHP How would you validate PKCS#7 padding?

I know that in Python you would do something along the lines of this to check the validation of the PKCS#7 padding:

pad = ord(plaintext[-1]); 
/* get the last N bytes of the plaintext */ 
all_padding = plaintext[-pad:];
for byte in all_padding:
    assert byte == pad

Is there a working example in PHP somewhere using ECB/CBC ciphertext? Or does anyone know how to implement the changes to make this PHP?

Upvotes: 1

Views: 456

Answers (1)

lockdown
lockdown

Reputation: 1496

After monkeying around a bit with what I knew about python I have come to this result which seems to be working correctly for me using CBC encryption:

$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypt, MCRYPT_MODE_CBC, $iv);
$padLength = ord($result[strlen($result)-1]);
$padBytes  = substr($result, -1 * $padLength);
if (strlen($padBytes) != $padLength || count(array_count_values(str_split($padBytes))) != 1) {
     throw new Exception('invalid padding!');
 }
 return $result;

Upvotes: 1

Related Questions