Skip to content

Instantly share code, notes, and snippets.

@roshanpal
Created July 16, 2015 04:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save roshanpal/37acd854a889f7b73a1c to your computer and use it in GitHub Desktop.
Save roshanpal/37acd854a889f7b73a1c to your computer and use it in GitHub Desktop.
PHP AES Encryption/Decryption Class with PKCS5 padding
<?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