Created
August 24, 2016 05:17
-
-
Save ferdhie/c38e0d6634017bf0daafa5a675114607 to your computer and use it in GitHub Desktop.
PHP MCRYPT AES CBC PKCS padding 5, interchangeable with Java Crypto
This file contains 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 | |
function aes_cbc_encrypt($data, $key) | |
{ | |
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); | |
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM); | |
$key = hash('SHA256', $key, true); | |
$strIn = pkcs5_pad($data); | |
$strCrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $strIn, MCRYPT_MODE_CBC, $iv); | |
return base64_encode($iv.$strCrypt); | |
} | |
function aes_cbc_decrypt($data, $key) | |
{ | |
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); | |
$strIn = base64_decode($data); | |
$key = hash('SHA256', $key, true); | |
$iv = substr($strIn, 0, $size); | |
$strIn = substr($strIn, $size); | |
return pkcs5_unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $strIn, MCRYPT_MODE_CBC, $iv)); | |
} | |
function pkcs5_pad($text) | |
{ | |
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); | |
$pad = $size - (strlen($text) % $size); | |
return $text . str_repeat(chr($pad), $pad); | |
} | |
function pkcs5_unpad($text) | |
{ | |
$pad = ord($text{strlen($text) - 1}); | |
if ($pad > strlen($text)) return false; | |
if (strspn($text, $text{strlen($text) - 1}, strlen($text) - $pad) != $pad) | |
{ | |
return false; | |
} | |
return substr($text, 0, -1 * $pad); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment