Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AES128 / AES256 CBC with PKCS7Padding in PHP
<?
function aes128_cbc_encrypt($key, $data, $iv) {
if(16 !== strlen($key)) $key = hash('MD5', $key, true);
if(16 !== strlen($iv)) $iv = hash('MD5', $iv, true);
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
}
function aes256_cbc_encrypt($key, $data, $iv) {
if(32 !== strlen($key)) $key = hash('SHA256', $key, true);
if(16 !== strlen($iv)) $iv = hash('MD5', $iv, true);
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
}
function aes128_cbc_decrypt($key, $data, $iv) {
if(16 !== strlen($key)) $key = hash('MD5', $key, true);
if(16 !== strlen($iv)) $iv = hash('MD5', $iv, true);
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$padding = ord($data[strlen($data) - 1]);
return substr($data, 0, -$padding);
}
function aes256_cbc_decrypt($key, $data, $iv) {
if(32 !== strlen($key)) $key = hash('SHA256', $key, true);
if(16 !== strlen($iv)) $iv = hash('MD5', $iv, true);
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$padding = ord($data[strlen($data) - 1]);
return substr($data, 0, -$padding);
}
@somnathbaksi

This comment has been minimized.

Copy link

@somnathbaksi somnathbaksi commented Jul 27, 2013

Nice ,,, keep it up

@bojanmartin

This comment has been minimized.

Copy link

@bojanmartin bojanmartin commented May 15, 2014

I'm not sure if there's another page explaining the context of this gist. For anyone who got here without context (e.g. from Google) - like I did - please note that creating an IV using str_repeat("\0", 16) makes this code absolutely not production-ready! See Block cipher mode of operation at Wikipedia for more details. In short, "In CBC mode, the IV must... be unpredictable at encryption time."

@texelate

This comment has been minimized.

Copy link

@texelate texelate commented Jan 16, 2015

@jruizinmind

This comment has been minimized.

Copy link

@jruizinmind jruizinmind commented Jan 27, 2017

Superb!

@demenvil

This comment has been minimized.

Copy link

@demenvil demenvil commented Apr 17, 2018

Nice ty !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment