Вопрос по encryption, security, connection-string, vb.net, .net – Как безопасно хранить строку подключения в приложении WinForms?
Мне нужно знать, как обычно хранить строку подключения к серверу SQL для приложения WinForms в VB.NET.
Я искал в сети, и я нашел ответы на каждый из следующих вопросов:
How do I read app.config values How to do it in ASP.NET Reference: this SO question. How do I store a connection string (unencrypted thus unsafe)Я хотел бы получить полный ответ о том, как сохранить строку подключения в VB.NET вapp.config
(или жеsettings.settings
если это лучше) надежно.
Является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, который жестко кодирует секретный ключ.
http://msdn.microsoft.com/en-us/library/89211k9b(v=vs.80).aspx
Релевантная информация:
Это входит вmachine.config файл:
<configProtectedData defaultProvider="RsaProtectedConfigurationProvider">
<providers>
<add name="RsaProtectedConfigurationProvider"
type="System.Configuration.RsaProtectedConfigurationProvider, ... />
<add name="DataProtectionConfigurationProvider"
type="System.Configuration.DpapiProtectedConfigurationProvider, ... />
</providers>
</configProtectedData>
И это код приложения:
Shared Sub ToggleConfigEncryption(ByVal exeConfigName As String)
' Takes the executable file name without the
' .config extension.
Try
' Open the configuration file and retrieve
' the connectionStrings section.
Dim config As Configuration = ConfigurationManager. _
OpenExeConfiguration(exeConfigName)
Dim section As ConnectionStringsSection = DirectCast( _
config.GetSection("connectionStrings"), _
ConnectionStringsSection)
If section.SectionInformation.IsProtected Then
' Remove encryption.
section.SectionInformation.UnprotectSection()
Else
' Encrypt the section.
section.SectionInformation.ProtectSection( _
"DataProtectionConfigurationProvider") 'this is an entry in machine.config
End If
' Save the current configuration.
config.Save()
Console.WriteLine("Protected={0}", _
section.SectionInformation.IsProtected)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
UPDATE 1
Спасибо @wpcoder, заэта ссылка
The connection string can only be decrypted on the computer on which it was encrypted
,updated MS link for the article could provide the solution