2016-04-21 16 views
0

我找到了一種方法去加密和連載/連載對象申請暫停期間/加密/序列化之後

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

回答

0

我向我的Person類添加了[Serializable]屬性。現在都在工作。

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