利用php加密库 mcrypt 进行AES加密解密
//AES加密类
class AESMcrypt {
public $iv = null; //秘钥向量
public $key = null; //加密key
public $bit = 128;
public $mode= null;//加密模式
private $cipher;
public function __construct($bit, $key, $iv, $mode) {
if(empty($bit) || empty($key) || empty($iv) || empty($mode)){
return NULL;
}
$this->bit = $bit;
$this->key = $key;
$this->iv = $iv;
$this->mode = $mode;
switch($this->bit) {
case 192:$this->cipher = MCRYPT_RIJNDAEL_192; break;
case 256:$this->cipher = MCRYPT_RIJNDAEL_256; break;
default: $this->cipher = MCRYPT_RIJNDAEL_128;
}
switch($this->mode) {
case 'ecb':$this->mode = MCRYPT_MODE_ECB; break;
case 'cfb':$this->mode = MCRYPT_MODE_CFB; break;
case 'ofb':$this->mode = MCRYPT_MODE_OFB; break;
case 'nofb':$this->mode = MCRYPT_MODE_NOFB; break;
case 'cbc':$this->mode = MCRYPT_MODE_CBC; break;
default: $this->mode = MCRYPT_MODE_CBC;
}
}
public function encrypt($data) {
$data = base64_encode(mcrypt_encrypt( $this->cipher, $this->key, $data, $this->mode, $this->iv));
return $data;
}
public function decrypt($data) {
$data = mcrypt_decrypt( $this->cipher, $this->key, base64_decode($data), $this->mode, $this->iv);
$data = rtrim(rtrim($data), "\x00..\x1F");
return $data;
}
}
在ThinkPHP3.2中的使用方法
把加密类放在第三方类库目录中
image.png
在公共函数中调用
/**
* AES加密
* @param [string] $str 要加密的字符串
* @return [string] $str 加密后的字符串
*/
function encrypt($str){
Vendor('AES.AESMcrypt');
$config = C('AES');
$bit = $config['bit'];
$key = $config['key'];
$iv = $config['iv'];
$mode = $config['mode'];
$aes = new AESMcrypt($bit, $key, $iv,$mode);
$str = $aes->encrypt($str);
return $str;
}
/**
* AES解密
* @param [string] $str 要解密的字符串
* @return [string] $str 解密后的字符串
*/
function decrypt($str){
Vendor('AES.AESMcrypt');
$config = C('AES');//config中的配置
$bit = $config['bit'];
$key = $config['key'];
$iv = $config['iv'];
$mode = $config['mode'];
$aes = new AESMcrypt($bit, $key, $iv,$mode);
$str = $aes->decrypt($str);
return $str;
}
config配置文件
//注意cbc模式key和iv必须是长度为16的字符串
'AES' => array(
'bit' => 128,
'key' => 'woshiwangjiewang',//加解密key
'iv' => 'wangjieshiwowang',//秘钥向量
'mode' => 'cbc',//加密模式
),
接下来就可以在ThinkPHP中的直接调用encrypt()和decrypt()传入字符串进行加密解密了。
encrypt('我是王杰');
加密后
// WLnz+cbKlkoI40BD8R4e/Q==
decrypt('WLnz+cbKlkoI40BD8R4e/Q==');
解密后
我是王杰
可以用下面的代码来检测系统是否安装了 mcrypt 模块,并查看支持哪些加密算法和模式
$cipher_list = mcrypt_list_algorithms();//mcrypt支持的加密算法列表
$mode_list = mcrypt_list_modes(); //mcrypt支持的加密模式列表
var_dump($cipher_list);
var_dump($mode_list);
网友评论