将mcrypt_generic转换为openssl_encrypt

时间:2018-02-15 05:53:43

标签: php openssl mcrypt

PHP不再支持mcrypt。我必须创建一个具有完全相同输出的OpenSSL替代方案,因为我只能访问一半代码库。我的尝试都失败了。如您所见,OS与MC不匹配。我尝试了不同的 $methods 以及OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING的组合。

我哪里错了?

const n = "\n";
$text= 'hello my friends';
$method = 'AES-128-CBC';
$key = base64_decode('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
$text = base64_decode('MDEyMzQ1Njc4OUFCQ0RFRgAAAAYxMjM0NTYxMjMDAwM=');
$size = openssl_cipher_iv_length($method);
$iv = substr($key, 0, $size);

// MCRYPT METHOD
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($module, $key, $iv);
$mcrypt = mcrypt_generic($module, $text);

// OPENSSL METHOD
$method = 'AES-128-CBC';
$openssl = openssl_encrypt($text, $method, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);

echo "MC: " . base64_encode($mcrypt) . n;
echo "OS: " . base64_encode($openssl) . n;

/*
MC: 9+gMhSSAHhJ4g4rdjwP02YQJTfU2qEThBco+W9ob9UU=
OS: Qsz5HitF4X+2DV48wh7ExCjWjGEOAl88MKXk/g24Z/I=
*/

1 个答案:

答案 0 :(得分:3)

Mcrypts: MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC

相当于:

OPENSSL: AES-256-CBC

我不知道为什么会有区别,但改变128 to 256为我解决了这个问题。