Migrate PHP function from mcrypt to Openssl

Asked

Viewed 295 times

2

I have a PHP function that uses mcrypt. The problem is that PHP 7.2 no longer accepts mcrypt... Does anyone know how to redo it to get the same result using Openssl?

function Encript($Val, $chave){

    $cifrado = MCRYPT_RIJNDAEL_256;
    $modo = MCRYPT_MODE_ECB;
    $Cript = mcrypt_encrypt($cifrado, $chave, $Val, $modo, mcrypt_create_iv(mcrypt_get_iv_size($cifrado, $modo), MCRYPT_DEV_RANDOM));
    return base64_encode($Cript);

}

function Decript($Val, $chave){

    $Base = base64_decode($Val);

    $cifrado = MCRYPT_RIJNDAEL_256;
    $modo = MCRYPT_MODE_ECB;
    return mcrypt_decrypt($cifrado, $chave, $Base, $modo, mcrypt_create_iv(mcrypt_get_iv_size($cifrado, $modo), MCRYPT_DEV_RANDOM));

}

2 answers

1

There is no port to Openssl. This is because the MCRYPT_RIJNDAEL_256 is not equal to AES-256, He uses a non-standard version. AES always operates with 128-byte blocks, even in AES-256, this does not occur in Mcrypt, which uses larger blocks. AES-256 is more vulnerable than AES-128 in some types of attacks, but the construction of Mcrypt is even less studied, which makes it less safe.

Another observation is the use of the ECB, never use ECB, you can see the penguim riddled. In addition, the mode used does not guarantee integrity of information, it is still possible to change the ciphertext.


You have two options:

1.Use Openssl with AES-256-GCM:

$nonce = random_bytes(openssl_cipher_iv_length("aes-256-gcm")); // Há riscos de colisão devido ao pequeno tamanho!
$cifrado = openssl_encrypt($Val, "aes-256-gcm", $chave, '', $nonce, $tag);

$original = openssl_decrypt($cifrado, "aes-256-gcm", $chave, '', $nonce, $tag);

2.Use Libsodium with Xchacha20poly1305 (recommended):

$nonce = random_bytes(SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES);
$cifrado = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt($Val, '', $nonce, $chave);


$original = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($cifrado, '', $nonce, $chave);

In either of the two it is necessary to decipher and encrypt again, preferably with new keys.

1

Unfortunately, you will need to re-encrypt all your data and actually since PHP 7.1.0, mcrypt_decrypt and mcrypt_encrypt are deprecated, so to solve your problem you need to use openssl_encrypt and openssl_decrypt, something like this.

$string="string";
$chave="chave";
$encrypted_string=openssl_encrypt($string,"AES-128-ECB",$chave);
$decrypted_string=openssl_decrypt($encrypted_string,"AES-128-ECB",$chave);

Just remembering ECB is not totally safe, but it is simple. Documentation :

  • I could have just said, but all right, it went unnoticed.

  • 1

    See if the change meets what you wanted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.