1

我想保护我的 app.config 文件中的连接字符串。我正在使用这段代码来做到这一点:

Public Shared Sub ProtectConnString()
    Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Dim configSection As System.Configuration.ConfigurationSection
    configSection = config.ConnectionStrings
    If Not (configSection Is Nothing) Then
        If Not (configSection.ElementInformation.IsLocked) Then
            configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
            configSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)
        End If
    End If
End Sub

但是,我注意到它使用的是机器级 DPAPI。我希望它使用用户级 DPAPI。我怎样才能做到这一点?

4

1 回答 1

0

如果您想使用用户级别的 DataProtectionConfigurationProvider 而不是机器级别,则将以下配置添加到 app.config 并添加如下所示的代码。

将此添加到 app.config

<configProtectedData>
  <providers>
    <add useMachineProtection="false" keyEntropy="" name="MyUserDataProtectionConfigurationProvider" 
type="System.Configuration.DpapiProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0, Culture=neutral, 
PublicKeyToken=b03f5f7f11d50a3a" />
  </providers>
</configProtectedData>

C# 代码

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            SectionInformation appSettingsSecInfo = config.GetSection("appSettings").SectionInformation;
            if (!appSettingsSecInfo.IsProtected)
            {
               appSettingsSecInfo.ProtectSection("MyUserDataProtectionConfigurationProvider");

                appSettingsSecInfo.ForceSave = true;

                config.Save(ConfigurationSaveMode.Full);
                MessageBox.Show("Config was not encrypted but now is encrypted");
            }
            else
            {
                MessageBox.Show("Config is already encrypted");
            }

MessageBox.Show("Some very secure information is about to be shown: " + ConfigurationManager.AppSettings["SomeImportantInfo"].ToString());
于 2014-05-21T19:46:35.580 回答