我加密了一个文件,并将加密的内容写入同一个文件。但是,当我解密文件并尝试将其写入相同时,我无法清除旧内容,即我的加密文本。我怎么能这样做
加密代码
static void EncryptFile(string sInputFilename,string sKey)
{
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.ReadWrite);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsInput,
desencrypt,
CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
fsInput.SetLength(0);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
}
解密代码
static void DecryptFile(string sInputFilename,
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.ReadWrite);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
CryptoStream cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read);
int data;
while ((data = cryptostreamDecr.ReadByte()) != -1)
{
fsread.WriteByte((byte)data);
}
fsread.Close();
cryptostreamDecr.Close();
}
答案 0 :(得分:1)
您正在尝试在解密时写入加密文件,因此您最终会在读完之前添加额外的未加密数据。
假设由于某种原因你不能只使用lcryder的建议,如果你真的需要在最后将数据写回同一个文件,你可以在内存中解密它并在你完成后写它: / p>
private static void DecryptFile(string sInputFilename,
string sKey)
{
var DES = new DESCryptoServiceProvider();
DES.Key = Encoding.ASCII.GetBytes(sKey);
DES.IV = Encoding.ASCII.GetBytes(sKey);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
using(var fsread = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.ReadWrite))
{
using(var cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read))
{
int data;
fsread.Flush();
using(var ms = new MemoryStream())
{
while((data = cryptostreamDecr.ReadByte()) != -1)
{
ms.WriteByte((byte) data);
}
cryptostreamDecr.Close();
using(var fsWrite = new FileStream(sInputFilename, FileMode.Truncate))
{
ms.WriteTo(fsWrite);
ms.Flush();
}
}
}
}
}
当您关闭读取文件流并打开一个新文件以进行写入时,内存流保存未加密的数据(使用FileMode.Truncate以便销毁原始内容)。