16

Mcrypt function has been deprecated as of PHP 7.1.0.

My deprecated string encode / decode functions:

$key: secret key
$str: string


$encoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $str, MCRYPT_MODE_CBC, md5(md5($key))));

$decoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($str), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

Can you suggest some alternatives?

Tibi
  • 163
  • 1
  • 1
  • 6
  • 1
    You're out out of luck here. You're using a Rijndael-256 cipher, which is very unusual and not supported by OpenSSL. What you probably meant is AES-256, which is Rijndael-128 with a 256 bit key. If switching ciphers is an option for you, switch to Rijndael-128, in which case you can use OpenSSL. – NikiC Jan 19 '17 at 13:40
  • why not just use sha-256 *(sha version 2)* – TheCrazyProfessor Feb 23 '17 at 14:43
  • Possible duplicate of [mcrypt is deprecated, what is the alternative?](https://stackoverflow.com/questions/41272257/mcrypt-is-deprecated-what-is-the-alternative) – kenorb Jan 05 '18 at 21:38

5 Answers5

18

You should use openssl_encrypt instead.

Aleksa Arsić
  • 524
  • 1
  • 8
  • 16
  • 1
    Encrypt example: http://micmap.org/php-by-example/en/function/openssl_encrypt , Decrypt example: http://micmap.org/php-by-example/en/function/openssl_decrypt – Milad Ghiravani Feb 07 '18 at 13:41
1

Consider using defuse or RNCryptor, they provide a complete solution, are being maintained and is correct.

zaph
  • 111,848
  • 21
  • 189
  • 228
1

For MCRYPT_RIJNDAEL_256 I posted a full answer for PHP7.3 here: https://stackoverflow.com/a/53937314/243782

snippet:

works like this with the phpseclib library

$rijndael = new \phpseclib\Crypt\Rijndael(\phpseclib\Crypt\Rijndael::MODE_ECB);
$rijndael->setKey(ENCRYPT_KEY);
$rijndael->setKeyLength(256);
$rijndael->disablePadding();
$rijndael->setBlockLength(256);

$decoded = $rijndael->decrypt($term);
Pentium10
  • 204,586
  • 122
  • 423
  • 502
1
echo encrypt_openssl($str, $key);

function encrypt_openssl($msg, $key, $iv = null) {
        $iv_size = openssl_cipher_iv_length('AES-256-CBC');
        if (!$iv) {
            $iv = openssl_random_pseudo_bytes($iv_size);
        }
        $encryptedMessage = openssl_encrypt($msg, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encryptedMessage);
    }

mcrypt may be removed in PHP 7.1 alternative openssl

-2

As mentioned above, open_ssl is a good alternative for mcrypt. The only problem I had with open_ssl, is that it cannot be used for large strings.

I wrote a script (static class), which overcomes this problem (large strings are split up in chunks and encrypted/decrypted separately in the background).

See public gist: https://gist.github.com/petermuller71/33616d55174d9725fc00a663d30194ba