Encryption
public static void EncryptAndSerialize(string filename, MyObject obj, SymmetricAlgorithm key)
{
using(FileStream fs = File.Open(filename, FileMode.Create))
{
using(Cryptostream cs = new CryptoStream(fs, key.CreateEncryptor(), CryptoStreamMode.Write))
{
XmlSerializer xmlser = new XmlSerializer(typeof(MyObject));
xmlser.Serialize(cs, obj);
}
}
}
Decryption:
public static MyObject DecryptAndDeserialize(string filename, SymmetricAlgorithm key)
{
using(FileStream fs = File.Open(filename, FileMode.Open))
{
using(Cryptostream cs = new CryptoStream(fs, key.CreateDecryptor(), CryptoStreamMode.Read))
{
XmlSerializer xmlser = new XmlSerializer(typeof(MyObject));
return (MyObject) xmlser.Deserialize(cs);
}
}
}
Usage:
DESCryptoServiceProvider key = new DESCryptoServiceProvider();
MyObject obj = new MyObject();
EncryptAndSerialize("testfile.xml", obj, key);
MyObject deobj = DecryptAndDeserialize("testfile.xml", key);
You need to change MyObject to whatever the type of your object is that you are serializing, but this is the general idea. The trick is to use the same SymmetricAlgorithm instance to encrypt and decrypt.