我正在尝试使用对称加密来加密一些数据,并将解密所需的密钥与 MemoryStream 中的数据一起存储。(虽然我知道仅此一项在安全方面确实很愚蠢,但我将使用 RSA 来加密对称密钥。不过,现在,我正试图让这部分工作。)
我正在使用 FileHelpers 库来解析我的分隔符的数据(分号,因为我不相信我会在数据中有分号)。不幸的是,在我的解密函数中,当它解析时,它只返回一条记录。而且,如果我显示在此函数末尾创建的整个加密数据字符串,它似乎并没有使用多条记录。
我想知道当我创建新的加密流时,它是否默认为内存流的开头,所以当我写入加密数据时,它会覆盖我刚刚写入内存流的数据。你认为这是对的吗?
谢谢你的帮助!
Private Function Encrypt(ByVal data As String) As String
Dim utf8 As New UTF8Encoding
' Convert string data to byte array
Dim inBytes() As Byte = utf8.GetBytes(data)
' Create memory stream for storing the data we've manipulated
Dim ms As New MemoryStream()
Dim aes As New RijndaelManaged()
aes.KeySize = 256
Dim cs As New CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)
' Write key to beginning of memory stream
ms.Write(aes.Key, 0, aes.Key.Length)
' Add semicolon delimiter to memory stream
ms.Write(utf8.GetBytes(";"), 0, utf8.GetBytes(";").Length)
' Write IV to memory stream
ms.Write(aes.IV, 0, aes.IV.Length)
' Write semicolon delimiter to memory stream
ms.Write(utf8.GetBytes(";"), 0, utf8.GetBytes(";").Length)
' Ensure that the data we've just written is in the memory stream, before
' we add the encrypted data
ms.Flush()
' Write the encrypted data
cs.Write(inBytes, 0, inBytes.Length) ' encrypt
cs.FlushFinalBlock()
' Return encrypted data as string
Return Convert.ToBase64String(ms.GetBuffer(), 0, ms.Length)
End Function