类:
class AES
{
protected $method;
protected $secret_key;
protected $iv;
protected $options;
protected $seed; //根据种子生成加密的key
public function __construct($method,$seed,$iv,$options=OPENSSL_RAW_DATA)
{
// key是必须要设置的
$this->secret_key = $this->_sha1prng($seed);
$this->method = $method; //算法 eg. 'AES-128-CBC'
$this->iv = $iv; //iv 向量
$this->options = $options;
}
/**
* 根据种子生成key
*/
private function _sha1prng($seed)
{
return substr(openssl_digest(openssl_digest($seed, 'sha256', true), 'sha256', true), 0, 16); //具体 sha256 可以替换成sha1
}
/**
* 加密方法,对数据进行加密,返回加密后的数据 非base64字符串
*
* @param string $data 要加密的数据
*
* @return string
*
*/
public function encrypt($data)
{
return openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
/**
* 解密方法,对数据进行解密,返回解密后的数据 非base64字符串
*
* @param string $data 要解密的数据
*
* @return string
*
*/
public function decrypt($data)
{
return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
}