PHP7 openssl函數替換mcrypt函數加密解密方法

2020-07-16 10:06:12

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),'');
    echo 'mcrypt_decrypt:'.$decrypt.'<br>';
} //使用mcrypt函數來對比



$len = strlen($data);
if($len%8){
    $data = str_pad($data,$len+8-$len%8,"");
}//使用空字元填充字串的右側,使字串位數變為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),'');
    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,"");
    }
    $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教學欄目,歡迎學習。

以上就是PHP7 openssl函數替換mcrypt函數加密解密方法的詳細內容,更多請關注TW511.COM其它相關文章!