登录

AES-128-ECB 加解密 PHP7.3以上兼容版本

php笔记
0 2084
yle="max-width:100%;overflow-x:auto;">/**
 * @desc:php aes加密解密类
 * @author
 */
class SecurityException
{
// 加密方式:openssl
    private $cipher = 'AES-128-ECB';
// MCRYPT_RAND  MCRYPT_DEV_RANDOM  MCRYPT_DEV_URANDOM
    protected static $key;
    /*
    构造函数
    @param key 密钥
    */

    public function __construct($key){
        $this->key = $key;
    }

    private function getiv()
    {
        $cipher = $this->cipher;
        $ivlen = openssl_cipher_iv_length($cipher);//向量长度
        $iv = openssl_random_pseudo_bytes($ivlen);//创建指定长度的向量
        return $iv;

    }

    /**AES-128-ECB
     * @param $data
     * @return string
     */
    public function encrypt($data)
    {
        $cipher = $this->cipher;
        $key = $this->key;
        $iv = $this->getiv();
        $encryption_key = base64_decode($key);
        $encrypted = openssl_encrypt($data $cipher $encryption_key OPENSSL_RAW_DATA $iv);
        $ret = base64_encode($encrypted . '::' . $iv);
        return $ret;

    }

    /**AES-128-ECB
     * @param $data
     * @return false|string
     */
    public function decrypt($data)
    {
        $cipher = $this->cipher;
        $key = $this->key;
        $iv = $this->getiv();
        $encryption_key = base64_decode($key);
        $arr = explode('::' base64_decode($data));
        $encrypted_data = $arr[0];
        $ret = openssl_decrypt($encrypted_data $cipher $encryption_key OPENSSL_RAW_DATA $iv);
        return $ret;
    }


}


发表评论

0 个回复