Thursday, February 21, 2008

Encrypt Web.config

Asp.net 2 has new features that you can encrypt the web.config programatically.

#Region "Protect/Unprotect Methods"

// Code taken verbatim from David Hayden's blog [http://davidhayden.com/blog/dave/]

// Entry: Encrypt Connection Strings AppSettings and Web.Config in ASP.NET 2.0 - Security Best Practices

// [http://davidhayden.com/blog/dave/archive/2005/11/17/2572.aspx]

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();

}

}

#endregion

Chris Blankenship provides a page which allows you to encrypt the web.config based on sections of the web.config. Once you encrypted the section, the application will still be running without problem, you don't have to decrypt it for the program to use it, it does it automatically.

Encrypt that Web.Config

blog comments powered by Disqus