How to read / write an encrypted XML file using LINQ to XML?

I would like to read / write encrypted XML files using LINQ to XML. Does anyone know how to use the encryption algorithms built into the .NET Framework to encrypt the stream used by the XDocument?

I tried, but you cannot install CryptoStream for read / write. It only supports reading or writing, which causes LINQ to XML to throw an exception.

Update: it would be nice to read / write the document "on the fly", but I only need to read the encrypted XML file, process it, and then write it encrypted again.

+5
source share
2 answers

The simplest approach is probably XDocument.Load (), Linq, and then XDocument.Save (). From a quick test application (easily switch to unallocated resources):

XDocument writeContacts = new XDocument(
   new XElement("contacts",
      new XElement("contact",
         new XElement("name", "Patrick Hines"),
         new XElement("phone", "206-555-0144",
             new XAttribute("type", "home")),
         new XElement("phone", "425-555-0145",
             new XAttribute("type", "work")),
         new XElement("address",
            new XElement("street1", "123 Main St"),
            new XElement("city", "Mercer Island"),
            new XElement("state", "WA"),
            new XElement("postal", "68042")
         )
      )
   )
);

Rijndael RijndaelAlg = Rijndael.Create();

FileStream writeStream = File.Open("data.xml", FileMode.Create);
CryptoStream cStream = new CryptoStream(writeStream,
    RijndaelAlg.CreateEncryptor(RijndaelAlg.Key, RijndaelAlg.IV),
    CryptoStreamMode.Write);

StreamWriter writer = new StreamWriter(cStream);

writeContacts.Save(writer);

writer.Flush();
writer.Close();

FileStream readStream = File.OpenRead("data.xml");

cStream = new CryptoStream(readStream,
  RijndaelAlg.CreateDecryptor(RijndaelAlg.Key, RijndaelAlg.IV),
  CryptoStreamMode.Read);

XmlTextReader reader = new XmlTextReader(cStream);

XDocument readContacts = XDocument.Load(reader);

//manipulate with Linq and Save() when needed

Change your favorite ICryptoTransform to CryptoStream.

+8
source

[update: kudos in Corbin March, which (at the same time) wrote the same thing, but in code!]

Most threads are one way. I suppose you have to:

  • create CryptoStreamread from file (file, etc.)
  • read the data (e.g. in XDocument)
  • Make your code (read the document, make changes, etc.)
  • enter a new entry CryptoStreamin the file (file, etc.) [starting from the same IV, etc.)
  • save document in stream

, (FileStream, MemoryStream ..), / (.. CryptoStream, , .Close() ).

0

All Articles