zoukankan      html  css  js  c++  java
  • 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,不知道的人会踩坑报错

  • 相关阅读:
    Nginx软件优化
    分布式文件系统---GlusterFS
    内建DNS服务器--BIND
    ESXI 6.5 从载到安装
    在Linux下写一个简单的驱动程序
    TQ2440开发板网络配置方式
    虚拟机Linux下找不到/dev/cdrom
    求最大公约数
    strcmp的源码实现
    转:嵌入式软件工程师经典笔试题
  • 原文地址:https://www.cnblogs.com/clubs/p/12009414.html
Copyright © 2011-2022 走看看