当我使用错误的密钥时,我得到一个“解密的”垃圾文件和来自 mscorlib.dll 的异常,“指定的块大小对此算法无效。” 相反,我想要的是解密完全失败而不会引发异常。
这是我当前的代码(改编自我在互联网上找到的 vb.net 示例,因此如果有更好的解决方案将不胜感激)
public static bool EncryptOrDecryptFile(string strInputFile,
string strOutputFile, string pKey, string pIv, CryptoAction Direction)
{
Byte[] bytKey = CreateKey(pKey);
Byte[] bytIV = CreateIV(pIv);
bool pRet = false;
if (!File.Exists(strInputFile))
return false;
try
{
using (FileStream fsInput = new FileStream(strInputFile, FileMode.Open, FileAccess.Read))
{
using (FileStream fsOutput = new FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write))
{
fsOutput.SetLength(0);
byte[] bytBuffer = new byte[4097];
long lngBytesProcessed = 0;
long lngFileLength = fsInput.Length;
int intBytesInCurrentBlock = 0;
CryptoStream csCryptoStream = null;
RijndaelManaged cspRijndael = new RijndaelManaged();
cspRijndael.BlockSize = 4096;
switch (Direction)
{
case CryptoAction.ActionEncrypt:
csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV),
CryptoStreamMode.Write);
break;
case CryptoAction.ActionDecrypt:
csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV),
CryptoStreamMode.Write);
break;
}
while (lngBytesProcessed < lngFileLength)
{
intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096);
csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock);
lngBytesProcessed = lngBytesProcessed + Convert.ToInt64(intBytesInCurrentBlock);
}
csCryptoStream.Close();
}
}
pRet = true;
}
catch (Exception ex)
{
pRet = false;
}
return pRet;
}
#endregion
}