Skip to content

Instantly share code, notes, and snippets.

@meglio
Created October 27, 2012 17:12
Show Gist options
  • Save meglio/3965357 to your computer and use it in GitHub Desktop.
Save meglio/3965357 to your computer and use it in GitHub Desktop.
Enc/Dec AES 256 CBC, with data consistency validation
private static function iv()
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
return mcrypt_create_iv($iv_size, MCRYPT_RAND);
}
static function encrypt($str, $key32)
{
# Prepend 4-chars data hash to the data itself for validation after decryption
$str = substr(md5($str), 0, 4).$str;
# Prepend $iv to decrypted data
$iv = self::iv();
$enc = $iv.mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key32, $str, MCRYPT_MODE_CBC, $iv);
return base64_encode($enc);
}
static function decrypt($str, $key32)
{
$str = base64_decode($str);
if ($str === false || strlen($str) < 32)
return null;
$iv = substr($str, 0, 32);
$encrypted = substr($str, 32);
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key32, $encrypted, MCRYPT_MODE_CBC, $iv), "\0");
if ($decrypted === false || is_null($decrypted) || strlen($decrypted) < 4)
return null;
$dataHash = substr($decrypted, 0, 4);
$data = substr($decrypted, 4);
if (substr(md5($data), 0, 4) !== $dataHash)
return null;
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment