将 Mcrypt 替换为 OpenSSL
目前,我们在系统上有一个mcrypt,用于在我们的PHP应用程序中加密一些敏感的数据。现在我们有一个新的要求,我们必须将加密模块更改为openssl。另一件重要的事情是,我们正在使用密码河豚和模式ecb。因此,我开始测试什么是差异,以及如何使用openssl解密mcrypt加密字符串。
我使用了标准的PHP函数:
- mcrypt_encrypt与openssl_encrypt
- mcrypt_decrypt与openssl_decrypt
这两种方法都产生了不同的结果。第二件事是,在给定的密码(河豚)和模式(ecb)中,两种类型的IV长度都是必需的(openssl=0和mcrypt=56)。
有谁知道我如何轻松地更改模块而无需进行大量迁移工作?
提前致谢!
更新:
以下是我测试过的代码:
<?php
function say($message){
if(!is_string($message)){
if(!isset($_SERVER["HTTP_USER_AGENT"])) echo "<pre>";
echo var_export($message, true) . ((!isset($_SERVER["HTTP_USER_AGENT"]) ? "\n" : "<br />"));
if(!isset($_SERVER["HTTP_USER_AGENT"])) echo "</pre>";
}else{
echo $message . ((!isset($_SERVER["HTTP_USER_AGENT"]) ? "\n" : "<br />"));
}
}
say("= Begin raw encryption");
$key = "anotherpass";
$str = "does it work";
say(" Params:");
say(" - String to encrypt '".$str."'");
say(" - Key: ".$key);
say("");
$params = array(
"openssl" => array(
"cipher" => "BF",
"mode" => "ECB",
),
"mcrypt" => array(
"cipher" => "blowfish",
"mode" => "ecb",
),
);
say("= Mcrypt");
$handler = mcrypt_module_open($params['mcrypt']['cipher'], '', $params['mcrypt']['mode'], '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($handler), MCRYPT_RAND);
$keysize = mcrypt_enc_get_key_size($handler);
mcrypt_generic_init($handler,$key,"\0\0\0\0\0\0\0\0");
say(" Params:");
say(" - InitVector ".bin2hex($iv)." (bin2hex)");
say(" - Max keysize ".$keysize);
say(" - Cipher ".$params['mcrypt']['cipher']);
say(" - Mode ".$params['mcrypt']['mode']);
say("");
say(" Encryption:");
$m_encrypted = mcrypt_generic($handler, $str);
$m_decrypted = mdecrypt_generic($handler, $m_encrypted);
say(" - Encrypted ".bin2hex($m_encrypted)." (bin2hex)");
say(" - Descrypted ".$m_decrypted);
say("");
say("= Openssl");
say(" Params:");
say(" - InitVector not needed");
say(" - Max keysize ".openssl_cipher_iv_length($params['openssl']['cipher']."-".$params['openssl']['mode']));
say(" - Cipher ".$params['openssl']['cipher']);
say(" - Mode ".$params['openssl']['mode']);
say("");
say(" Encryption:");
$o_encrypted = openssl_encrypt($str,$params['openssl']['cipher']."-".$params['openssl']['mode'],$key,true);
$o_decrypted = openssl_decrypt($o_encrypted,$params['openssl']['cipher']."-".$params['openssl']['mode'],$key,true);
say(" - Encrypted ".bin2hex($o_encrypted)." (bin2hex)");
say(" - Descrypted ".$o_decrypted);
这是我的结果:
= Begin raw encryption
Params:
- String to encrypt 'does it work'
- Key: anotherpass
= Mcrypt
Params:
- InitVector 06a184909d7bf863 (bin2hex)
- Max keysize 56
- Cipher blowfish
- Mode ecb
Encryption:
- Encrypted 0e93dce9a6a88e343fe5f90d1307684c (bin2hex)
- Descrypted does it work
= Openssl
Params:
- InitVector not needed
- Max keysize 0
- Cipher BF
- Mode ECB
Encryption:
- Encrypted 213460aade8f9c14d8d51947b8231439 (bin2hex)
- Descrypted does it work
也许现在有什么想法?
谢谢!