类的基础用法
2020-09-01 11:07:37 来源:admin 点击:751
//AES-CBC加减密类 ,类中静态static方法不能使用私有变量
class Aes {
private $hex_iv = '00000000000000000000000000000000'; # converted C byte code in to HEX and placed it here
private $key = '3sffeexxfgas'; #Same as in C
//不是静态类方法,所以可以使用$this->key
public function encrypt($input)
{
$data = openssl_encrypt($input, 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->hex_iv));
$data = base64_encode($data);
return $data;
}
public function decrypt($input)
{
$decrypted = openssl_decrypt(base64_decode($input), 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->hex_iv));
return $decrypted;
}
function hexToStr($hex)
{
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2)
{
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
}
$pwd = new Aes();
echo $pwd->encrypt('asdasd');
echo '<hr/>';
echo $pwd->decrypt('93m8CEacf+p9XRh/j8pKlQ==');
//AES-ECB加减密类 ,类中静态static方法不能使用私有变量
class Aes
{
public static function encrypt($string, $key)
{
// openssl_encrypt 加密不同Mcrypt,对秘钥长度要求,超出16加密结果不变
$data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
return base64_encode($data);
}
public static function decrypt($string, $key)
{
return openssl_decrypt(base64_decode($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
}
}
$pwd = new Aes();
echo $pwd->encrypt('asdasd','397e2e');
echo '<hr/>';
echo $pwd->decrypt('sn5B2HOXgkZPufr01BvG3A==','397e2e');