我在使用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 :(得分:0)
确保刷新流中的最后一个块非常重要。需要填充诸如ECB模式和CBC模式的分组密码模式,因为分组密码只能加密完整的明文块。由于流不知道您的序列化数据对象是它必须加密的最后一个数据,因此它无法填充和加密最后一个块本身。
在将最后一个纯文本数据写入CryptoStream
后,应调用FlushFinalBlock。或者,您可以在上部close()
而不是基础流上调用CryptoStream
,或者确保在上调用基础流上的close()
之前正确处理。