2013-07-11 99 views
0

我和我在使用DES加密技術反序列化對象時遇到了一些麻煩。DES序列化異常

我收到一個異常,說「壞數據」。在DeserializeDESObjectFromFile功能。

我可以請一些幫助,讓這個工作?

這裏是我的代碼:

Public Sub SerializeDESObjectToFile(FileName As String, Item As Object) 
    Dim fs As FileStream 
    Dim formatter As New BinaryFormatter 

    Dim DESKey() As Byte = {200, 5, 78, 232, 9, 6, 0, 4} 
    Dim DESInitializationVector() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 
    Dim MyStreamEncrypter As CryptoStream = Nothing 

    fs = New FileStream(FileName, FileMode.Create) 
    Dim DESAlgorithm As DES 
    DESAlgorithm = New DESCryptoServiceProvider 
    MyStreamEncrypter = New CryptoStream(fs, DESAlgorithm.CreateEncryptor(DESKey, DESInitializationVector), CryptoStreamMode.Write) 

    Try 
     formatter.Serialize(MyStreamEncrypter, Item) 
    Catch e As Exception 
     Console.WriteLine("Failed to serialize. Reason: " & e.Message) 
    Finally 
     fs.Close() 
    End Try 
End Sub 

Public Function DeserializeDESObjectFromFile(FileName As String) As Object 
    Dim fs As New FileStream(FileName, FileMode.Open) 
    Dim ItemToReturn As New Object 

    Dim DESKey() As Byte = {200, 5, 78, 232, 9, 6, 0, 4} 
    Dim DESInitializationVector() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 
    Dim MyStreamDecrypter As CryptoStream = Nothing 

    Dim DESAlgorithm As DES 
    DESAlgorithm = New DESCryptoServiceProvider 

    MyStreamDecrypter = New CryptoStream(fs, DESAlgorithm.CreateDecryptor(DESKey, DESInitializationVector), CryptoStreamMode.Read) 

    Try 
     Dim formatter As New BinaryFormatter 
     ItemToReturn = DirectCast(formatter.Deserialize(MyStreamDecrypter), Object) 
     Return ItemToReturn 
    Catch e As Exception 
     MsgBox(e.Message) 
     Return Nothing 
    Finally 
     fs.Close() 
    End Try 
End Function 
+0

只能在標記中使用IDE(visual studio)的指示,如果它可以影響問題本身。使用經常使用的標籤,例如使用[tag:加密]而不是[tag:des]來獲得更多關注。 –

回答

0

重要的是要確保在流中的最後一個塊刷新是很重要的。分組密碼模式(如ECB模式和CBC模式)需要填充,因爲分組密碼只能加密完整的明文塊。由於流不知道您的序列化數據對象是它必須加密的最後一個數據,因此它無法填充和加密最後一個塊本身。

在將最後一個純文本數據寫入CryptoStream後,應調用FlushFinalBlock。或者,您可以在CryptoStream上調用close()而不是底層的流,或者確保之前的在基礎流上調用close()

+0

如果C .NET專家可以檢查最後一行,那麼將不勝感激。我相當肯定地閱讀API,但就我的知識而言,這是相當可觀的。 –