应用程序在加密/序列化期间/之后停止

本文关键字:之后 序列化 加密 应用程序 | 更新日期: 2024-10-25 11:00:22

我找到了一种加密和序列化/反序列化对象的方法

C# 在写入磁盘之前加密序列化文件

这是我的代码...

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; }
    }

但是,它似乎确实加密和序列化了对象,因为创建了一个新文件,打开时看起来是加密的。它只是不继续执行反序列化。

有人有什么想法吗?

应用程序在加密/序列化期间/之后停止

我将[Serializable]属性添加到我的Person Class中。现在都在工作。

 [Serializable]
    public class Person
    {
        public String Name { get; set; }
        public int Age { get; set; }
    }