How To Encrypt an AppSettings Key In Web.config

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.
 
How To Encrypt a AppSettings Key In Web.config

Step 1 - Adding a section in configSections in web.config
  1. <configSections>
  2. <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  3. </configSections
Step 2 - Add secureAppSettings section under configuration
  1. <secureAppSettings>
  2. <add key="Password" value="XXXXXXXX"/>
  3. </secureAppSettings>
How To Encrypt a AppSettings Key In Web.config 
 
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"
 
How To Encrypt a AppSettings Key In Web.config
 
After execution of the above command, secure app settings section encrypted as below.
 
How To Encrypt a AppSettings Key In Web.config 
 
Step 4 - Accessing appsettings key from .NET code
 
To access the encrypted key value in code, we can write it like below.
  1. using System.Collections.Specialized;
  1. var passwordValue = "";
  2. var section = System.Web.Configuration.WebConfigurationManager.GetSection("secureAppSettings") as NameValueCollection;
  3. if (section != null && section["Password"] != null)
  4. {
  5. passwordValue = section["Password"];
  6. }
How To Encrypt a AppSettings Key In Web.config 
 
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!