2013-12-16 91 views
1

我有使用測試以下的效用函數,以序列化我的對象到加密的字節數組,並且還從解密的字節數組加密和解密的字節數組

//encryption key 
public static byte[] Key = new byte[]{0x43, 0x72, 0x6e, 0x6d, 0x54, 0x4d, 0x65, 
             0x94, 0x16, 0x32, 0x44, 0x84, 0x7e, 0x18, 
             0x64, 0x76, 0x6e, 0x63, 0x64, 0x7a, 0x5f, 
             0x84, 0x7f, 0x9a}; 

//Decrypt byte[] 
public static byte[] Decrypt(byte[] data) 
{ 
    MemoryStream ms = new MemoryStream(); 
    Rijndael alg = Rijndael.Create(); 
    alg.Key = Key; 
    CryptoStream cs = new CryptoStream(ms, 
    alg.CreateDecryptor(), CryptoStreamMode.Write); 
    cs.Write(data, 0, data.Length); 
    cs.Close(); 
    byte[] decryptedData = ms.ToArray(); 
    return decryptedData; 
} 

//Encrypt byte[] 
public static byte[] Encrypt(byte[] data) 
{ 
    MemoryStream ms = new MemoryStream(); 
    Rijndael alg = Rijndael.Create(); 
    alg.Key = Key; 
    CryptoStream cs = new CryptoStream(ms, 
    alg.CreateEncryptor(), CryptoStreamMode.Write); 
    cs.Write(data, 0, data.Length); 
    cs.Close(); 
    byte[] encryptedData = ms.ToArray(); 
    return encryptedData; 
} 

//serialize object to memory stream 
public static MemoryStream SerializeToStream(object o) 
{ 
    MemoryStream stream = new MemoryStream(); 
    IFormatter formatter = new BinaryFormatter(); 
    formatter.Serialize(stream, o); 
    return stream; 
} 

//deserialize object from memory stream 
public static T DerializeFromStream<T>(MemoryStream memoryStream) where T : new() 
{ 
    if (memoryStream == null) { return new T(); } 
    T o; 
    BinaryFormatter binaryFormatter = new BinaryFormatter(); 
    using (memoryStream) 
    { 
     memoryStream.Seek(0, SeekOrigin.Begin); 
     o = (T)binaryFormatter.Deserialize(memoryStream); 
    } 
    return o; 
} 

反序列化,在這裏上述的效用函數

//serialize to stream then to byte array 
var obj = new SomeObject(); 
var bytes = SerializeToStream(obj).ToArray(); 
bytes = Encrypt(bytes); 

//deserialize to decrypted byte array then to stream then to object 
var memoryStream = new MemoryStream(); 
var Decryptedbytearray = Decrypt(bytes); 
//fille the stream 
memoryStream.Write(Decryptedbytearray, 0, Decryptedbytearray.Length); 
//deserialize the object from the stream 
//it fails here giving an exception saying the binary data is not valid 
var obj2 = DerializeFromStream<SomeObject>(memoryStream); 

反序列化對象時出現問題,請參閱註釋最後一行,我做錯了什麼?

+0

您是否嘗試調試它? – MarcinJuraszek

+0

@MarcinJuraszek當然,但我得到無效的反序列化二進制數據,到目前爲止序列化部分工作正常 – FPGA

回答

3

如果你調試你的代碼,你會發現它不能正確解密。原因是你不僅要使用相同的key,還要使用相同的IV

MSDN

的IV屬性無論何時創建新實例SymmetricAlgorithm類之一的自動設定爲一個新的隨機值或當手動調用GenerateIV方法。 IV特性的大小必須是相同的塊大小屬性除以8

看看this question關於如何創建密鑰並從密碼一個IV細節。

+0

現在完美工作,非常感謝 – FPGA