Tuesday, September 25, 2007

How to Encrypt web.config section (ASP.NET 2.0)

How to Encrypt web.config section (ASP.NET 2.0)

ASP.NET 2.0 has now made this monumental task of encrypting configuration sections within Web.config a snap. There are no more excuses in .NET 2.0 as to why you haven't encrypted sensitive information, such as connection strings, in your Web.config. Not only can you encrypt config sections using aspnet_regiis from the command line, but you can also encrypt and unencrypt Web.config on the fly in code.Encrypt AppSettings ProgramaticallyShown below is a snippet of the application settings in Web.config in ASP.NET 2.0. Unprotected, you can read the application settings really easily. However, if this is private data that you don't want people to know, it is best to encrypt it. appSettings>The code for protecting and unprotecting sections in your Web.config is fairly trivial, because WebConfigurationManager-related classes handle all the work for you. I added two buttons to a web page, called btnProtect and btnUnProtect, to protect and unprotect on the fly. Here is the code of interest:

protected void UnProtect_Click(object sender, EventArgs e)
{
UnProtectSection("appSettings");
}
protected void Protect_Click(object sender, EventArgs e)
{
ProtectSection("appSettings","DataProtectionConfigurationProvider");
}
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();
}
}

No comments:

About Me

Bangalore, Karnataka, India