Home >Backend Development >PHP7 >How to encrypt php7.0 openssl_encrypt
php5.4版本mcrypt_encryp提升到php7.0 openssl_encrypt,加密字段不一样。
今天有个加密,使用的加密字段和key,加密模式都一样,可是加密后的数据不一样,
这是代码片段
<?php $privateKey = "qewrvxffbfdhsfdgh"; $iv = "234253454354352"; $data = "测试用的数据"; $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv); echo(base64_encode($encrypted)); echo "\n"; >
加密后的数据是gHXA5vo5hEMxjthYNq/gborXWNETPw0rYEb2FspAYzc=
下面是使用php7.0版本以上不支持mcrypt_encryp函数进行加密的代码
<?php $privateKey = "qewrvxffbfdhsfdgh"; $iv = "234253454354352"; $data = "测试用的数据"; $encrypted= openssl_encrypt($data,'aes-128-cbc', $privateKey, OPENSSL_RAW_DATA, $iv); echo(base64_encode($encrypted)); echo "\n"; >
加密后是gHXA5vo5hEMxjthYNq/gbtwwm1TlRzsRBI64TrEo3P8=
1.gHXA5vo5hEMxjthYNq/gborXWNETPw0rYEb2FspAYzc=
2.gHXA5vo5hEMxjthYNq/gbtwwm1TlRzsRBI64TrEo3P8=
是不是不一样,这样加密出来的数据不仔细查看,会认为是一样的数据。
要想保证加密一样,将php7.0的代码修改如下
<?php $privateKey = "qewrvxffbfdhsfdgh"; $iv = "234253454354352"; $data = "测试用的数据"; if (strlen($data) % 16) { $data = str_pad($data,strlen($data) + 16 - strlen($data) % 16, "\0"); } $encrypted= openssl_encrypt($data, 'AES-128-CBC',$privateKey,OPENSSL_NO_PADDING,$iv); echo (base64_encode($encrypted));
加密后的数据是gHXA5vo5hEMxjthYNq/gborXWNETPw0rYEb2FspAYzc=,这样就保持一致了。
本文来自php7教程栏目,欢迎学习。
The above is the detailed content of How to encrypt php7.0 openssl_encrypt. For more information, please follow other related articles on the PHP Chinese website!