當我使用錯誤的密鑰時,我得到一個「解密的」垃圾文件和mscorlib.dll的異常,「指定的塊大小對此算法無效」。我想要的是解密完全失敗而不拋出異常。如何使用Rijndael解密文件來確定密鑰或向量不正確?
這裏是我當前的代碼(改編自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
}
謝謝。如何在dotnet 3.5中執行filestream CopyTo? – cabgef 2011-03-01 13:42:45
@mikeh - 我會在Stream上創建一個擴展方法,並將這個問題的答案複製到它:http://stackoverflow.com/questions/1933742/how-is-the-stream-copytostream-method-implemented- in-net-4 – 2011-03-01 13:44:22
對於不正確的IV /密鑰,不能保證填充例外。 – 2011-03-02 00:48:34