2
votes

PHP no longer supports mcrypt. I have to make an OpenSSL alternative that has the exact same output as I only have access to half the code base. My attempts have all failed. As you can see below OS doesn't match MC. I've tried different $methods and combinations of OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING.

Where am I going wrong?

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
@jww Thanks, though I was skeptical at finding an answer after about a day of troubleshooting this and searching all over the internet I found the solution here: stackoverflow.com/questions/45218465/… Michael Butler: "In your specific example I've found that by changing aes-128-ecb to aes-256-ecb, it produces the same output as the legacy mcrypt_encrypt." Appreciate it! - J. Smith
Not sure if this helps anyone else, but I am converting an old library and my problem was missing the OPENSSL_RAW_DATA option on openssl_encrypt. - Ben

1 Answers

4
votes

Mcrypts: MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC

is equivalent to:

OPENSSL: AES-256-CBC

I have no idea why there's the difference, but changing the 128 to 256 solved it for me.