5

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

jww
  • 97,681
  • 90
  • 411
  • 885
Alexander Pravdin
  • 4,982
  • 3
  • 27
  • 30
  • Do not use ECB mode, it is not secure, see [ECB mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29), scroll down to the Penguin. – zaph Feb 16 '17 at 11:19
  • [PHP replace mcrypt with openssl](http://stackoverflow.com/q/9993909/608639)? – jww Feb 16 '17 at 15:29

1 Answers1

5

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.

Narf
  • 14,600
  • 3
  • 37
  • 66
  • Thank you for your answer. Could you suggest an appropriate random_bytes() length? Could you advise an openssl algorythm similar to or better than Rijndael-256 for regular website use such as passwords encryption? My actual task is not a user password encryption, but similar. – Alexander Pravdin Feb 17 '17 at 09:01
  • There's no universally good length ... it depends on the algorithm. As for the algorithm itself, again - just use a library. – Narf Feb 17 '17 at 09:02