Skip to content

Instantly share code, notes, and snippets.

@defuse
Created March 1, 2015 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save defuse/c197a18a7b5a0667c92d to your computer and use it in GitHub Desktop.
Save defuse/c197a18a7b5a0667c92d to your computer and use it in GitHub Desktop.
PHP Exception Leaks Encryption Key
<?php
// Broken crypto code from https://github.com/slimphp/Slim/blob/develop/Slim/Crypt.php
function validateKeyLength($key, $module)
{
$keySize = strlen($key);
$keySizeMin = 1;
$keySizeMax = mcrypt_enc_get_key_size($module);
$validKeySizes = mcrypt_enc_get_supported_key_sizes($module);
if ($validKeySizes) {
if (!in_array($keySize, $validKeySizes)) {
throw new \InvalidArgumentException('Encryption key length must be one of: ' . implode(', ', $validKeySizes));
}
} else {
if ($keySize < $keySizeMin || $keySize > $keySizeMax) {
throw new \InvalidArgumentException(sprintf(
'Encryption key length must be between %s and %s, inclusive',
$keySizeMin,
$keySizeMax
));
}
}
}
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
validateKeyLength("HEY LOOK THIS IS THE SECRET KEY!!", $module);
/*
PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Encryption key length must be one of: 16, 24, 32' in /tmp/test.php:10
Stack trace:
#0 /tmp/test.php(24): validateKeyLength('HEY LOOK THIS I...', Resource id #4)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#1 {main}
thrown in /tmp/test.php on line 10
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Encryption key length must be one of: 16, 24, 32' in /tmp/test.php:10
Stack trace:
#0 /tmp/test.php(24): validateKeyLength('HEY LOOK THIS I...', Resource id #4)
#1 {main}
thrown in /tmp/test.php on line 10
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment