反序列化对象时,我在使用序列化加密时遇到问题。
这是错误:
反序列化失败。原因:解析完成前遇到流结束
这是我的代码:
Imports System.IO
Imports System.Security.Cryptography
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Text
Module TestModEncryption
Public Sub SaveEncryptedObjectToFile(FileName As String, Item As Object)
Dim fs As FileStream
Dim encryptor As CryptoStream
Dim formatter As New BinaryFormatter
Dim password As String = "MyPassword"
Dim salt As String = "InitialVector123"
Dim AES As AesManaged = New AesManaged
AES.Padding = PaddingMode.None
AES.Mode = CipherMode.CBC
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As Integer = 2
Dim InitialVector As String = "InitialVector123" 'This should be a string of 16 ASCII characters.
Dim KeySize As Integer = 256 'Can be 128, 192, or 256.
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As New Rfc2898DeriveBytes(password, SaltValueBytes, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(CInt(KeySize / 8))
Dim encryptTransf As ICryptoTransform = AES.CreateEncryptor(KeyBytes, InitialVectorBytes)
fs = New FileStream(FileName, FileMode.Create)
encryptor = New CryptoStream(fs, encryptTransf, CryptoStreamMode.Write)
Try
formatter.Serialize(encryptor, Item)
Catch e As SerializationException
Console.WriteLine("Failed to serialize. Reason: " & e.Message)
Throw
Finally
fs.Close()
End Try
End Sub
Public Function OpenEncryptedObjectFromFile(FileName As String) As Object
Dim fs As New FileStream(FileName, FileMode.Open)
Dim decryptor As CryptoStream
Dim ItemToReturn As New Object
Dim password As String = "MyPassword"
Dim salt As String = "InitialVector123"
Dim AES As AesManaged = New AesManaged
AES.Padding = PaddingMode.None
AES.Mode = CipherMode.CBC
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As Integer = 2
Dim InitialVector As String = "InitialVector123" 'This should be a string of 16 ASCII characters.
Dim KeySize As Integer = 256 'Can be 128, 192, or 256.
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As New Rfc2898DeriveBytes(password, SaltValueBytes, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(CInt(KeySize / 8))
Dim decryptTrans As ICryptoTransform = AES.CreateDecryptor(KeyBytes, InitialVectorBytes)
Try
Dim formatter As New BinaryFormatter
decryptor = New CryptoStream(fs, decryptTrans, CryptoStreamMode.Read)
ItemToReturn = DirectCast(formatter.Deserialize(decryptor), Object)
Return ItemToReturn
Catch e As SerializationException
MsgBox("Failed to deserialize. Reason: " & e.Message)
Return Nothing
'Throw
Finally
fs.Close()
End Try
End Function
End Module