Search content within the blog

Tuesday, November 11, 2008

Encrypting, Decrypting Web.Config Contents

Original Reference: http://www.dotnetcurry.com/ShowArticle.aspx?ID=185&AspxAutoDetectCookieSupport=1

prerequisite's:
  • Add a global.asax file to your application.
  • Import namespace: <%@ Import Namespace="System.Web.Configuration" %>
  • Configure Application_Start Event and Application_End Event for the application to automatically encrypt, decrypt web.config file contents.
  • For the decrypt part to work first stop the webserver (IIS or Development server) then close the browser.
There are various sections of typical web.config file that usually contain sensitive information:
  • - username and password used to connect to databases
  • - usernam and password needed for runtime impersonation of fixed identity
  • - your smtp server username and password
  • etc
By using the built-in Encryption methods we can protect those configuration sections, so even if someone somehow manages
to obtain our web.config files or just take a brief look at them , there will not be much for him to see there.

ASP.NET 2.0 comes with two encryption providers we can use to protect our configuration files:
  • DataProtectionConfigurationProvider
  • RSAProtectedConfigurationProvider
  • also you can implement your own Providers, because its a plugin based model
here is an example showing the encryption, decryption implemented in global.asax file.

void Application_Start(object sender, EventArgs e)

{
// Code that runs on application startup

#region --Encrypt web.config section contents region wise--
try
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ConfigurationSection objConfigSection = objConfig.GetSection("appSettings");
if (objConfigSection != null)
{
if (!objConfigSection.SectionInformation.IsProtected)
{
objConfigSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
objConfig.Save();
}
}
}
catch (Exception ex)
{

}
#endregion

}

void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
#region --Decrypt the sections of web.config that were encrypted--
try
{
//Configuration confg = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
//ConfigurationSection confStrSect = confg.GetSection("appSettings");
if (objConfigSection != null && objConfigSection.SectionInformation.IsProtected)
{
objConfigSection.SectionInformation.UnprotectSection();
objConfig.Save();
}

}
catch (Exception ex)
{

}
#endregion
}

No comments:

Post a Comment