Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Encrypt .NET Configuration File

0.00/5 (No votes)
25 Apr 2011 1  
How to encrypt .NET configuration file

Under some scenarios, developers want to encrypt some sections inside app.config or web.config file. This article How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA describes how to do so clearly, Scott Guthrie also posted one: Encrypting Web.Config Values in ASP.NET 2.0.

However, in the posts above, they use aspnet_regiis.exe and it seems it doesn’t directly support app.config, if we want to encrypt app.config for Windows Form or WPF applications While I tried use it to encrypt my app.config file, it generates a web.config which means my Winform definitely can’t use it, even if I copy the encrypted appSettings section from this generated web.config to my own app.config (ConfigurationManager.AppSettings[EncryptedKeyName] is null after I did that).

Config Encrypt

Encrypted WebConfig

After several minutes of Google search and testing, I found the code below is simple and very straight forward to achieve this:

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

SectionInformation appSettingsSecInfo = config.GetSection(
   "appSettings").SectionInformation;
if (!appSettingsSecInfo.IsProtected)
{
    Console.WriteLine("The configuration file has NOT been protected!");

    // Encrypt this section by using security provider 
    // (RsaProtectedConfigurationProvider or DpapiProtectedConfigurationProvider).
    appSettingsSecInfo.ProtectSection("RsaProtectedConfigurationProvider");
    appSettingsSecInfo.ForceSave = true;

    config.Save(ConfigurationSaveMode.Full);
}

This code snippet will do the encryption job and works for both app.config/web.config. Here is the MSDN definition page for SectionInformation.ProtectSection.

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here