3

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?

Linesofcode
  • 5,327
  • 13
  • 62
  • 116

2 Answers2

5

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
);
michail_w
  • 4,318
  • 4
  • 26
  • 43
  • Well, it doesn't seem the problem is on the function since the error remains. I'll accept your answer though because it seems more correct. – Linesofcode Apr 18 '17 at 22:29
  • 1
    Hey, your `$iv` always returns zero. Is that normal? – Linesofcode Apr 19 '17 at 11:00
  • 1
    Looks like for your cipher method does not have any cipher length to init vector. Look at example here: http://ideone.com/TdFnAo – michail_w Apr 19 '17 at 11:15
  • Would you be kind to look at my other post? http://stackoverflow.com/questions/43494466/php-soap-fill-header-credentials – Linesofcode Apr 19 '17 at 11:29
0
echo encrypt_openssl($data, $key);

function encrypt_openssl($msg, $key, $iv = null) {
        $iv_size = openssl_cipher_iv_length('AES-128-ECB');
        if (!$iv) {
            $iv = openssl_random_pseudo_bytes($iv_size);
        }
        $encryptedMessage = openssl_encrypt($msg, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encryptedMessage);
    }