Search code examples
phpopensslmcrypt

PHP convert MCRYPT_ENCRYPT to OPENSSL_ENCRYPT (SOAP header)


I need to encrypt some SOAP header fields, and I currently have the following code working in a project with PHP 5.6 version.

function getBaseEncoded($data, $key)
{
    $size       = $this->pkcs5_pad($data, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
    $iv         = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $result     = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $size, MCRYPT_MODE_ECB, $iv);

    return trim(base64_encode($result));
}

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

What happens is that now I have in my hands a similiar project but with PHP 7, and the function MCRYPT is deprecated and I need to switch it to OPENSSL_ENCRYPT.

The code below is my first attempt:

function getBaseEncoded($data, $key)
{
    $result = openssl_encrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);

    return trim(base64_encode($result));
}

But I'm now receiving a SOAP error with the message

SoapFault => Could not connect to host

and it got me thinking if the problem is on my new function?


Solution

  • You are missing some initializator vector data.

    $ivsize = openssl_cipher_iv_length('AES-128-ECB');
    $iv = openssl_random_pseudo_bytes($ivsize);
    
    $ciphertext = openssl_encrypt(
            $data,
            'AES-128-ECB',
            $key,
            OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
            $iv
    );