我在使用 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