PHP如何使用AES加密和解密
AES加密在php5的版本中使用的mcrypt_decrypt 函数,该函数已经在php7.1后弃用了,取而代之的是openssl的openssl_encrypt和openssl_decrypt,并且代码也非常精简,下面是示例代码:
<?php
class Aes
{
public $key = ‘‘;
public $iv = ‘‘;
public $method = ‘‘;
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 = [
‘key‘ => ‘reter4446fdfgdfgdfg‘, //加密key
‘iv‘ => md5(time() . uniqid(), true), //保证偏移量为16位
‘method‘ => ‘AES-128-CBC‘ //加密方式 # AES-256-CBC等
];
$obj = new Aes($config);
$res = $obj->aesEn(‘‘);//加密数据
echo $res;
echo ‘<hr>‘;
echo $obj->aesDe($res);//解密注意:要使用openssl相关函数必须要开启openssl扩展,否则程序报错

链接:https://www.php.cn/php-weizijiaocheng-437570.html(文章没有提示要开启openssl,不知道的人会踩坑报错)
相关推荐
MXstudying 2019-07-01
我的程序员人生 2015-07-28
puddingpp 2019-06-27
IT日志 2017-04-19
githubphpnobug 2016-10-26
tengyuan 2020-05-30
visionzheng 2020-05-04
LowisLucifer 2020-04-30
dbhllnr 2020-04-26
wordmhg 2020-03-27
wbingyang 2020-02-14
CloudXli 2020-01-12
ahnuzfm 2019-12-24
hgzhang 2019-10-22
数据与算法之美 2015-03-09
frankwtq 2012-02-02
guohewei 2019-03-28