Migrate PHP function from mcrypt to Openssl

1

I have a PHP function that uses mcrypt. The problem is that PHP 7.2 does not accept mcrypt anymore ... Does anyone know how to redo it so as 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));

}
    
asked by anonymous 30.07.2018 / 23:35

2 answers

1

Unfortunately, you will need to re-encrypt all your data, and in fact 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's simple. Documentation :

    
31.07.2018 / 03:29
0

There is no way to port OpenSSL. This is because MCRYPT_RIJNDAEL_256 is not equal to AES-256 , it uses a non-default version. AES always operates with 128-byte size blocks, even in AES-256, this does not occur in MCrypt, which uses larger blocks. AES-256 is more vulnerable than the AES-128 in some types of attacks , but the construction of MCrypt is still less studied, which makes it less secure.

Another note is the use of ECB, never use ECB , you can see the creped penguins . In addition, the mode used does not guarantee information integrity, 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 case, you need to decrypt and encrypt again, preferably with new ones.

    
05.08.2018 / 00:59