考虑以下测试:
[Test]
public void TestAes256EcbPkcs7Stream()
{
// 504 bytes of plain text
const string inputString = new string('z', 504);
var inputBytes = Encoding.UTF8.GetBytes(inputString);
byte[] key = {
0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0
};
var rij = new RijndaelManaged
{
BlockSize = 256, // 256 bits == 32 bytes
Key = key,
IV = key, // just for test
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
var enc = rij.CreateEncryptor();
var encBytes = enc.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
Assert.AreEqual(512, encBytes.Length);
var dec = rij.CreateDecryptor();
byte[] decBytes = new byte[inputBytes.Length];
int decPos = 0;
using (var cipherMs = new MemoryStream(encBytes))
{
var buf = new byte[32];
// process all blocks except the last one
while (cipherMs.Read(buf, 0, buf.Length)==buf.Length &&
cipherMs.Length!=cipherMs.Position)
{
for (int w = 0; w!=buf.Length;)
{
w += dec.TransformBlock(buf, 0, buf.Length, decBytes, decPos);
decPos += w;
}
}
// ensure that we read all blocks
Assert.IsTrue(cipherMs.Length==cipherMs.Position);
// process the last block
var tailBytes = dec.TransformFinalBlock(buf, 0, buf.Length);
// here decPos==480, that means 480 bytes were written to decBytes
// and 504-480 = 24 bytes come from TransformFinalBlock
Assert.AreEqual(24, tailBytes.Length); // <- fail, because the actual length is 56
Buffer.BlockCopy(tailBytes, 0, decBytes, decPos, tailBytes.Length);
}
Assert.AreEqual(inputBytes, decBytes);
}
出于某种原因,我得到了56字节的最终块而不是24字节。
我想,TransformBlock
/ TransformFinalBlock
应该以其他方式使用,但遗憾的是,MSDN文档并未对这些方法进行过多解释。
有什么想法吗?
答案 0 :(得分:0)
好的,这就是事情:
当第一次调用TransformBlock
时,它会将输入缓冲区的最后一个块复制到所谓的 depad buffer ,然后将剩余的块转换并写入输出缓冲区。在下一次调用期间,它从depad缓冲区转换数据,将其写入输出缓冲区,再次将输入缓冲区的最后一个块复制到depad缓冲区,并将转换后的剩余块写入输出,就像第一次一样。
TL; DR: TransformBlock
缓存最后一个输入数据块,因此当调用TransformFinalBlock
时,它可以抓取最后一个块并删除填充。如果没有缓存,最后一个块可能由TransformBlock
处理。在这种情况下,不会删除填充。