dinsdag 26 februari 2019

How to recreate encryption by MCRYPT_RIJNDAEL_256 in PHP 7.2 and higher.

So with PHP7.2 around the edge and the deprecation of mcrypt, sometimes you still need to be able to encrypt with MCRYPT_RIJNDAEL_256

So I got around this question on stackoverflow: https://stackoverflow.com/questions/54887285/exact-alternate-to-mcrypt-encrypt-in-php-7-2

Researching this issue I found that openssl when it comes to MCRYPT_RIJNDAEL_256 says "Screw you, update your methods". So, the OP already had found a library which could do what he wanted it to do, but somehow the OP was using an outdated version.

This sent me on an experimenting spree which led to the code in the answer, a method to be able to encrypt and decrypt with the MCRYPT_RIJNDAEL_256  method as given in that answer.

To get this answer to work you'll need to incorporate the library phpseclib and install it in your code path.

Then you can use this code to translate the encrypted strings back and forth as you please.
Happy coding!

set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
include('Crypt/Rijndael.php');
include('Crypt/Random.php');
use phpseclib\Crypt\Rijndael as Crypt_Rijndael;
function encryptRJ256($key,$iv,$text)
{
    $cipher = new Crypt_Rijndael('cbc'); 
    $cipher->setBlockLength(256);
    // keys are null-padded to the closest valid size
    // longer than the longest key and it's truncated
    $cipher->setKeyLength(256);
    $cipher->setKey($key);
    // the IV defaults to all-NULLs if not explicitly defined
    $cipher->setIV($iv);
    $cipher->disablePadding();
    $length = strlen($text);
    $pad = 32 - ($length % 32);
    $text = str_pad($text, $length + $pad, chr(0));
    return base64_encode($cipher->encrypt($text));
}
function decryptRJ256($key,$iv,$text)
{
    $cipher = new Crypt_Rijndael('cbc'); // could use CRYPT_RIJNDAEL_MODE_CBC
    $cipher->setBlockLength(256);
    // keys are null-padded to the closest valid size
    // longer than the longest key and it's truncated
    $cipher->setKeyLength(256);
    $cipher->setKey($key);
    // the IV defaults to all-NULLs if not explicitly defined
    $cipher->setIV($iv);
    $cipher->disablePadding();
    return $cipher->decrypt(base64_decode($text)); 
}