PHP AES对称加密
代码类:
class AES
{
//设置AES秘钥
private $key = 'e2xfv2vG0cvloi';
public function __construct($key = "")
{
$this->setKey($key);
}
/**
* 设置密钥
* @param $key 密钥
*/
public function setKey($key){
$key = trim($key);
if($key){
$this->key = $key;
}
}
/**
* 加密
* @param string $str 要加密的数据
* @return bool|string 加密后的数据
*/
public function encrypt($str) {
$data = openssl_encrypt($str, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
$data = base64_encode($data);
return $data;
}
/**
* 解密
* @param string $str 要解密的数据
* @return string 解密后的数据
*/
public function decrypt($str) {
$decrypted = openssl_decrypt(base64_decode($str), 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
return $decrypted;
}
}