我会创建一个提供属性的序列化类。读取它(给出一个文件名)返回反序列化的对象,写入它(也给出一个文件名)序列化对象。
我添加了带有字符串密码的第二个属性。使用它时,您可以加密序列化的对象字符串和写入磁盘或从它读取时 1. 加密,然后反序列化。
要加密,我建议使用密码中的哈希函数,而不是直接使用它。
不幸的是,我在 vb.net 中只有一个代码示例:
Function Encrypt(ByVal data As String, ByVal password As String) As String
Dim pdb As New Rfc2898DeriveBytes(password, Salt)
Dim alg As Rijndael = Rijndael.Create()
alg.Key = pdb.GetBytes(32)
alg.IV = pdb.GetBytes(16)
Dim ms As New IO.MemoryStream
Dim cs As New CryptoStream(ms, alg.CreateEncryptor, CryptoStreamMode.Write)
cs.Write(System.Text.Encoding.Default.GetBytes(data), 0, data.Length)
cs.Close()
ms.Close()
Return Convert.ToBase64String(ms.ToArray)
End Function
Private Salt As Byte() = {100, 86, 34, 53, 11, 224, 145, 123, _
237, 213, 12, 124, 45, 65, 71, 127, _
135, 165, 234, 164, 127, 234, 231, 211, _
10, 9, 114, 234, 44, 63, 75, 12}
Function Decrypt(ByVal data As String, ByVal password As String) As String
Dim pdb As New Rfc2898DeriveBytes(password, Salt)
Dim alg As Rijndael = Rijndael.Create()
alg.Key = pdb.GetBytes(32)
alg.IV = pdb.GetBytes(16)
Dim ms As New IO.MemoryStream
Dim cs As New CryptoStream(ms, alg.CreateDecryptor, CryptoStreamMode.Write)
cs.Write(Convert.FromBase64String(data), 0, Convert.FromBase64String(data).Length)
cs.Close()
ms.Close()
Return System.Text.Encoding.Default.GetString(ms.ToArray)
End Function
和
Function EncryptWithHash(ByVal data As String, ByVal passToHash As String) As String
Dim _hash As String = getMd5Hash(passToHash)
Dim _result As String = Encrypt(data, _hash)
Return _result
End Function
Function DecryptWithHash(ByVal data As String, ByVal passToHash As String) As String
Dim _hash As String = getMd5Hash(passToHash)
Dim _result As String = Encrypt(data, _hash)
Return _result
End Function
Function getMd5Hash(ByVal input As String) As String
' Create a new instance of the MD5CryptoServiceProvider object.
Dim md5Hasher As New MD5CryptoServiceProvider()
' Convert the input string to a byte array and compute the hash.
Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input))
' Create a new Stringbuilder to collect the bytes
' and create a string.
Dim sBuilder As New StringBuilder()
' Loop through each byte of the hashed data
' and format each one as a hexadecimal string.
Dim i As Integer
For i = 0 To data.Length - 1
sBuilder.Append(data(i).ToString("x2"))
Next i
' Return the hexadecimal string.
Return sBuilder.ToString()
End Function
我的代码中的属性有 Get:
Dim _dataC As String = ReadFile(filename)
Dim _dataR As String = Crypt.Decrypt(_dataC, password)
Dim _result = tmpS.ReadString(_dataR)
并设置:
Dim _tmpS As New Custom.Serialization(Of Object)
Dim _tmpRaw As String = _tmpS.WriteString(value)
Dim _tmpCrypt As String = Crypt.Encrypt(_tmpRaw, password)
WriteFile(tmpPath, _tmpCrypt)
您必须定义自己的序列化,并读取/写入文件:
My.Computer.FileSystem.WriteAllText(filename, data, False)
_result = My.Computer.FileSystem.ReadAllText(FileName)