我有一个XML文件,其中包含有关使用此方法解密的stringConnection
参数的信息:
public void DecryptFile(string sInputFileName, string sOutputFileName, string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
FileStream fsread = new FileStream(sInputFileName, FileMode.Open, FileAccess.Read);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
//Print result
StreamWriter fsDecrypted = new StreamWriter(sOutputFileName);
//In this point ReadToEnd return the final xml result decrypted
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
fsread.Close();
fsread.Dispose();
}
结果将是:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<TU>
<BD>DataBaseName</BD>
<SR>ServerName</SR>
<USR>UserDB</USR>
<CONT>Pass</CONT>
<EMP>codCompany</EMP>
<EMPDES>companyName</EMPDES>
<SUC>codLocal</SUC>
</TU>
</NewDataSet>
但是ReadToEnd
不会返回我的XML文件的最后一个标签,如下所示:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<TU>
<BD>DataBaseName</BD>
<SR>ServerName</SR>
<USR>UserDB</USR>
<CONT>Pass</CONT>
<EMP>codCompany</EMP>
<EMPDES>companyName</EMPDES>
<SUC>codLocal</SUC>
</TU>
</NewDataSet
我的方法有什么问题?
答案 0 :(得分:1)
主要问题是你并没有真正阅读CryptoStream
到最后,因为它阻止数据的方式(正如in this answer所指出的那样)。这是一种改编自this answer的方法,它使用缓冲区一次读取1024个字节。
public void DecryptFile(string sInputFileName, string sOutputFileName, string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
using (FileStream fsread = new FileStream(sInputFileName, FileMode.Open, FileAccess.Read))
using (StreamWriter fsDecrypted = new StreamWriter(sOutputFileName))
using (CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read))
{
//Print result
var buffer = new byte[1024];
var read = cryptostreamDecr.Read(buffer, 0, buffer.Length);
while (read > 0)
{
fsDecrypted.Write(buffer, 0, read);
read = cryptostreamDecr.Read(buffer, 0, buffer.Length);
}
}
}
您还缺少using
statements,无论您的程序是否有异常,都可以确保您的流正确处理。