復制粘貼即可使用~~!
封裝一個類
<?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); }