我已经在 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!)