Created
August 5, 2018 12:32
-
-
Save senowbar/7626409708eadf92e6904795acba7aac to your computer and use it in GitHub Desktop.
AES encryption and decryption
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 | |
class Aes | |
{ | |
private static $key = 'your_key'; | |
private static $iv = 'your_iv'; | |
public static function encrypt($data) | |
{ | |
return base64_encode(mcrypt_encrypt( | |
MCRYPT_RIJNDAEL_128, | |
self::$key, | |
self::pkcs5_pad($data), | |
MCRYPT_MODE_CBC, | |
self::$iv | |
)); | |
} | |
public static function decrypt($data) | |
{ | |
$str = mcrypt_decrypt( | |
MCRYPT_RIJNDAEL_128, | |
self::$key, | |
base64_decode($data), | |
MCRYPT_MODE_CBC, | |
self::$iv | |
); | |
return self::pkcs5_unpad($str); | |
} | |
private static function pkcs5_pad($text) | |
{ | |
$blocksize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); | |
$pad = $blocksize - (strlen($text) % $blocksize); | |
return $text . str_repeat(chr($pad), $pad); | |
} | |
private static function pkcs5_unpad($text) | |
{ | |
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); | |
$pad = ord($text[($len = strlen($text)) - 1]); | |
$len = strlen($text); | |
$pad = ord($text[$len - 1]); | |
return substr($text, 0, strlen($text) - $pad); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment