Encrypt your config please…

ASP.NET 2.0 makes encrypting configSections in the web.config file a snap and there is no reason to not encrypt sensitive configSections. Just google for “encrypt config” and there are tons of code snippets waiting for you to copy and paste. Below is a code snippet that is found most commonly in google search results for protecting and unprotecting web.config file:

private void ProtectSection(string sectionName, string provider)
{ Configuration config
= WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section
= config.GetSection(sectionName); if (section != null && !section.SectionInformation.IsProtected) { section.SectionInformation.ProtectSection(provider); config.Save(); } } private void UnProtectSection(string sectionName) { Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); ConfigurationSection section = config.GetSection(sectionName); if (section != null && section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); config.Save(); } }  
You would usually call ProtectSection method in the Application_Start event in global.asax. As you can see, it accepts two parameters, sectionName (like “connectionStrings”) and provider which is basically an encryption services provider. ASP.NET ships with 2 default providers:
  • The Windows Data Protection API (DPAPI) Provider (DataProtectionConfigurationProvider) If you use this provider then the encryption keys are provided by the Windows OS. You don’t need to maintain the keys. However, this also means that you will need to deploy you application initially with a plain-text config file and then wait for your application logic to actually encrypt it.
  • RSA Protected Configuration Provider (RSAProtectedConfigurationProvider) If you use this options then you are also required to create key containers to hold the public and private keys used for encrypting and decrypting the config information.
Once the data is encrypted, you don’t need to change anything in your code while accessing the settings. The ASP.NET configuration classes are smart enough to decrypt and provide you plain-text when they come across encrypted configSections. Pretty cool eh!

Please note that you may never need to invoke the UnprotectSection method. It is only provided, just in case you want to revert back to a plain-text config file.

For a complete detailed tutorial on encrypting configSections see http://aspnet.4guysfromrolla.com/articles/021506-1.aspx

  • Share/Bookmark

Leave a comment

Your comment