如何在 WinForms 应用程序中安全地存储连接字符串?

问题描述:

我需要知道在 VB.NET 中为 WinForms 应用程序存储 SQL 服务器连接字符串的常用方法是什么.

I need to know what is the common way to store a SQL server connection string for a WinForms application in VB.NET.

我在网上搜索并找到了以下每个问题的答案:

I have searched the net and I found answers to each of the following questions:

  • 如何读取 app.config 值
  • 如何在 ASP.NET 中做到这一点参考:这个问题.莉>
  • 如何存储连接字符串(未加密,因此不安全)

我想要一个完整的答案,了解如何在 app.config(或 settings.settings,如果更好)中的 VB.NET 中安全地存储连接字符串.

I would like a full answer on how to store a connection string in VB.NET in app.config (or settings.settings if it's better) securely.

app.config 是正确的地方吗?我可以加密这些值吗?

Is app.config the right place? Can I encrypt these values?

简单地说,.net 框架允许您这样做,请参阅

Simply , the .net framework allows you to do that , see

http://msdn.microsoft.com/en-us/library/89211k9b(v=vs.80).aspx

相关信息:

这会进入 ma​​chine.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

更新 1

感谢@wpcoder,为这个链接

Thanks @wpcoder, for this link