Rumah >pembangunan bahagian belakang >PHP7 >PHP7 openssl函数替换mcrypt函数加密解密方法
PHP7 openssl函数替换mcrypt函数加密解密
以下是两者的区别及openssl替换mcrypt的方法:
替代
$key = '-2i61^'; $iv = '&11r2(*3'; $data = "123456789"; //要加密的数据 if(PHP_VERSION<5.6){ $a= base64_encode(mcrypt_encrypt(MCRYPT_3DES,$key,$data,MCRYPT_MODE_CBC,$iv)); echo 'mcrypt_encrypt:'.$a.'<br>'; //rtrim 移除字符串右侧的空白字符 $decrypt = rtrim(mcrypt_decrypt(MCRYPT_3DES,$key,base64_decode($a),MCRYPT_MODE_CBC,$iv),'\0'); echo 'mcrypt_decrypt:'.$decrypt.'<br>'; } //使用mcrypt函数来对比 $len = strlen($data); if($len%8){ $data = str_pad($data,$len+8-$len%8,"\0"); }//使用空字符填充字符串的右侧,使字符串位数变为8的倍数 $b = base64_encode(openssl_encrypt($data,'DES-EDE3-CBC',$key,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,$iv)); echo "openssl_encrypt:".$b. '<br>'; $decrypt = openssl_decrypt(base64_decode($b),'DES-EDE3-CBC',$key,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,$iv); echo 'openssl_decrypt:'.$decrypt.'<br>';
运行结果
mcrypt_encrypt:O4/3PssvAkrYtIlhbQEr+g== mcrypt_decrypt:123456789 openssl_encrypt:O4/3PssvAkrYtIlhbQEr+g== openssl_decrypt:123456789
然后来个对比,看看这两个函数的速度:
$key = '-2i61^'; $iv = '&11r2(*3'; $data = "123456789"; if(PHP_VERSION<5.6){ $start = microtime(true); for($i=0;$i<10000;$i++){ $a= base64_encode(mcrypt_encrypt(MCRYPT_3DES,$key,$data,MCRYPT_MODE_CBC,$iv)); } echo 'mcrypt_time:'; echo microtime(true)-$start.'<br>'; echo 'mcrypt_encrypt'.$a.'<br>'; $decrypt = rtrim(mcrypt_decrypt(MCRYPT_3DES,$key,base64_decode($a),MCRYPT_MODE_CBC,$iv),'\0'); echo 'mcrypt_decrypt'.$decrypt.'<br>'; } $start = microtime(true); for($i=0;$i<10000;$i++){ $len = strlen($data); if($len%8){ $data = str_pad($data,$len+8-$len%8,"\0"); } $b = base64_encode(openssl_encrypt($data,'DES-EDE3-CBC',$key,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,$iv)); } echo "openssl_time:"; echo microtime(true)-$start . '<br>'; echo "openssl_encrypt:".$b. '<br>'; $decrypt = openssl_decrypt(base64_decode($b),'DES-EDE3-CBC',$key,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,$iv); echo 'openssl_decrypt'.$decrypt.'<br>';
结果
mcrypt_time:1.8425710201263 mcrypt_encryptO4/3PssvAkrYtIlhbQEr+g== mcrypt_decrypt123456789 openssl_time:0.023201942443848 openssl_encrypt:O4/3PssvAkrYtIlhbQEr+g== openssl_decrypt123456789
本文来自php7教程栏目,欢迎学习。
Atas ialah kandungan terperinci PHP7 openssl函数替换mcrypt函数加密解密方法. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!