Skip to content

Instantly share code, notes, and snippets.

@ineersa
Last active December 28, 2015 16:59
Show Gist options
  • Save ineersa/7532738 to your computer and use it in GitHub Desktop.
Save ineersa/7532738 to your computer and use it in GitHub Desktop.
<?php
class AES
{
public static function aes128Encrypt($key, $data) {
if(16 !== strlen($key)) $key = hash('MD5', $key, true);
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16)));
}
public static function aes256Encrypt($key, $data) {
if(32 !== strlen($key)) $key = hash('SHA256', $key, true);
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16)));
}
public static function aes128Decrypt($key, $data) {
if(16 !== strlen($key)) $key = hash('MD5', $key, true);
$data = base64_decode($data);
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
$padding = ord($data[strlen($data) - 1]);
return substr($data, 0, -$padding);
}
public static function aes256Decrypt($key, $data) {
if(32 !== strlen($key)) $key = hash('SHA256', $key, true);
$data = base64_decode($data);
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
$padding = ord($data[strlen($data) - 1]);
return substr($data, 0, -$padding);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment