openssl_error_string() for PHP 在 Windows 开发环境中不起作用

问题描述

如果我在 MAC OSX 开发环境中使用 openssl_encrypt 加密某些内容,则无法在我的 Windows 开发环境中对其进行解密。

  • 我的 Mac 开发环境将 MAMP 用于运行 PHP 的 OSX 7.4.2.
  • 我的 Windows 开发环境使用 MAMP for Windows 运行 PHP 7.4.2。

一些注意事项:

  • 如果我在 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';

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...