有没有人有任何关于如何将序列化数据加密到文件然后使用DES读回来的例子?
我已经写了一些不起作用的代码,但我宁愿看到新的尝试而不是追求我的代码。
编辑:抱歉,忘记提及我需要使用XmlSerializer.Serialize / Deserialize的示例。
答案 0 :(得分:18)
加密
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);
}
}
}
解密:
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);
}
}
}
用法:
DESCryptoServiceProvider key = new DESCryptoServiceProvider();
MyObject obj = new MyObject();
EncryptAndSerialize("testfile.xml", obj, key);
MyObject deobj = DecryptAndDeserialize("testfile.xml", key);
您需要将MyObject更改为您要序列化的对象类型,但这是一般的想法。诀窍是使用相同的SymmetricAlgorithm实例进行加密和解密。
答案 1 :(得分:2)
这个帖子给出了基本的想法。这是一个使函数具有通用性的版本,并且还允许您传递加密密钥以使其可逆。
public static void EncryptAndSerialize<T>(string filename, T obj, string encryptionKey) {
var key = new DESCryptoServiceProvider();
var e = key.CreateEncryptor(Encoding.ASCII.GetBytes("64bitPas"), Encoding.ASCII.GetBytes(encryptionKey));
using (var fs = File.Open(filename, FileMode.Create))
using (var cs = new CryptoStream(fs, e, CryptoStreamMode.Write))
(new XmlSerializer(typeof (T))).Serialize(cs, obj);
}
public static T DecryptAndDeserialize<T>(string filename, string encryptionKey) {
var key = new DESCryptoServiceProvider();
var d = key.CreateDecryptor(Encoding.ASCII.GetBytes("64bitPas"), Encoding.ASCII.GetBytes(encryptionKey));
using (var fs = File.Open(filename, FileMode.Open))
using (var cs = new CryptoStream(fs, d, CryptoStreamMode.Read))
return (T) (new XmlSerializer(typeof (T))).Deserialize(cs);
}
答案 2 :(得分:0)