PHP如何使用AES加密和解密


AES加密在php5的版本中使用的mcrypt_decrypt 函數,該函數已經在php7.1后棄用了,取而代之的是openssl的openssl_encrypt和openssl_decrypt,並且代碼也非常精簡,下面是示例代碼:

 1 <?php
 2 
 3 class Aes
 4 {
 5     public $key = '';
 6     public $iv = '';
 7     public $method = '';
 8 
 9     public function __construct($config)
10     {
11         foreach ($config as $k => $v) {
12             $this->$k = $v;
13         }
14     }
15 
16     //加密
17     public function aesEn($data)
18     {
19         return base64_encode(openssl_encrypt($data, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv));
20     }
21 
22     //解密
23     public function aesDe($data)
24     {
25         return openssl_decrypt(base64_decode($data), $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
26     }
27 }
28 
29 $config = [
30     'key' => 'reter4446fdfgdfgdfg', //加密key
31     'iv' => md5(time() . uniqid(), true), //保證偏移量為16位
32     'method' => 'AES-128-CBC' //加密方式  # AES-256-CBC等
33 ];
34 $obj = new Aes($config);
35 $res = $obj->aesEn('admin@123');//加密數據
36 echo $res;
37 echo '<hr>';
38 echo $obj->aesDe($res);//解密

注意:要使用openssl相關函數必須要開啟openssl擴展,否則程序報錯

 

鏈接:https://www.php.cn/php-weizijiaocheng-437570.html(文章沒有提示要開啟openssl,不知道的人會踩坑報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM