Here is a common way to encrypt a section in web.config:
void EncryptConfig(bool encrypt)
{
string path = Request.ApplicationPath;
Configuration config = WebConfigurationManager.OpenWebConfiguration(path);
ConfigurationSection sec = config.GetSection("connectionStrings");
if (encrypt)
{
sec.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
}
else
{
sec.SectionInformation.UnprotectSection();
}
config.Save();
}
There is an alternative to the parameter that the protectSection takes in. Instead of RSAProtectedConfigurationProvider, you can use DataProtectionConfigurationProvider.
The second way to achieve the same goal is to use aspnet_regiis with a couple of switches to encrypt a section in the web.config file. Run Visual Studio command prompt and execute aspnet_regiis command followed by /pef switch, then the section you want to protect, and lastly the application path.
C:\>aspnet_regiis /pef "connectionStrings" "C:\...\MyWebApp"
Encrypting Configuration section...
Succeeded!
Encrypting Configuration section...
Succeeded!
In the sample above, the connectionStrings section of the web.config file in MyWebApp application is encrypted and protected (You need to specify the full path to the application). To unprotect a section, replace the switch /pef with /pdf.
No comments:
Post a Comment