PHP convert MCRYPT_ENCRYPT to OPENSSL_ENCRYPT (SOAP header)

强颜欢笑 提交于 2020-06-12 08:47:30

问题


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?


回答1:


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
);



回答2:


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);
    }


来源:https://stackoverflow.com/questions/43482840/php-convert-mcrypt-encrypt-to-openssl-encrypt-soap-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!