Sometimes we come across a scenario where we need to encrypt a sensitive key in appSettings section in Web.config file. This blog demonstrates the steps to encrypt a key and read the respective key in an ASP.NET application.
I have an appsettings key that is being called from .NET application. Before we are encrypting appsettings key in web.config.
Step 1 - Adding a section in configSections in web.config
- <configSections>
- <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
- </configSections
Step 2 - Add secureAppSettings section under configuration
- <secureAppSettings>
- <add key="Password" value="XXXXXXXX"/>
- </secureAppSettings>
Step 3 - Execute command from command prompt to encrypt secureAppSettings section
Open command prompt and execute the below commands.
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
aspnet_regiis.exe -pef "secureAppSettings" "your application web config path" -prov "DataProtectionConfigurationProvider"
After execution of the above command, secure app settings section encrypted as below.
Step 4 - Accessing appsettings key from .NET code
To access the encrypted key value in code, we can write it like below.
- using System.Collections.Specialized;
- var passwordValue = "";
- var section = System.Web.Configuration.WebConfigurationManager.GetSection("secureAppSettings") as NameValueCollection;
- if (section != null && section["Password"] != null)
- {
- passwordValue = section["Password"];
- }
Excellent! We successfully encrypted to a key in appsettings in web.config. Similarly, we can do the same steps while deploying a Web application to IIS.
Happy Learning!