问题描述
如果我在 MAC OSX 开发环境中使用 openssl_encrypt
加密某些内容,则无法在我的 Windows 开发环境中对其进行解密。
一些注意事项:
- 如果我在 Windows 中使用
openssl_encrypt
加密,我也可以在 Windows 中解密它。 - 如果我在 Mac 上加密,我无法在 Windows 中解密,但我可以在 Mac 中解密。
- 我在 Windows 中得到的错误是
error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
。
我已阅读这篇文章:How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption
从这篇文章中,我猜测我使用的是不兼容版本的 openssl_decrypt,但我不确定如何解决这个问题,或者这是否是问题所在。
这是我的代码:
<?PHP
/**
* First,this code works on both Mac and Windows
*/
$cipher = "AES-128-CBC";
$key = 1234567890123456;
$iv = 1234567890123456;
$plaintext = '1234';
$encrypted = openssl_encrypt($plaintext,$cipher,$key,$iv);
if(false === $encrypted)
{
echo openssl_error_string();
die;
}
echo "Plain text: " . $plaintext . "<br>";
echo "Encrypted text: " . $encrypted . "<br><br>";
// on Mac $encrypted = w9oKTqKTtvBuRUVbhQP/qw==
// on Win $encrypted = 19MQn7slHAAdFYR1TJSZxQ==
$decrypted = openssl_decrypt($encrypted,$iv);
$result = $decrypted === $plaintext;
echo "Text was encrypted and decrypted on the same system: ";
print $result ? 'It worked<br><br>' : 'It did not work<br><br>';
// output on both Windows and Mac - It worked
/**
* Code below does not work
*/
// This is the encrypted text the Mac produces
$text_encrypted_mac = 'w9oKTqKTtvBuRUVbhQP/qw==';
$decrypted = openssl_decrypt($text_encrypted_mac,$iv);
$result = $decrypted === $plaintext;
echo "Start with text encrypted on Mac: ";
print $result ? 'It worked<br>' : 'It did not work<br>';
// output on Mac - 'It worked'
// output on Windows - 'It did not work'
// this is the encrypted text I get on Windows
$text_encrypted_win = '19MQn7slHAAdFYR1TJSZxQ==';
$decrypted = openssl_decrypt($text_encrypted_win,$iv);
$result = $decrypted === $plaintext;
echo "Start with text encrypted on Windows: ";
print $result ? 'It worked<br>' : 'It did not work<br>';
// output on Mac - 'It did not work'
// output on Windows - 'It worked'
解决方法
@Sammitch 给了我这个问题的正确答案。我需要将我的 Key 和 IV 放在引号中。所以key和IV的正确代码如下:
$cipher = 'AES-128-CBC';
$key = '1234567890123456';
$iv = '1234567890123456';
$plaintext = '1234';