February 22, 2021 06:20 by
Peter
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>
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"
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.
HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.