If I encrypt something with openssl_encrypt
in my MAC OSX development environment, I cannot unencrypt it in my Windows devlopment environment.
- My Mac development environment is using MAMP for OSX running PHP 7.4.2.
- My Windows development environment is using MAMP for Windows running PHP 7.4.2.
A few notes:
- If I encrypt with
openssl_encrypt
in Windows I can also decypt it in Windows. - If I encrypt it on Mac I cannot decrypt it in Windows, but I can decrypt it in Mac just fine.
- The error I get in windows is
error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
.
I have read this post: How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption
And from this article I'm guessing that I am using incompatible versions of openssl_decrypt but I'm not sure how to remedy this or if this is even the issue.
Here is my code:
<?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, 0, $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, $cipher, $key, 0, $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, $cipher, $key, 0, $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, $cipher, $key, 0, $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'