How to use AES encryption and decryption with PHP

藏色散人
Release: 2023-04-07 22:22:01
forward
4124 people have browsed it

AES encryption uses the mcrypt_decrypt function in the php5 version. This function has been deprecated after php7.1. It is replaced by openssl's openssl_encrypt and openssl_decrypt, and the code is also very streamlined. Here is the sample code:

Related recommendations: "PHP Tutorial"

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 = [
'key'=>'reter4446fdfgdfgdfg', //加密key 
'iv'=>  md5(time(). uniqid(),true), //保证偏移量为16位
'method'=> 'AES-128-CBC' //加密方式  # AES-256-CBC等
 ];
 
$obj = new Aes($config);
 
$res = $obj->aesEn('aaaddee44');//加密数据
 
echo $res;
echo &#39;<hr>&#39;;
 
echo $obj->aesDe($res);//解密
Copy after login

The above is the detailed content of How to use AES encryption and decryption with PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!