简体   繁体   中英

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:

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. 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. Can anyone shed some insight into this for me?

An alternative way would be to use a CryptoStream, like this:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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