我使用AES加密。当我加密然后解密整个文件时没关系。我想将多个文件添加到一个加密的文件中。这就是问题所在。加密很好,但解密会导致 CryptographicException - 数据长度错误。甚至可以解密文件的一部分还是整个加密?我使用了一个加密流并将所有要加密的文件传递给单个文件。我试图做相反的事情:
AesManaged aes = AES.InitAes(key, salt);
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
int defChunkSize = 1024 * 1024 * 50;
using (FileStream source = new FileStream(header.data.filename, FileMode.Open))
{
foreach (CryptHeader.fileStruct file in header.data.files)
{
preparePath(file.filename);
using (FileStream target = new FileStream(file.filename, FileMode.Create))
{
using (CryptoStream cryptoStream = new CryptoStream(target, transform, CryptoStreamMode.Write))
{
long padding = source.Length - header.data.files.Sum(x => x.length);//Just test
int chunkSize = (defChunkSize > (int)file.length) ? (int)file.length : defChunkSize;
byte[] chunkData = new byte[chunkSize];
int bytesRead = 0;
int totalRead = 0;
while (totalRead < file.length)
{
bytesRead = source.Read(chunkData, 0, chunkSize);
if (bytesRead <= 0) break;
totalRead += bytesRead;
cryptoStream.Write(chunkData, 0, bytesRead);
}
chunkData = null;
}
}
}
}