【发布时间】:2013-11-14 19:56:37
【问题描述】:
我在 C# 中设置了一个简单的对称 AES-en/解密,但我遇到了填充问题。根据MSDN,PKCS #7 的填充字节应该是0x07,但在我的情况下它只是零字节(0x00)。
这怎么可能?似乎这在 .NET 中没有正确实现...
这是我的代码:
Aes aes = new AesManaged();
aes.Key = new byte[] { /* ... */ };
aes.IV = new byte[] { /* ... */ };
// Debugging shows:
// aes.Padding = PaddingMode.PKCS7
// the data to encrypt (1 byte only, to demonstrate padding)
byte[] plainData = new byte[1] { 0xFF };
byte[] encData;
// (encrypt)
using (MemoryStream encStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(encStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(plainData, 0, plainData.Length);
}
encData = encStream.ToArray();
}
// (new length is 16 bytes (128 bits), incl. padding)
plainData = new byte[16];
// (decrypt)
using (MemoryStream decrStream = new MemoryStream(encData))
{
using (CryptoStream cryptoStream = new CryptoStream(decrStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
cryptoStream.Read(plainData, 0, plainData.Length);
}
}
// output:
// 16 bytes,
// 1st byte = 0xFF,
// other 15 bytes = 0x00 (instead of 0x07!)
【问题讨论】:
-
你能不能不要把你的问题标题和关键词叠加起来?没有必要——这就是标签部分的用途。你能花点时间把它编辑成可读的东西吗?
-
提个建议,不知道还能选什么。