A client came to us needing to migrate some data from existing Laravel 4 project to Laravel 5. This was tricky due to the old system using Mcrypt with Rijndael 256 cipher. Mcrypt has finally been deprecated in PHP 7.1 and we thus did not want to install a deprecated PHP module. To get round this we used an old PHP library called phpCrypt. Once we had a copy of the library and the Original API key we could create a phpCrypt object as follows:
include_once(base_path('lib/phpcrypt/phpCrypt.php')); use PHP_Crypt\PHP_Crypt as PHP_Crypt; // API Key from Laravel 4 system $oldApiKey = '...'; // Create a new Crypt Object with our old API key $phpCrypt = new PHP_Crypt($oldApiKey, PHP_Crypt::CIPHER_RIJNDAEL_256, PHP_Crypt::MODE_CBC);
To decrypt the data we first need to check how Laravel 4 stores and encrypts. Looking at Illuminate\Encryption\Encrypter encrypt function we see:
$iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer()); $value = base64_encode($this->padAndMcrypt($value, $iv)); // Once we have the encrypted value we will go ahead base64_encode the input // vector and create the MAC for the encrypted value so we can verify its // authenticity. Then, we'll JSON encode the data in a "payload" array. $mac = $this->hash($iv = base64_encode($iv), $value); return base64_encode(json_encode(compact('iv', 'value', 'mac')));
So we have several steps to undo. Working back from the last line we end up with the following decrypt code:
// Decrypt old data for new $originalData = '...'; $payload = json_decode(base64_decode($originalData), true); $value = base64_decode($payload['value']); $iv = base64_decode($payload['iv']); $this->phpCrypt->IV($iv); $decryptedData = $this->phpCrypt->decrypt($value); $pad = ord($decryptedData[($len = strlen($decryptedData)) - 1]); $data = unserialize(substr($decryptedData, 0, $len - $pad));
Note we decide to ignore the mac checking and have expanded the contents of padAndMcrypt.
This snippet allow us to successfully decrypt the old data from Laravel 4, which intern could be encrypted with a new algorithm in the new Laravel 5 application.
Comments are closed.