Home>Article>Backend Development> PHP7 openssl function replaces mcrypt function encryption and decryption method

PHP7 openssl function replaces mcrypt function encryption and decryption method

silencement
silencement Original
2019-06-04 15:01:21 3565browse

PHP7 openssl function replaces mcrypt function encryption and decryption method

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.'
'; //rtrim 移除字符串右侧的空白字符 $decrypt = rtrim(mcrypt_decrypt(MCRYPT_3DES,$key,base64_decode($a),MCRYPT_MODE_CBC,$iv),'\0'); echo 'mcrypt_decrypt:'.$decrypt.'
'; } //使用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. '
'; $decrypt = openssl_decrypt(base64_decode($b),'DES-EDE3-CBC',$key,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,$iv); echo 'openssl_decrypt:'.$decrypt.'
';

运行结果

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.'
'; echo 'mcrypt_encrypt'.$a.'
'; $decrypt = rtrim(mcrypt_decrypt(MCRYPT_3DES,$key,base64_decode($a),MCRYPT_MODE_CBC,$iv),'\0'); echo 'mcrypt_decrypt'.$decrypt.'
'; } $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 . '
'; echo "openssl_encrypt:".$b. '
'; $decrypt = openssl_decrypt(base64_decode($b),'DES-EDE3-CBC',$key,OPENSSL_RAW_DATA|OPENSSL_NO_PADDING,$iv); echo 'openssl_decrypt'.$decrypt.'
';

结果

mcrypt_time:1.8425710201263 mcrypt_encryptO4/3PssvAkrYtIlhbQEr+g== mcrypt_decrypt123456789 openssl_time:0.023201942443848 openssl_encrypt:O4/3PssvAkrYtIlhbQEr+g== openssl_decrypt123456789

本文来自php7教程栏目,欢迎学习。

The above is the detailed content of PHP7 openssl function replaces mcrypt function encryption and decryption method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn