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