【发布时间】:2016-04-21 20:25:57
【问题描述】:
我找到了一种加密和序列化/反序列化对象的方法
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; }
}
然而,它似乎对对象进行了加密和序列化,因为创建了一个新文件,打开时看起来是加密的。它只是不会继续执行反序列化。
任何想法任何人?
【问题讨论】:
-
"应用程序在这一行之后没有继续" 是挂起还是崩溃?
-
它似乎“中断”了,即退出该方法并允许用户使用控件表单等。所以它几乎就像它“认为”它已经完成但它没有。
标签: c# winforms serialization