I needed a solution to encrypt a single key in appSettings section in ASP.NET Web.config file. The article on MSDN Encrypting and Decrypting Configuration Sections tells about encrypting the whole section but I want to hide only a particular key.
It seems that apsnet_regiis could encrypt only sections, so I’ve found a way how to extract this key to another section and encrypt that section in one of StackOverflow answers http://stackoverflow.com/a/6224769
Here are the steps that must be done to get the result:
1. Add a line in configSections with the name of your new section
1 2 3 4 5 |
<configuration> <configSections> ... <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </configSections> |
2. Add new section under configuration
1 2 3 4 5 |
<configuration> ... <secureAppSettings> <add key="ValidationKey" value="..." /> </secureAppSettings> |
3. In .NET code get the section and key from it
1 2 3 4 5 |
var section = System.Web.Configuration.WebConfigurationManager.GetSection("secureAppSettings") as NameValueCollection; if (section != null && section["ValidationKey"] != null) { key = section["ValidationKey"]; } |
4. After you deploy your Web application to IIS, you should encrypt section secureAppSettings according to the MSDN article mentioned above. Launch Command Prompt as Administrator (it’s important!) and run command (something like this):
1 |
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -pe "secureAppSettings" -app "/WebApp" |