'openssl_cipher_iv_length error on php 7.4

how to fix openssl_cipher_iv_length error on php 7.4 its working normally on php 7.2?

    $key = pack('H*','5e4888f3b85db60b53303483581c2b42112788e5e1b2d18c45cf70b867ca0721');
    $method = 'aes-256-ecb'; 
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
    $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
    $encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
    return $encrypted;

in PHP 7.4 i get this error Fatal error: Uncaught Error: Length must be greater than 0
In Php 7.2 Everything is work



Solution 1:[1]

We need add a condition in order to find out if $ivSize is greater than zero. If $ivSize will be return zero $iv will stay empty.

Here is fixed code for PHP 7.4 and newer.

$key = pack('H*','5e4888f3b85db60b53303483581c2b42112788e5e1b2d18c45cf70b867ca0721');
$method = 'aes-256-ecb'; 
$ivSize = openssl_cipher_iv_length($method);
$iv = '';
if ($ivSize > 0) {
    $iv = openssl_random_pseudo_bytes($ivSize);
}
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
return $encrypted;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1