<?php
class AES
{
/**
* @param $key string 加密KEY
* @param $iv string 加密向量
* @param $data string 需要加密的数据
* @return string
*/
public static function encrypt($key, $iv, $data)
{
/**
* 打开加密
*/
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");
/**
* 初始化加密
*/
mcrypt_generic_init($td, $key, $iv);
/**
* 加密
*/
//$encrypted = mcrypt_generic($td, $data);
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($data) % $block);
$data .= str_repeat(chr($pad), $pad);
$encrypted = mcrypt_generic($td, $data);
/**
* 清理加密
*/
mcrypt_generic_deinit($td);
/**
* 关闭
*/
mcrypt_module_close($td);
return base64_encode($encrypted);
}
/**
* @param $key string 加密KEY
* @param $iv string 偏移量
* @param $data string 加密的数据
* @return string
*/
public static function decrypt($key, $iv, $data)
{
/**
* 打开加密
*/
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128,"",MCRYPT_MODE_CBC,"");
/**
* 初始化加密
*/
mcrypt_generic_init($td, $key, $iv);
$decode = base64_decode($data);
/**
* 解密
*/
// $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
// $pad = $block - (strlen($data) % $block);
// $data .= str_repeat(chr($pad), $pad);
$dencrypted = mdecrypt_generic($td, $decode);
/**
* 清理加密
*/
mcrypt_generic_deinit($td);
/**
* 关闭
*/
mcrypt_module_close($td);
return static::strippadding($dencrypted);
}
private static function strippadding($string) {
$slast = ord(substr($string, -1));
$slastc = chr($slast);
$pcheck = substr($string, -$slast);
if (preg_match("/$slastc{" . $slast . "}/", $string)) {
$string = substr($string, 0, strlen($string) - $slast);
return $string;
} else {
return false;
}
}
}
?>