Created
July 16, 2015 04:33
-
-
Save roshanpal/37acd854a889f7b73a1c to your computer and use it in GitHub Desktop.
PHP AES Encryption/Decryption Class with PKCS5 padding
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 | |
/** | |
* Created by PhpStorm. | |
* User: roshan | |
* Date: 4/5/15 | |
* Time: 2:46 PM | |
*/ | |
class Aes | |
{ | |
private static $key = 'YourKeyxxxxxxxxx'; | |
private static $iv = 'YourIvxxxxxxxxxx'; | |
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