问题
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