天天看點

php7使用AES對稱加密算法

對稱加密算法:AES,可逆(DES的替代者)

話不多說。直接上代碼

<?php
 
namespace app\common;
 
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 還不是很清楚
     * 使用意見。背景請使用 AES-128-ECB API傳輸加密建議使用 AES-128-CBC 并攜帶IV向量。必備
     *
     */
    public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
    {
        // key是必須要設定的
        $this->secret_key = isset($key) ? $key : '132465';
 
        $this->method = $method;
 
        $this->iv = $iv;
 
        $this->options = $options;
    }
 
    /**
     * 加密方法,對資料進行加密,傳回加密後的資料
     *
     * @param string $data 要加密的資料
     *
     * @return string
     *
     */
    public function encrypt($data)
    {
        $aesValue = openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
        return urlsafe_b64encode($aesValue);
    }
 
    /**
     * 解密方法,對資料進行解密,傳回解密後的資料
     *
     * @param string $data 要解密的資料
     *
     * @return string
     *
     */
    public function decrypt($data)
    {
        $data = urlsafe_b64decode($data);
        return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
    }
}
           

urlsafe_b64decode 和 urlsafe_b64encode實作如下

function urlsafe_b64encode ($string) {
    $data = base64_encode ($string);
    $data = str_replace ( array('+', '/', '=') , array('-', '_', '') , $data );
    return $data;
 }
// URL安全的字元串解碼:
function urlsafe_b64decode ($string) {
    $data = str_replace ( array('-', '_') , array('+', '/') , $string );
    $mod4 = strlen ($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
 }
           

使用範例(Thinkphp6)

$aes = new OpenSSLAES($this->key);
    //加密
    $aesValue = $aes->encrypt('123465456465');
	//解密
    $value = $aes->decrypt($aesValue);