Search code examples
phpencryptionopensslmcrypt

Converting mcrypt_encrypt to openssl_encrypt in PHP


As mcrypt_encrypt is removed from PHP 8, I need to convert the following code to using openssl_encrypt

function encryptValue($input,$sKey)
{   
    $key = hex2bin($sKey);
    
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
    $pad = $block - (strlen($input) % $block);
    $input .= str_repeat(chr($pad), $pad);
    
    $encrypted_text = bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $input, MCRYPT_MODE_ECB));  

    return $encrypted_text;
}

I have it replaced by the following:

function encryptData($input, $sKey)
    {
        $key= hex2bin($sKey);

        $encrypted_text = bin2hex(openssl_encrypt($input, 'AES-256-ECB', $key, OPENSSL_RAW_DATA));
        return $encrypted_text;
    }

As openssl does default padding, I did not pad the plaintext like in the original code. I believe the secret key is being converted to binary. If I leave out the key conversion from both code, then I get the same encrypted text. But if I use the key conversion, then the encrypted texts are different.

If I remove the below code from both, then both returns the same encrypted text.

$key= hex2bin($sKey);

But without this, it will not work with the external API.


Solution

  • Your code "$key .= chr(hexdec($sKey[$i].$sKey[$i+1]))" is a "hexstring to string" converter, e.g. the input "31323334353637386162636465666768" gets converted to "12345678abcdefgh".

    Now everything depends on the key length - when using my sample string you have a 16 characters/bytes long AES key that is good for AES-128 and not AES-256 as you used in your function.

    Using a doubled input key will need AES-256 in your openssl-code.

    It could be helpful if you could give a sample key with resulting ciphertext if my answer didn't solve your problem.