Created
June 5, 2017 14:48
-
-
Save cballou/f84690a5fd78ed7ae1ffee694566d212 to your computer and use it in GitHub Desktop.
Mcrypt helper function for padding AES encryption keys to ensure PHP 5.6-7.1 is backwards compatible with PHP <= 5.5.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 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"; | |
$c++; | |
} | |
} | |
return $str; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 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