在我的工作中,我們將完整的連接字符串存儲在app.config中,但我們使用AES256對它們進行加密。它工作得很好,並增加了相當的安全性。我們編寫了一個小工具,可以讓您加密和解密連接字符串,因此編輯app.config文件非常簡單。我們只在應用程序中使用硬編碼的加密密鑰,因此如果有人關心反編譯程序集,那麼可能會發現它,但它提高了足以滿足我們需求的標準。下面是我們用來加密和解密的連接字符串類:
Public Class Aes256Base64Encrypter
Public Function Decrypt(ByVal encryptedText As String, ByVal secretKey As String) As String
Dim plainText As String = Nothing
Using inputStream As MemoryStream = New MemoryStream(System.Convert.FromBase64String(encryptedText))
Dim algorithm As RijndaelManaged = getAlgorithm(secretKey)
Using cryptoStream As CryptoStream = New CryptoStream(inputStream, algorithm.CreateDecryptor(), CryptoStreamMode.Read)
Dim outputBuffer(0 To CType(inputStream.Length - 1, Integer)) As Byte
Dim readBytes As Integer = cryptoStream.Read(outputBuffer, 0, CType(inputStream.Length, Integer))
plainText = Unicode.GetString(outputBuffer, 0, readBytes)
End Using
End Using
Return plainText
End Function
Public Function Encrypt(ByVal plainText As String, ByVal secretKey As String) As String
Dim encryptedPassword As String = Nothing
Using outputStream As MemoryStream = New MemoryStream()
Dim algorithm As RijndaelManaged = getAlgorithm(secretKey)
Using cryptoStream As CryptoStream = New CryptoStream(outputStream, algorithm.CreateEncryptor(), CryptoStreamMode.Write)
Dim inputBuffer() As Byte = Unicode.GetBytes(plainText)
cryptoStream.Write(inputBuffer, 0, inputBuffer.Length)
cryptoStream.FlushFinalBlock()
encryptedPassword = System.Convert.ToBase64String(outputStream.ToArray())
End Using
End Using
Return encryptedPassword
End Function
Private Function getAlgorithm(ByVal secretKey As String) As RijndaelManaged
Const salt As String = "put a salt key here"
Const keySize As Integer = 256
Dim keyBuilder As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(secretKey, Unicode.GetBytes(salt))
Dim algorithm As RijndaelManaged = New RijndaelManaged()
algorithm.KeySize = keySize
algorithm.IV = keyBuilder.GetBytes(CType(algorithm.BlockSize/8, Integer))
algorithm.Key = keyBuilder.GetBytes(CType(algorithm.KeySize/8, Integer))
algorithm.Padding = PaddingMode.PKCS7
Return algorithm
End Function
End Class
事實上,我們認爲包裹其中的硬編碼加密密鑰對應的ConnectionStringEncrpyter類裏面。
我應該認爲這樣做,謝謝。 – MarioDS
由於這個問題得到了相當多的意見,我編輯了你的答案,以確保信息不會丟失,如果鏈接斷裂。 – MarioDS
@pylover _這回答了這個問題,但沒有提供一個合適的解決方案_。從MS鏈接提供; **說明**:「連接字符串只能在加密的計算機上解密」。 [文章更新的MS鏈接可以提供解決方案](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/protecting-connection-information) – wpcoder