-3

I have encryption code as below & it was working in PHP version 5.6. But it is not working in PHP version 7.2.

**

Warning : Use of undefined constant MCRYPT_RIJNDAEL_128 - assumed 'MCRYPT_RIJNDAEL_128' (this will throw an Error in a future version of PHP)

**

Any alternative of this?

$serviceid="2951";
$secretkey = "fQ5FHy0qzM6ljp97";

function pkcs5_pad ($text, $blocksize)
{
  $pad = $blocksize - (strlen($text) % $blocksize);
  return $text . str_repeat(chr($pad), $pad);
}

function encrypt($plaintext, $key) {
    $plaintext = pkcs5_pad($plaintext, 16);
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_ECB);
    $ciphertext_base64 = base64_encode($ciphertext);
    $ciphertext_base64; 
}
$data = $serviceid;
$auth= encrypt($data ,$secretkey); 

Value of encryption is AGchNk2xOnHHxhgYv02XJw==

I tried with below code in PHP 7.2

function encrypt($plaintext, $key) 
{
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-128-cbc'));
$encrypted = openssl_encrypt($plaintext, 'aes-128-cbc', $key, 0, $iv);
return base64_encode($encrypted . '::' . $iv);
}

but output keeps changing

Jay Doshi
  • 666
  • 1
  • 5
  • 16
  • Define "not working". Do you get any errors, warnings or notices? Or unexpected results? – El_Vanja May 12 '21 at 13:32
  • Anyways, a quick look at the [documentation](https://www.php.net/manual/en/function.mcrypt-encrypt) should clear the issue. – El_Vanja May 12 '21 at 13:33
  • @El_Vanja I added warning in question. Warning : Use of undefined constant MCRYPT_RIJNDAEL_128 - assumed 'MCRYPT_RIJNDAEL_128' (this will throw an Error in a future version of PHP) – Jay Doshi May 12 '21 at 13:35
  • As already answered "mcrypt" was removed from PHP 7.2.x. As your mcrypt encryption uses AES (= Rijndael 128) the **ECB** mode you should use this with OpenSSL as well (so leave out all code regarding the "iv" (initialization vector). – Michael Fehr May 12 '21 at 14:59

2 Answers2

3

As you can see into documentation mcrypt_encrypt is REMOVED from PHP 7.2.0

Here an SO question for best alternative

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
  • Is this okay? function encrypt($plaintext, $key) { $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-128-cbc')); $encrypted = openssl_encrypt($plaintext, 'aes-128-cbc', $key, 0, $iv); return base64_encode($encrypted . '::' . $iv); } – Jay Doshi May 12 '21 at 14:12
-1

I have found solution of my query. Please check below

function encrypt($plaintext,$key)
{
    return base64_encode(openssl_encrypt($plaintext, 'aes-128-ecb', $key, OPENSSL_RAW_DATA));
}
Jay Doshi
  • 666
  • 1
  • 5
  • 16