我继承了一个PHP 5.X时代编码的项目。该站点目前正在PHP 7.1上运行,并使用MCRYPT库进行加密和解密功能。
我需要升级到PHP 7.2,这意味着再见MCRYPT!
不熟悉加密会导致尝试转换为OPENSSL的问题
下面是当前使用的代码。
function decrypt($encryptedText)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$enc = base64_decode($encryptedText);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $enc, MCRYPT_MODE_ECB, $key), "\x80");
}
function encrypt($plaintext)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$inputLength = strlen($plaintext);
$blockCount = floor($inputLength / $blockSize);
$padding = ($blockCount + 1) * $blockSize - $inputLength;
$paddedPlainText = str_pad($plaintext, $inputLength + $padding, "\x80", STR_PAD_RIGHT);
$enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $paddedPlainText, MCRYPT_MODE_ECB, $key);
return base64_encode($enc);
}
我已经查看了其他几篇StackOverflow帖子,它们涉及了从MCRYPT转换为OPENSSL的确切主题,根据我所阅读的所有内容,我想到了以下代码,该代码不起作用。
function decrypt($encryptedText)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$ivsize = openssl_cipher_iv_length('AES-128-ECB');
$iv = openssl_random_pseudo_bytes($ivsize);
$enc = base64_decode($encryptedText);
return trim(openssl_decrypt($enc, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
}
function encrypt($plaintext)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$ivsize = openssl_cipher_iv_length('AES-128-ECB');
$iv = openssl_random_pseudo_bytes($ivsize);
$enc = openssl_encrypt($plaintext, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
return base64_encode($enc);
}
我不确定,但是我感觉到问题与旧加密功能中的文本填充有关,这导致新代码无法正常工作。如果确实存在问题,我不知道如何将其集成到OPENSSL函数中。
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$inputLength = strlen($plaintext);
$blockCount = floor($inputLength / $blockSize);
$padding = ($blockCount + 1) * $blockSize - $inputLength;
$paddedPlainText = str_pad($plaintext, $inputLength + $padding, "\x80", STR_PAD_RIGHT);
再次,不熟悉加密,感谢任何/所有帮助,所以我可以弄清楚并理解我在做什么错。
这是我的SSl课程。试试看:
class Ssl
{
private $cipher = "aes-128-gcm";
private $options = 0;
/**
* @param string $plaintext
* @return array
*/
public function encrypt($plaintext)
{
$key = \openssl_random_pseudo_bytes(16);
$ivlen = \openssl_cipher_iv_length($this->cipher);
$iv = \openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $this->cipher, $key, $this->options, $iv,$tag);
return array(
'key' => \bin2hex($key),
'iv' => \bin2hex($iv),
'tag' => \bin2hex($tag),
'ciphertext' => $ciphertext,
);
}
/**
* @param string $json
* @return false|string
*/
public function decrypt($json, $key)
{
$data = \json_decode($json);
$result = \openssl_decrypt($data->ciphertext, $this->cipher, \hex2bin($key), $this->options, \hex2bin($data->iv), \hex2bin($data->tag));
return \json_decode($result, true);
}
}