我找到了一种加密和序列化/反序列化对象的方法
C# Encrypt serialized file before writing to disk
这是我的代码......
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Digital_Only_Calculator
{
class EncryptionSerialiser
{
byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Where to store these keys is the tricky part,
// you may need to obfuscate them or get the user to input a password each time
byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
string path = Application.StartupPath + @"\" + "test.ser";
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
public void EncryptThenSerialise(object obj)
{
// Encryption
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
using (var cryptoStream = new CryptoStream(fs, des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
BinaryFormatter formatter = new BinaryFormatter();
// This is where you serialize the class
formatter.Serialize(cryptoStream, obj);
}
}
public Person DecryptThenSerialise(object obj)
{
// Decryption
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var cryptoStream = new CryptoStream(fs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
// This is where you deserialize the class
Person deserialized = (Person)formatter.Deserialize(cryptoStream);
return deserialized;
}
}
}
}
测试代码......
Person p = new Person();
p.Name = "Bill";
p.Age = 40;
EncryptionSerialiser ESER = new EncryptionSerialiser();
ESER.EncryptThenSerialise(p);
Person p2 = new Person();
p2 = ESER.DecryptThenSerialise(p2);
问题是,应用程序在此行之后不会继续(您可以在EncryptThenSerialise方法中看到。
formatter.Serialize(cryptoStream, obj);
人类......
public class Person
{
public String Name { get; set; }
public int Age { get; set; }
}
然而,似乎加密并序列化对象,因为创建了一个新文件,当打开时看起来是加密的。它只是没有继续执行de serialization。
任何想法?
答案 0 :(得分:0)
我将[Serializable]属性添加到我的Person类。一切正常。
[Serializable]
public class Person
{
public String Name { get; set; }
public int Age { get; set; }
}