用openssl_encrypt替换mcrypt

时间:2018-03-20 13:50:57

标签: php openssl mcrypt

我正在尝试更新一个与php 7.1一起使用的函数,该函数弃用了mcrypt。

原始功能是:

function encryptNET3DES($key, $vector, $text) {        
    $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
    $key_add = 24 - strlen($key);
    $key .= substr($key, 0, $key_add);
    $text_add = strlen($text) % 8;
    for ($i = $text_add; $i < 8; $i++) {
        $text .= chr(8 - $text_add);
    }
    mcrypt_generic_init($td, $key, $vector);
    $encrypt64 = mcrypt_generic($td, $text);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return base64_encode($encrypt64);
}

我尝试的是:

function encryptNET3DESssl($key, $vector, $text) {        
    $key_add = 24 - strlen($key);
    $key .= substr($key, 0, $key_add);
    $text_add = strlen($text) % 8;
    for ($i = $text_add; $i < 8; $i++) {
        $text .= chr(8 - $text_add);
    }
    $encrypt64 = openssl_encrypt($text, 'des-ede3-cbc', $key, OPENSSL_RAW_DATA, $vector);
    return base64_encode($encrypt64);
}

我跑的时候:

$security_token = 'Z6AlpD35lEphQCaljt+MwKHjk9K0/KKd';
$key = base64_decode($security_token);
$iv = base64_decode(substr(date('ymdhis'), 1) . '=');
$string = '31ArmandoQuitoEstebanBlanco1234567-9unmail@dominio.com123456789Av.Sin Nombre 00001234.50685835353.3048hs'.date("Y-m-dh:i:s");

$normal = encryptNET3DES($key, $iv, $string);
$ssl = encryptNET3DESssl($key, $iv, $string);

var_dump($normal);
var_dump($ssl);

结果是:

index.php:12:string 'kaOlYwfRa8jCYYxYVqGJClf27ok2zzemeYTdTmvnDULKX8QvE6XL2DpNKgMMWKzz8+WYawXpQzhZ0UYlijIHjpM6tofE/65VaivNZd+P2w3Od+3iCGCwqKAsJAiezZesuMk+13OmaGVFG7cmt67AV1AgNTZVZCpPcGn3rx4J5LQ=' (length=172)
index.php:13:string 'kaOlYwfRa8jCYYxYVqGJClf27ok2zzemeYTdTmvnDULKX8QvE6XL2DpNKgMMWKzz8+WYawXpQzhZ0UYlijIHjpM6tofE/65VaivNZd+P2w3Od+3iCGCwqKAsJAiezZesuMk+13OmaGVFG7cmt67AV1AgNTZVZCpPcGn3rx4J5LToK7ummSyDXw==' (length=184)

我可以看到它们在最后10个字符之前是相同的,所以我的猜测是我错过了某些参数,因为我的开放ssl加密与mcrypt加密相同。

1 个答案:

答案 0 :(得分:2)

使用openssl时无需填充文本,这将自动处理。

将您的代码更改为以下内容,两种方法都会产生相同的结果:

function encryptNET3DESssl($key, $vector, $text) {        
  $key_add = 24 - strlen($key);
  $key .= substr($key, 0, $key_add);

  $encrypt64 = openssl_encrypt($text, 'des-ede3-cbc', $key, OPENSSL_RAW_DATA, $vector);
  return base64_encode($encrypt64);
}