您的当前位置:首页>全部文章>文章详情

php的AES加密解密类

发表于:2023-02-27 22:54:29浏览:160次TAG: #AES #加密 #解密 #加密传输数据
<?php
namespace app\common\utils;
/**
 * AES加密解密类
 */
class Aes
{
    /**
     * 模式
     */
    const METHOD = 'AES-128-ECB';
    /**
     * 生成密钥
     * @return false|string
     */
    public static function key()
    {
        $str1='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str1);
        $rands = substr($randStr,0,16);
        return $rands;
    }

    /**
     * 加密
     * @param $data
     * @param $aes_key
     * @return string
     */
    public static function encrypt($data,$aes_key)
    {
        $data = trim($data);
        $method = self::METHOD;
        $ivlen = openssl_cipher_iv_length($method);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $encrypt_data = openssl_encrypt($data, $method,$aes_key, OPENSSL_RAW_DATA , $iv);
        return base64_encode($encrypt_data);
    }
    /**
     * 解密
     * @param $encrypt_data
     * @param $aes_key
     * @return false|string
     */
    public static function decrypt($encrypt_data,$aes_key)
    {
        $encrypt_data = base64_decode($encrypt_data);
        $method = self::METHOD;
        $ivlen = openssl_cipher_iv_length($method);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $decrypt_data = openssl_decrypt($encrypt_data,$method,$aes_key,OPENSSL_RAW_DATA,$iv);
        return $decrypt_data;
    }
}

/**
 * 调用
 * 示例
 * 密钥(16位):YVI3qKPrbjyR0BoO
 * 明文:你好,大字节
 * 密文:Zi6fZM4fcQnr0AJfgAd0w1n0Gre4K5adjF6r8vStXz4=
 */
// 加密
$encrypt_data = \app\dazijie\utils\Aes::encrypt('你好,大字节','YVI3qKPrbjyR0BoO');
// 解密
$decrypt_data = \app\dazijie\utils\Aes::decrypt('Zi6fZM4fcQnr0AJfgAd0w1n0Gre4K5adjF6r8vStXz4=','YVI3qKPrbjyR0BoO');