2014-01-24 36 views
1

我想保護我的app.config文件中的連接字符串。我正在使用此代碼來執行此操作:用用戶級別的DPAPI保護配置文件(WinForms)

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 

但是,我注意到它使用的是Machine-Level DPAPI。我希望它使用用戶級DPAPI。我怎樣才能做到這一點?

回答

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());