申请暂停期间/加密/序列化之后

申请暂停期间/加密/序列化之后

问题描述:

我找到了一种方法去加密和连载/连载对象申请暂停期间/加密/序列化之后

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

Person类...

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

但它确实似乎加密和序列化对象,作为一个新的文件被创建,当打开长相加密。它只是不会继续执行序列化。

任何想法的人?

+0

“应用程序不会在这行后继续”它挂起,还是崩溃? –

+0

它似乎是“突破”,即退出该方法,并允许用户使用控制表单等。所以它几乎就像它认为它已完成,但它没有。 – user3755946

我向我的Person类添加了[Serializable]属性。现在都在工作。

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