本文实例讲述了PHP实现的AES加密、解密封装类与用法。分享给大家供大家参考,具体如下:
Aes类文件(aes.php):
<?php
class Aes{
public $key = '';
public $iv = '';
public function __construct($config){
foreach($config as $k => $v){
$this->$k = $v;
}
}
//加密
public function aesEn($data){
return base64_encode(openssl_encrypt($data, $this->method,$this->key, OPENSSL_RAW_DATA , $this->iv));
}
//解密
public function aesDe($data){
return openssl_decrypt(base64_decode($data), $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
}
}
配置文件(Config.php):
<?php
$aes_config = [
'key' => 'A42EAC0C2B408472', //加密key
'iv' => md5(time().uniqid(),true), //保证偏移量为16位
'method'=> 'AES-128-CBC' //加密方式 # AES-256-CBC等
];
加密、解密调用方法:
<?php
require_once('Config.php');
require_once('aes.php');
$obj = new Aes($aes_config);
$res = $obj->aesEn('https://www.baidu.com');//加密数据
echo '加密结果:'.$res;
echo '<hr>';
echo '解密结果:'.$obj->aesDe($res);//解密