2014-12-23 75 views
0

當我想要反序列化對象時,它會給出一個錯誤,指出「錯誤的數據」。解密加密文件時出現「錯誤數據」異常

文件數據轉換成功後,它給上設置或關閉流

錯誤 #########錯誤
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) 
at System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle hKey, Byte[] data, Int32 ib, Int32 cb, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode PaddingMode, Boolean fDone) 
at System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) 
at System.Security.Cryptography.CryptoStream.FlushFinalBlock() 
    at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) 
    at System.IO.Stream.Close() 
    at System.IO.Stream.Dispose() 
    at BinaryFileHelper.DeserializeObject[T](String filename) 
#########錯誤
private static DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider() 
{ 
    Key = System.Text.Encoding.UTF8.GetBytes("12345678".Substring(0, 8)), 
    IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF } 
}; 

public static void SerializeObject(string filename, object objectToSerialize) 
{ 
    using (Stream stream = File.Open(filename, FileMode.OpenOrCreate)) 
    { 
     BinaryFormatter binaryFormatter = new BinaryFormatter(); 
     using (Stream cryptoStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write)) 
     { 
      binaryFormatter.Serialize(cryptoStream, objectToSerialize); 
     } 
    } 
} 

public static T DeserializeObject<T>(string filename) 
{ 
    T objectFromDeserialize; 
    using (Stream stream = File.Open(filename, FileMode.Open)) 
    { 
     BinaryFormatter binaryFormatter = new BinaryFormatter(); 
     using (Stream cryptoStream = new CryptoStream(stream, cryptic.CreateDecryptor(), CryptoStreamMode.Read)) 
     { 
      objectFromDeserialize = (T)binaryFormatter.Deserialize(cryptoStream); 
     } // After conversion succeed, it gives error on disposing or closing at this line 
    } 
    return objectFromDeserialize; 
} 
+0

http://blogs.msmvps.com/jonskeet/2014/01/20/diagnosing-issues-with-reversible-data-transformations/ – Aron

回答

0

問題是使用OpenOrCreate而不是Create。原因是如果文件已經存在,OpenOrCreate將創建一個FileStream用於追加到文件末尾。 Create將在創建新文件之前刪除現有文件。

public static void SerializeObject(string filename, object objectToSerialize) 
{ 
    using (Stream stream = File.Open(filename, FileMode.Create))//Changed 
    { 
     BinaryFormatter binaryFormatter = new BinaryFormatter(); 
     using (Stream cryptoStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write)) 
     { 
      binaryFormatter.Serialize(cryptoStream, objectToSerialize); 
     } 
    } 
} 
相關問題