我面临的情况是,我需要安全地加密/解密 n 长度的文件,最好使用 Rijndael,但绝对是 256 位加密。
我以前玩过加密,并且非常高兴地加密/解密了字符串和字节数组。
但是,因为我不知道文件的大小(并且有问题的文件可能非常大(〜2.5gb)是非常可行的,所以我不能将它们加载到字节数组中并在其中进行编码/解密像我以前一样的单一界限。
因此,在 Google 上阅读了一些内容后,我知道答案是分块加密和解密文件,因此我生成了以下代码:
private static void Enc(string decryptedFileName, string encryptedFileName)
{
FileStream fsOutput = File.OpenWrite(encryptedFileName);
FileStream fsInput = File.OpenRead(decryptedFileName);
byte[] IVBytes = Encoding.ASCII.GetBytes("1234567890123456");
fsOutput.Write(BitConverter.GetBytes(fsInput.Length), 0, 8);
fsOutput.Write(IVBytes, 0, 16);
RijndaelManaged symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC};
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(passwordDB.GetBytes(256 / 8), IVBytes);
CryptoStream cryptoStream = new CryptoStream(fsOutput, encryptor, CryptoStreamMode.Write);
for (long i = 0; i < fsInput.Length; i += chunkSize)
{
byte[] chunkData = new byte[chunkSize];
fsInput.Read(chunkData, 0, chunkSize);
cryptoStream.Write(chunkData, 0, chunkData.Length);
}
cryptoStream.Close();
fsInput.Close();
fsInput.Dispose();
cryptoStream.Dispose();
}
private static void Dec(string encryptedFileName, string decryptedFileName)
{
FileStream fsInput = File.OpenRead(encryptedFileName);
FileStream fsOutput = File.OpenWrite(decryptedFileName);
byte[] buffer = new byte[8];
fsInput.Read(buffer, 0, 8);
long fileLength = BitConverter.ToInt64(buffer, 0);
byte[] IVBytes = new byte[16];
fsInput.Read(IVBytes, 0, 16);
RijndaelManaged symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC };
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(passwordDB.GetBytes(256 / 8), IVBytes);
CryptoStream cryptoStream = new CryptoStream(fsOutput,decryptor,CryptoStreamMode.Write);
for (long i = 0; i < fsInput.Length; i += chunkSize)
{
byte[] chunkData = new byte[chunkSize];
fsInput.Read(chunkData, 0, chunkSize);
cryptoStream.Write(chunkData, 0, chunkData.Length);
}
cryptoStream.Close();
cryptoStream.Dispose();
fsInput.Close();
fsInput.Dispose();
}
这一切对我来说“看起来”都不错,但可悲的是,看起来似乎是骗人的!
加密工作没有错误,但在解密过程中,“cryptoStream.Close()”方法抛出以下异常:
System.Security.Cryptography.CryptographicException
未处理消息=“填充是
无效且无法删除。”
来源=“mscorlib”堆栈跟踪:
在 System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[]
输入缓冲区,Int32 输入偏移,Int32
输入计数,字节[]和输出缓冲区,
Int32 输出偏移、PaddingMode
paddingMode,布尔值 fLast)
在 System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[]
输入缓冲区,Int32 输入偏移,Int32
输入计数)
在 System.Security.Cryptography.CryptoStream.FlushFinalBlock()
在 System.Security.Cryptography.CryptoStream.Dispose(布尔值
处置)
在 System.IO.Stream.Close()
未加密的文件大小似乎与预期的文件大小不匹配(范围从大约 8 个字节到大约 60 个字节)
我通过更改 RijndaelManaged 对象创建行以包含填充类型来“修复”该异常,如下所示:
RijndaelManaged symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC,Padding=PaddingMode.None };
但文件大小仍然不匹配,并且可以预见的是,新近未加密的文件是胡说八道!
我承认我现在已经超出了加密/解密的舒适区,这可能是一个菜鸟错误 - 但我无法发现它!
任何有关解决此问题的帮助将不胜感激!