Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Mcrypt helper function for padding AES encryption keys to ensure PHP 5.6-7.1 is backwards compatible with PHP <= 5.5.
* Pad an AES encrypted key to ensure it's of valid size according
* to specification. This function is backwards compatible with
* PHP <= 5.5 and is intended for usage with PHP 5.6+.
function pad_aes($str) {
$c = strlen($str);
$validLengths = array(16, 24, 32);
foreach ($validLengths as $l) {
if ($c === $l) return $str;
while ($c < $l) {
$str .= "\0";
return $str;
* Example of using the pad_aes() helper function to ensure your
* mcrypt_encrypt() and mcrypt_decrypt() functions use appropriately
* sized key lengths.
// invalid key of length 15
$key = 'abcdefghijklmni';
// our secret message for two-way encryption
$message = 'hello, world!';
// demonstration of encryption and decryption
$iv = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, pad_aes($key), $message, MCRYPT_MODE_CBC, $iv);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, pad_aes($key), $encrypted, MCRYPT_MODE_CBC, $iv);
// example demonstrating that the decrypted message still has padding
var_dump('SECRET: ' . $message);
var_dump('DECRYPTED WITH PADDING: ' . $decrypted);
// strip off null byte padding
$stripped = rtrim($decrypted, "\0");
var_dump('DECRYPTED: ' . $stripped);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.