When I use the wrong key, I am getting a "decrypted" garbage file and an exception from mscorlib.dll, "Specified block size is not valid for this algorithm." What I would like instead is for the decryption to fail entirely without throwing an exception.
Here's my current code (adapted from a vb.net example I found on the internet, so better solution would be appreciated if out there)
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
}