2008-09-29 82 views
5

我在VB.net“加密”这个功能(见下文)如何将加密的字符串保存到数据库?

Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24} 
Private iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219} 

Public Function Encrypt(ByVal plainText As String) As Byte() 
    ' Declare a UTF8Encoding object so we may use the GetByte 
    ' method to transform the plainText into a Byte array. 
    Dim utf8encoder As UTF8Encoding = New UTF8Encoding() 
    Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText) 

    ' Create a new TripleDES service provider 
    Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() 

    ' The ICryptTransform interface uses the TripleDES 
    ' crypt provider along with encryption key and init vector 
    ' information 
    Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv) 

    ' All cryptographic functions need a stream to output the 
    ' encrypted information. Here we declare a memory stream 
    ' for this purpose. 
    Dim encryptedStream As MemoryStream = New MemoryStream() 
    Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write) 

    ' Write the encrypted information to the stream. Flush the information 
    ' when done to ensure everything is out of the buffer. 
    cryptStream.Write(inputInBytes, 0, inputInBytes.Length) 
    cryptStream.FlushFinalBlock() 
    encryptedStream.Position = 0 

    ' Read the stream back into a Byte array and return it to the calling method. 
    Dim result(encryptedStream.Length - 1) As Byte 
    encryptedStream.Read(result, 0, encryptedStream.Length) 
    cryptStream.Close() 
    Return result 
End Function 

我想保存在SQL数据库加密的字符串。我该怎么做?

+1

,我不知道为什么会得到downvoted,看起来像一个有效的问题我 – 2008-09-29 03:25:22

回答

0

将字节数组编码为一个字符串。 0x00可以是“00”,0xFF可以是“FF”。或者你可以看看Base64

+0

我怎么编码字节数组转换为字符串? – sef 2008-09-29 03:10:30

0

指定的字符串应该与任何二进制数据没有区别。

如果您知道结果将会很小,您可以对其进行解码并将其保存在文本字段中。

3

只需存储在二进制列中。 (大多是从内存中完成,更正欢迎!)

CREATE TABLE [Test] 
(
    [Id] NOT NULL IDENTITY(1,1) PRIMARY KEY, 
    [Username] NOT NULL VARCHAR(500), 
    [Password] NOT NULL VARBINARY(500) 
) 

然后插入这样的:

Dim conn As SqlConnection 

Try 
    conn = New SqlConnection("<connectionstring>") 
    Dim command As New SqlCommand("INSERT INTO [Test] ([Username], [Password]) VALUES (@Username, @Password)", conn) 

    Dim usernameParameter = New SqlParameter("@Username", SqlDbType.VarChar) 
    usernameParameter.Value = username 
    command.Parameters.Add(usernameParameter) 

    Dim passwordParameter = New SqlParameter("@Password", SqlDbType.VarBinary) 
    passwordParameter.Value = password 
    command.Parameters.Add(passwordParameter) 

    command.ExecuteNonQuery() 

Finally 
    If (Not (conn Is Nothing)) Then 
     conn.Close() 
    End If 
End Try 
相关问题