PHP中AES加密解密類
阿新 • • 發佈:2018-11-28
我們在工作中會遇到各種加密,下面就是PHP中AES加密解密的類
<?php 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); } } $aes = new Aes('123456'); $str = 'www.codelovers.cn程式設計愛好者之家'; $encrypted = $aes->encrypt($str); echo '要加密的字串:'.$str.'<br>加密後的字串:', $encrypted, '<hr>'; $decrypted = $aes->decrypt($encrypted); echo '要解密的字串:', $encrypted, '<br>解密後的字串:', $decrypte
輸出結果如下圖:
更多內容請參考原文連結:https://www.codelovers.cn/article/20181123173030.html