Monday, 8 December 2008

Encrypting config sections on the fly in .Net

Question:
In a asp.net application I want to keep some config sections encrypted. How do I do this?



Answer:
On application start check if the section is encrypted and if it is not encrypt it on hte fly.

To do that, add the call to the encryption method to the Application_Start event in the global.asax.

protected void Application_Start(object sender, EventArgs e)
{
   EncryptConfig.EncryptSection("connectionStrings", "DataProtectionConfigurationProvider");
}


And then we have to write our EncryptSection method:
public class EncryptConfig
{
   public static void EncryptSection(string sectionName, string provider)
   {
      Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");

      ConfigurationSection section = config.GetSection(sectionName);

      if (section != null && !section.SectionInformation.IsProtected)
      {
         section.SectionInformation.ProtectSection(provider);
         config.Save();
      }
   }

   public static void DecryptSection(string sectionName)
   {
      Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");

      ConfigurationSection section = config.GetSection(sectionName);

      if (section != null && section.SectionInformation.IsProtected)
      {
         section.SectionInformation.UnprotectSection();
         config.Save();
      }
   }
}

No comments: