我有一个XmlTextWriter,它使用XmlSerializer写入文件,如下所示:
using (XmlTextWriter writer = new XmlTextWriter(path, null))
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 3;
MyFileObj.ourSerializer.Serialize(writer, xmlFile, ourXmlNamespaces);
}
其中“ourSerializer”只是对System.Xml.Serialization.XmlSerializer对象的引用。但是,我有一个实例,其中必须将此XML加密到磁盘,以便最终用户无法读取其内容,并且我不确定使用现有代码的正确方法,因为有许多地方调用此代码并且不需要加密。任何人都可以为我提供一些见解吗?
答案 0 :(得分:1)
另一种方法是使用CryptoStream,如下所示:
using (var fs = new FileStream(path, System.IO.FileMode.Create))
{
using (var cs = new CryptoStream(fs, _Provider.CreateEncryptor(), CryptoStreamMode.Write))
{
using (var writer = XmlWriter.Create(cs))
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 3;
MyFileObj.ourSerializer.Serialize(writer, xmlFile, ourXmlNamespaces);
}
}
}
其中_Provider是正确初始化的AesCryptoServiceProvider。
答案 1 :(得分:0)
以下是我最终解决问题的方法:
MemoryStream ms = new MemoryStream();
XmlSerializer ourSerializer.Serialize(ms, xmlFile, ourXmlNamespaces);
ms.Position = 0;
//Encrypt the memorystream
using (TextReader reader = new StreamReader(ms, Encoding.ASCII))
using (StreamWriter writer = new StreamWriter(path))
{
string towrite = Encrypt(reader.ReadToEnd());
writer.Write(towrite);
}
基本上将XML序列化为MemoryStream,将文本读回TextReader,加密TextReader内容,然后将生成的加密字符串保存到文件中。