PHP7 openssl函数替换mcrypt函数加密解密方法

2019年7月5日15:06:19 发表评论 171 views

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.'
'
;

    //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

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: