Encrypting and Decrypting Configuration Sections in web.config file

21 July 2022 | Viewed 5059 times

Usually in in ASP.NET applications the Web .config file stores sensitive information. Examples of sensitive information include usernames, passwords, connection strings, and encryption keys.

Why we need to encrypt configuration sections?

Storing sensitive information in a non-readable format improves the security of your application by making it difficult for an attacker to gain access to the sensitive information, even if an attacker gains access to the file, database, or other storage location.

How to encrypt configuration sections?

To secure information in configuration files, ASP.NET provides a feature called protected configuration, which enables us to encrypt sensitive information in a configuration file.

The Aspnet_regiis.exe tool (located in the %SystemRoot%\Microsoft.NET\Framework\versionNumber folder) includes options for encrypting and decrypting sections of a Web .config file, creating or deleting key containers, exporting and importing key container information, and managing access to a key container.

Step1: Open Command Prompt in Administrator mode

Step2: Navigate to .Net Framework location
Command
cd \WINDOWS\Microsoft.Net\Framework\v4.0.*

Step3: Run below command to encrypt the configuration section
Command
ASPNET_REGIIS -PEF "connectionStrings" "C:\Repository\ProjectName"
ASPNET_REGIIS -PEF "appSettings" "C:\Repository\ProjectName"
ASPNET_REGIIS -PEF "system.web/sessionState" "C:\Repository\ProjectName"

Command
PEF - Password Encrypted Format
Arguments
"connectionStrings" -Configuration section from config file
"C:\Repository\ProjectName" - Location of the web .config file to encrypt

You have to repeat Step3 for each section you want to encrypt.

How to decrypt configuration sections?

During deployments or upgrade we may need to change the connection strings or need to add/remove/update the appSetting keys. So, to make changes to Configuration section we need to decrypt and then update and again encrypt.

Step1: Open Command Prompt in Administrator mode

Step2: Navigate to .Net Framework location
Command
cd \WINDOWS\Microsoft.Net\Framework\v4.0.*

Step3: Run below command to encrypt the configuration section
Command
ASPNET_REGIIS -PDF "connectionStrings" "C:\Repository\ProjectName"
ASPNET_REGIIS -PDF "appSettings" "C:\Repository\ProjectName"
ASPNET_REGIIS -PDF "system.web/sessionState" "C:\Repository\ProjectName"

Command
PDF - Password Decrypted Format
Arguments
"connectionStrings" -Configuration section from config file
"C:\Repository\ProjectName" - Location of the web .config file to encrypt

PreviousNext