php AES加密解密实例

实例代码



class Aes{
     
	protected $key='';
	protected $iv='';
    /**
     * @param $key
     * @param $iv
     * @return $this
     * 配置 key iv
     */
    public function instance($key,$iv){
     
        $this->key=$key;
        $this->iv=$key;
        return $this;
    }

    /**
     * @param $input
     * @return string
     * 加密
     */
    public function encrypt($input)
    {
     
        $data = openssl_encrypt($input, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->iv));
        $data = base64_encode($data);
        return $data;
    }

    /**
     * @param $input
     * @return string
     * 解密
     */
    public function decrypt($input)
    {
     
        $decrypted = openssl_decrypt(base64_decode($input), 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->iv));
        return $decrypted;
    }

    /**
     * @param $hex
     * @return string
     * hex转换
     */
    public function hexToStr($hex)
    {
     
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2)
        {
     
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }

}

可以直接复制使用,php的aes加密类库

你可能感兴趣的:(php,AES加密,AES解密,php,密码学)