We keep some application data in configuration file like app settings, connection strings and many more. It may be some sensitive data like database credentials, SMTP credentials etc., and storing these information in config file as a plain text is not a good idea. To keep these information secure, we should encrypt and then store.
Before doing the encryption/decryption make sure you are following the proper file naming convention.
- Make sure the configuration section content is in a "web.config" file.
- if not, rename it to the "web.config" file before performing encryption/decryption.
Encryption
We will encrypt the below config file's appSettings section in our example.
Lets do the following steps to encrypt the appSettings section of the above configuration file.
- Open the command prompt as administrator
- Type "c:\windows\Microsoft.NET\Framework\<specificversion>" and press ENTER. Note: "specificversion" is .Net framework version
- Type the following command and ENTER
aspnet_regiis.exe -pef "<configuration section>" "<Configuration file physical location>" -prov "<protection configuration provider>" - Configuration section - The config section name which you want to encrypt like appSettings, connectionString etc.
- Configuration file physical location - Web.config file location
- Protection configuration provider - The encryption take place differently according to provider like "DataProtectionConfigurationProvider" or "RsaProtectedConfigurationProvider".
Example:
aspnet_regiis.exe -pef "appSettings" "c:\encryptionDemo" -prov "RsaProtectedConfigurationProvider" - After the step 3, the appSettings section in web.config file present at "c:\encryptionDemo" will get encrypted.
Decryption
The encrypted config section can be decrypted using the following command line.
aspnet_regiis.exe -pdf "appSettings" "c:\encryptionDemo"
The decrypted file will look like -
It is always recommended to store the sensitive data in configuration file as encrypted form only otherwise it can be compromised. Here we went through the very basic way of encryption / decryption. We can do in depth and secure level of encryption and decryption like use-account level and machine-level encryption and decryption.