Protect Config File with User-Level DPAPI (WinForms)

876 Views Asked by At

I want to protect connection strings in my app.config file. I'm using this code to do it:

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

However, I notice it's using Machine-Level DPAPI. I'd like it to use User-Level DPAPI. How can I make this happen?

1

There are 1 best solutions below

0
On

If you want to use a user level DataProtectionConfigurationProvider as opposed to machine level than add the configuration below to app.config and add the code as shown below.

Add this to 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# Code

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