这就是我们的场景:我们有巨大的加密文件,以千兆字节为顺序,如果我们将它们读取到最后,我们可以正确解密。当我们读取并检测文件中的某些标志时出现问题,然后我们停止读取并调用 reader.Close(),会发生 CryptographicException:“填充无效且无法删除”。被抛出。我有一个重现此行为的小型控制台应用程序,要对其进行测试,只需运行它,它将在您的 C:\ 驱动器中创建一个文件,然后在按下任意键时将逐行读取,并在按下“q”时停止.
using System;
using System.IO;
using System.Security.Cryptography;
namespace encryptSample
{
class Program
{
static void Main(string[] args)
{
var transform = CreateCryptoTransform(true);
// first create encrypted file
using (FileStream destination = new FileStream("c:\\test_enc.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
{
using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
using (StreamWriter source = new StreamWriter(cryptoStream))
{
for (int i = 0; i < 1000; i++)
{
source.WriteLine("This is just random text to fill the file and show what happens when I stop reading in the middle - " + i);
}
// Also tried this line, but is the same with or without it
cryptoStream.FlushFinalBlock();
}
}
}
StreamReader reader;
ICryptoTransform transformDec;
CryptoStream cryptoStreamReader;
transformDec = CreateCryptoTransform(false);
FileStream fileStream = new FileStream("c:\\test_enc.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
cryptoStreamReader = new CryptoStream(fileStream, transformDec, CryptoStreamMode.Read);
reader = new StreamReader(cryptoStreamReader);
while (Console.In.ReadLine() != "q")
{
Console.WriteLine(reader.ReadLine());
}
try
{
cryptoStreamReader.Close();
reader.Close();
reader.Dispose();
}
catch (CryptographicException ex)
{
if (reader.EndOfStream)
throw;
}
}
private static ICryptoTransform CreateCryptoTransform(bool encrypt)
{
byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Must be at least eight bytes. MAKE THIS SALTIER!
const int iterations = 1042; // Recommendation is >= 1000.
const string password = "123456";
AesManaged aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
// NB: Rfc2898DeriveBytes initialization and subsequent calls to GetBytes must be eactly the same, including order, on both the encryption and decryption sides.
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform transform = encrypt ? aes.CreateEncryptor(aes.Key, aes.IV) : aes.CreateDecryptor(aes.Key, aes.IV);
return transform;
}
}
}
在我们原来的类中,我们在 Dispose() 期间执行 reader.Close。我的问题是,检查 reader.EndOfStream 是否为假然后捕获 CryptographicException 是否有效?还是加密/解密方法有问题?也许我们错过了一些东西。
问候!