mcrypt_decrypt 在解密文本末尾添加 null

mcrypt_decrypt adding null at the end of decrypted text

我使用 Rijndael 算法加密和解密我的数据库密码。我将编码后的密码保存在另一个文件中。在这里,我减少了相关代码:

$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, PASSWORD_SALT, 'mypassword', MCRYPT_MODE_ECB);    
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, PASSWORD_SALT, $encrypted, MCRYPT_MODE_ECB);
// !! The value of $decrypted is "mypassword      " i.e. "mypasswordNULLNULLNULLNULLNULL"

'mypassword' 转换为 'mypassword' + 6xNULL。解密后的代码包含空值。

我在 1 年前写了这段代码,一切正常。但是现在,当所有技术的版本都发生变化时,我遇到了问题。

一直都是这样。

根据文档:

The data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '[=11=]'.

因此,要么你 trim 你的数据 [=10=],要么你必须将原始长度存储在任何地方,然后将填充的 0 剪掉。

使用 Rijndael-128 算法 mcrypt_encrypt() 将始终 return 16 字节的倍数。如果您的纯文本不是 16 字节的精确倍数,则数据将用零字节填充,因此它将是 16 的倍数。

那些零字节也会出现在解密文本中。您必须使用以下方法删除它们:

$decrypted = rtrim($decrypted, "[=10=]");

注1:Rijndael是一种块加密算法,它在固定大小的块上运行。这就是为什么可能需要填充的原因。

注释 2:加密仅适用于永远不会以值 00h 结尾的编码输入(因为默认零填充)。摘自 http://php.net/manual/en/function.mcrypt-encrypt.php

处的示例代码