Tuesday, June 1, 2010

Web.Config Encryption

Encryption is possible in 2 ways

1) programatically
2) aspnet_regiis.exe, a command-line program

and the following sections can be encrypted.

, , and .

Each of these sections can optionally be encrypted, either programmatically or through aspnet_regiis.exe, a command-line tool. When encrypted, the scrambled text is stored directly in the configuration file. For example, if we were to encrypt the section above the resulting Web.config file might look like the following: (Note: a large chunk of the has been removed for brevity.)

e.g



AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAed...GicAlQ==




There are some configuration sections that you cannot encrypt using this technique:












In order to encrypt these configuration sections you must encrypt the value and store it in the registry. There's an aspnet_setreg.exe command-line tool to help along with this process

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.

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:

Post a Comment