Search code examples
encryptionopensslmcryptphp-7.3

How to migrate Mcrypt to openssl function to encrypt with PHP7.3


Unfortunately 7.3 doesn't support mcrypt and I have to refactor some code. I cannot migrate this encription function:

mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, pkcs5_pad(trim($strToEncode), mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB)), MCRYPT_MODE_ECB, $iv);

I tried this code:

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

$cipher = "aes-128-gcm";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$block_size = strlen(openssl_encrypt('', $cipher, '', OPENSSL_RAW_DATA, $iv));
$ciphertext = openssl_encrypt(pkcs5_pad(trim($strToEncode),$block_size), $cipher, $key, $options=0, $iv);

But it doesn't work and I got: Uncaught DivisionByZeroError in pkcs5_pad function


Solution

  • This is the working code:

    $cipher = "aes-128-ecb";
    $ciphertext = openssl_encrypt(trim($strToEncode), $cipher, $key, OPENSSL_RAW_DATA);