How to encrypt sensitive information in web/app config file – .net/C#


When you create any web application, console app or any other apps, you need to keep connection strings, passwords or any other sensitive information in config file. We can easily encrypt these without much efforts or code changes.

ASP.NET IIS Registration tool enables you to encrypt and de-crypt the web config section info.

Steps to encrypt –

  1. Run Command Prompt (cmd.exe) as admin
  2. Go to path – C:\Windows\Microsoft.NET\Framework\v4.0.30319 . You can use following command – cd “C:\Windows\Microsoft.NET\Framework\v4.0.30319”
  3. Now run following command- ASPNET_REGIIS -pef “connectionStrings” “D:\MyCode\w3techschools” . Replace your config path; in above command my code path is- “D:\MyCode\w3techschools”.
  4. Now you will see your config file has connection string as encrypted.

In above command you have given name of section- “connectionStrings”, so it’ll encrypt your connection string section. Similarly you can encrypt other sections like -appSettings or even your any custom section created.

Similarly you can decrypt your connectionstring with below command (needs to be run as Admin only on same machine where it was encrypted)

ASPNET_REGIIS -pdf “connectionStrings” “D:\MyCode\w3techschools”

Here are key benefits/features of this way of encryption:-

  1. No code changes required. You can use your connection string reading code in same existing way. So you can encrypt these connectionstrings in any environments directly without need of deployment.
  2. This encryption uses machine specific keys, so any file encrypted in one machine can not be decrypted anywhere else.
  3. Only users with admin privileges can execute these command.

Hopefully it’ll help you in some way. In next post, I’ll share details of how you can create custom app settings and encrypt those. In practical scenarios, you do not need to encrypt all the appsettings but certain appsettings with any sensitive information e.g. password of any email box etc.

Happy Learning!

Let’s Learn and Grow!

Leave a Reply