Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decrypt a string with OpenSSL which was previously encrypted with mcrypt?

Since mcrypt was deprecated in PHP 7.1 and I have a lot of data encrypted/decrypted with mcrypt in existing project, how to migrate my PHP code from mcrypt to OpenSSL? I have the following code to encrypt:

$encoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, 'salt', 'source string', MCRYPT_MODE_ECB));

And decryption code is:

$source = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, 'salt', base64_decode('encoded string'), MCRYPT_MODE_ECB);

What openssl_ functions should I use in the above examples to get the same results without encoded data conversion?

Or the only way is to run a script which will decrypt all my stored encrypted data with mcrypt and encode with openssl?

Thanks

like image 903
Alexander Pravdin Avatar asked Feb 16 '17 04:02

Alexander Pravdin


People also ask

What replaced mcrypt?

It was removed from PHP 7.2 and moved to an unofficial PECL extension because the mcrypt library is no longer maintained. For PHP 7.2+, PHP instead uses libsodium as a cryptography library. New PHP code should be written to use libsodium rather than mcrypt.

Is mcrypt secure?

Don't use mcrypt . Although it's possible to provide a relatively secure cryptography library that builds on top of mcrypt (the earlier version of defuse/php-encryption did), switching your code to openssl will provide better security, performance, maintainability, and portability.

What is mcrypt library?

mcrypt is a replacement for the popular Unix crypt command. crypt was a file encryption tool that used an algorithm very close to the World War II Enigma cipher. Mcrypt provides the same functionality but uses several modern algorithms such as AES.


1 Answers

OpenSSL doesn't have the Rijndael-256 cipher; there's no equivalent - you'll have to decrypt and re-encrypt everything.

But also:

  • You're missing padding and authentication.
  • Don't use ECB mode.
  • "salt" is not a proper encryption key, nor is any regular string. Use random_bytes() to generate your keys, with the proper key length for the chosen algorithm.

All of the above can be summed up like this: don't do it on your own, use a well-vetted library like defuse/php-encryption.

Cryptography is no simple thing and you can't do it properly with just 5 lines of code.

like image 197
Narf Avatar answered Oct 12 '22 01:10

Narf