使用PHP7.1的openssl加解密AES-128-CBC,与7.0之前的版本匹配

因为老版本与线上环境的mcrypt不兼容,在php7.1上使用会报错,官网也说了:Warning
This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.
这里贴上解决办法。
先上7.0之前的代码:


class Security
{
    public static function encrypt($input, $key, $iv) {
        $localIV = $iv;
        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
        mcrypt_generic_init($module, $key, $localIV);
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $input = Security::pkcs5_pad($input, $size);
        $data = mcrypt_generic($module, $input);

        mcrypt_generic_deinit($module);
        mcrypt_module_close($module);
        $data = base64_encode($data);
        return $data;
    }

    private static function pkcs5_pad ($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    public static function decrypt($sStr, $key, $iv) {
        $localIV = $iv;
        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
        mcrypt_generic_init($module, $key, $localIV);
        $encryptedData = base64_decode($sStr);
        $encryptedData = mdecrypt_generic($module, $encryptedData);

        $dec_s = strlen($encryptedData);
        $padding = ord($encryptedData[$dec_s-1]);
        $decrypted = substr($encryptedData, 0, -$padding);

        mcrypt_generic_deinit($module);
        mcrypt_module_close($module);
        if(!$decrypted){
            throw new Exception("Decrypt Error,Please Check SecretKey");
        }
        return $decrypted;
    }
}

$key = 'abcdefghijklmnop'; // 16位(也可以不是16位,但当它大于16位时,7.1的openssl函数会截取前16位,有点坑)
$iv = '1234567890123456'; // 16位

echo '用来加密的串:------------------------';
echo $str = '中文数字123字母ABC符号!@#$%^&*()';

echo '
用7.1之前的mcrypt加密:------------------------'
; echo $strEncode = Security::encrypt($str, $key, $iv); echo '
用7.1之前的mcrypt解密:------------------------'
; echo Security::decrypt($strEncode, $key, $iv);

然后是7.1的:

echo '
用PHP 7.1的openssl加密:------------------------'
; echo base64_encode(openssl_encrypt($str, 'aes-128-cbc', $key, true, $iv)); echo '
用PHP 7.1的openssl解密:------------------------'
; echo openssl_decrypt(base64_decode($strEncode), 'aes-128-cbc', $key, true, $iv);

输出结果:

用来加密的串:------------------------中文数字123字母ABC符号!@#$%^&*()7.1之前的mcrypt加密:------------------------l73zMo3B2Q73cXvPUjlgWNSJJKYWxOx3dj1f4E/Ml3LGa43mY2xHkqqf3HiyohIb7.1之前的mcrypt解密:------------------------中文数字123字母ABC符号!@#$%^&*()PHP 7.1openssl加密:------------------------l73zMo3B2Q73cXvPUjlgWNSJJKYWxOx3dj1f4E/Ml3LGa43mY2xHkqqf3HiyohIbPHP 7.1openssl解密:------------------------中文数字123字母ABC符号!@#$%^&*()

你可能感兴趣的:(php,php,openssl)