php OpenSSL 加解密

时间:2022-11-17 19:19:30

2018-1-6 17:10:19 星期六

 $data = '123456';
$openssl_method = 'AES-256-CBC';
$openssl_iv_length = openssl_cipher_iv_length($openssl_method);
$openssl_iv = openssl_random_pseudo_bytes($openssl_iv_length);
$openssl_password = openssl_random_pseudo_bytes(16); echo '<pre>';
// 加密
$e = openssl_encrypt($data, $openssl_method, $openssl_password, 0, $openssl_iv);
echo openssl_error_string (); //解密
$f = openssl_decrypt($e, $openssl_method, $openssl_password, 0, $openssl_iv);
echo openssl_error_string ();
var_dump($e, $f);

注意:

1. 加密后输出是base64编码后的结果, 可以直接输出到客户端

2. $options 有 OPENSSL_RAW_DATA 时, 输出的是加密后的原始结果, 没有用base64编码

3. $options 有 OPENSSL_ZERO_PADDING 时, 要求被加密的数据必须是"加密块"长度的整数倍