tp5簡單學會 AES加密


復制粘貼即可使用~~!

 

封裝一個類

<?php
/*
 * @Author: zsz
 * @Date: 2020-11-13 10:45:07
 * @LastEditTime: 2020-11-27 16:27:07
 */


namespace app\common\secret;


class Aes
{
    /**
     * var string $method 加解密方法,可通過openssl_get_cipher_methods()獲得
     */
    protected $method;

    /**
     * var string $secret_key 加解密的密鑰
     */
    protected $secret_key;

    /**
     * var string $iv 加解密的向量,有些方法需要設置比如CBC
     */
    protected $iv;

    /**
     * var string $options (不知道怎么解釋,目前設置為0沒什么問題)
     */
    protected $options;

    /**
     * 構造函數
     *
     * @param string $key 密鑰
     * @param string $method 加密方式
     * @param string $iv iv向量
     * @param mixed $options 還不是很清楚
     *
     */
    public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
    {
        // key是必須要設置的
        $this->secret_key = isset($key) ? $key : 'morefun';

        $this->method = $method; // 密碼算法

        $this->iv = $iv;

        $this->options = $options;
    }

    /**
     * 加密方法,對數據進行加密,返回加密后的數據
     *
     * @param string $data 要加密的數據
     *
     * @return string
     *
     */
    public function encrypt($data)
    {
        return openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
    }

    /**
     * 解密方法,對數據進行解密,返回解密后的數據
     *
     * @param string $data 要解密的數據
     *
     * @return string
     *
     */
    public function decrypt($data)
    {
        return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
    }
}

 

測試

public function index()
    {
        $str = 555;
        $aes = new Aes("secret");   // 該參數為key
        $encode = $aes->encrypt($str);
        echo $encode;
        echo $aes->decrypt($encode);
    }

 


免責聲明!

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



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