.NET AES 填充模式更改加密数据大小
我不一定有问题,我更好奇。如果我将 AES 填充模式设置为 PKCS7,并加密长度为 128 的 byte[]
,则输出的 byte[]
长度为 144。
var input = new string('0', 128);
var inputBytes = Encoding.UTF8.GetBytes(input);
using var aes = Aes.Create();
Console.WriteLine(aes.BlockSize); // 128 (bits)
aes.Padding = PaddingMode.PKCS7;
using var encryptedMessageStream = new MemoryStream();
using (var cryptoStream = new CryptoStream(encryptedMessageStream, aes.CreateEncryptor(), CryptoStreamMode.Write, leaveOpen: true))
{
cryptoStream.Write(inputBytes);
}
var encryptedBytes = encryptedMessageStream.ToArray(); // 144 length
如果我不做任何更改,期望将填充模式切换为 None
,那么加密字节的长度将为 128(与我的输入长度相同)。因此,即使我的输入数据没有改变,并且输入长度可以被 AES 块大小(8 字节)整除,填充模式也会改变最终输出。据我的理解,它不应该,因为我的输入长度可以被 AES 块大小整除。那么为什么 PKCS7
和 None
会给出不同的输出大小呢?
当通过解密运行两种模式时,我很好地得到了原始消息。
I don't necessarily have a problem, I am more curious. If I set the AES padding mode to PKCS7
, and encrypt a byte[]
of length 128, the output byte[]
is length 144.
var input = new string('0', 128);
var inputBytes = Encoding.UTF8.GetBytes(input);
using var aes = Aes.Create();
Console.WriteLine(aes.BlockSize); // 128 (bits)
aes.Padding = PaddingMode.PKCS7;
using var encryptedMessageStream = new MemoryStream();
using (var cryptoStream = new CryptoStream(encryptedMessageStream, aes.CreateEncryptor(), CryptoStreamMode.Write, leaveOpen: true))
{
cryptoStream.Write(inputBytes);
}
var encryptedBytes = encryptedMessageStream.ToArray(); // 144 length
If I change nothing expect switch the padding mode to None
, then the encrypted bytes will have length 128 (same length as my input). So even though my input data has not changed, and the input length is evenly divisible by the AES block size (8 bytes), the padding mode is changing the final output. As far as my understanding goes, it shouldn't, because, my input length is evenly divisible by the AES block size. So why would PKCS7
, and None
be giving different output sizes?
When running both modes through decryption, I get the original message back just fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PKCS 填充要求至少添加一个字节的填充:
因此,虽然您可能认为圆块大小的明文需要零字节,但这不是有效的填充量,因为最小数量是 1 字节。 (对此的解释是,否则解密器无法区分恰好以
0x01
结尾的圆块大小的明文和用单个填充的短一字节的明文0x01。)
PKCS padding requires that at least one byte of padding be added:
So, while you may feel that your round-block-size plaintext requires zero bytes, that's not a valid amount of padding because the minimum number is 1 byte. (The explanation of this is that otherwise it's impossible for the decipherer to differentiate between a round-block-size plaintext that happens to end in
0x01
and a one byte shorter plaintext that's padded with a single0x01
.)