我想使用LINQ to XML读/写加密的XML文件.有谁知道如何使用.NET Framework内置的加密算法来加密XDocument对象使用的Stream?
我确实尝试过,但你不能将CryptoStream设置为读/写访问权限.它只支持Read或Write,这会导致LINQ to XML抛出异常.
更新:"动态"读取/写入文档会很好,但我只需要读取加密的xml文件,对其进行操作,然后再将其写回加密.
最简单的方法可能是XDocument.Load(),Linq,然后是XDocument.Save().从快速测试应用程序(轻松使用非处置资源):
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
将您最喜欢的ICryptoTransform交换到CryptoStream中.