Pages

Thursday, January 3, 2008

Encrypting Configuration Information in ASP.NET 2.0 Applications

The .NET Framework 2.0 libraries include the capabilities to encrypt most any configuration sections within the Web.config or machine.config files. Configuration sections are those XML elements that are children of the or elements.

Encryption Options
Protecting configuration sections in ASP.NET 2.0 uses the provider model, which allows for any implementation to be seamlessly plugged into the API. The .NET Framework 2.0 ships with two built-in providers for protecting configuration sections:

The Windows Data Protection API (DPAPI) Provider (DataProtectionConfigurationProvider) - this provider uses the built-in cryptography capabilities of Windows to encrypt and decrypt the configuration sections. By default this provider uses the machine's key. You can also use user keys, but that requires a bit more customization.Since the keys are machine- or user- specific, the DPAPI provider does not work in settings where you wan to deploy the same encrypted configuration file to multiple servers.
RSA Protected Configuration Provider (RSAProtectedConfigurationProvider) - uses RSA public key encryption to encrypt/decrypt the configuration sections. With this provider you need to create key containers that hold the public and private keys used for encrypting and decrypting the configuration information.

Programmatically Encrypting Configuration Sections
The System.Configuration.SectionInformation class abstractly represents a configuration section. To encrypt a configuration section simply use the SectionInformation class's ProtectSection(provider) method, passing in the name of the provider you want to use to perform the encryption. To access a particular configuration section in your application's Web.config file, use the WebConfigurationManager class (in the System.Web.Configuration namespace) to reference your Web.config file, and then use its GetSection(sectionName) method to return a ConfigurationSection instance. Finally, you can get to a SectionInformation object via the ConfigurationSection instance's SectionInformation property.

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: