简体   繁体   English

加密XmlTextWriter并将其序列化为文件的正确方法是什么?

[英]What is the proper way to encrypt an XmlTextWriter and serialize it to a file?

I have an XmlTextWriter that gets written to file using an XmlSerializer that looks like the following: 我有一个XmlTextWriter,它使用XmlSerializer写入文件,如下所示:

using (XmlTextWriter writer = new XmlTextWriter(path, null))
{
   writer.Formatting = Formatting.Indented;
   writer.Indentation = 3;
   MyFileObj.ourSerializer.Serialize(writer, xmlFile, ourXmlNamespaces);
}

where "ourSerializer" is just a reference to an System.Xml.Serialization.XmlSerializer object. 其中“ ourSerializer”只是对System.Xml.Serialization.XmlSerializer对象的引用。 However, I have an instance where this XML must be encrypted to disk so that the end user cannot read its contents, and I am unsure of the proper way to go about it using the existing code since there are many places where this code is called and does not need to be encrypted. 但是,我有一个实例,必须将此XML加密到磁盘上,以使最终用户无法读取其内容,而且我不确定使用现有代码进行处理的正确方法,因为在很多地方都可以调用此代码。并且不需要加密。 Can anyone shed some insight into this for me? 谁能为我提供一些见识?

An alternative way would be to use a CryptoStream, like this: 另一种方法是使用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);
        }
    }
}

Where _Provider is an AesCryptoServiceProvider properly initialized. _Provider是正确初始化的AesCryptoServiceProvider。

Here is how I ended up solving the issue: 这是我最终解决问题的方法:

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);
}

Basically serialized the XML to a MemoryStream, read the text back out into a TextReader, encrypted the TextReader contents and then saved the resulting encrypted string to a file. 基本上将XML序列化为MemoryStream,将文本读回TextReader,对TextReader的内容进行加密,然后将生成的加密字符串保存到文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM