我有两个方法,如下所示,读取和写入我的XML文件。加密XML文件并允许从我的代码中读/写它的最简单方法是什么?
阅读XML文件
XmlSerializer SerializerObj = new XmlSerializer(typeof(List<ItemsUnderControlObject>));
// Create a new file stream for reading the XML file
FileStream ReadFileStream = new FileStream(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()) + @"\itemlist.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
// Load the object saved above by using the Deserialize function
MyGlobals.ListOfItemsToControl = (List<ItemsUnderControlObject>)SerializerObj.Deserialize(ReadFileStream);
// Cleanup
ReadFileStream.Close();
编写XML文件
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(List<ItemsUnderControlObject>));
// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()) + @"\itemlist.xml");
SerializerObj.Serialize(WriteFileStream, MyGlobals.ListOfItemsToControl);
WriteFileStream.Close();
答案 0 :(得分:1)
查看System.Security.Cryptography
命名空间,该命名空间提供了一堆允许加密/解密的类。许多人会接受一个流来解密,所以只需将你的WriteFileStream / ReadFileStream实例传递给一个加密类,就可以了。
下面的示例部分基于example in MSDN设置AES加密提供程序(并且可以适用于其他加密算法)。它需要一些初始化代码,这些代码取决于您的实现 - see example那里。
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (Stream msEncrypt = new FileStream(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()) + @"\itemlist.xml"))
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(List<ItemsUnderControlObject>));
// Create a new file stream to write the serialized object to a file
SerializerObj.Serialize(swEncrypt, MyGlobals.ListOfItemsToControl);
}
}
}
}