Securing web.config passwords and secrets in .NET

by Tobias Lekman, 09 February, 2018

Sometimes we need to access remote systems that cannot use single sign-on or Kerberos, and are forced to store sensitive information in the web.config file. This could potentially be an issue if the server has access by several admins. In this case, you could encrypt the passwords.

If you have the ability to add malicious code, reverse engineer the DLL etc, then sure you can get around it but it is an adequate solution for stopping people with read access to see your secrets.

I wanted a simple solution to read/encrypt the appSetting values only, so wrote a class that:

  • Checks for the unencrypted value
  • Encrypts the value using a salt and in the scope of the IIS user account (you should use an AD account for your app pool in IIS)
  • Saves the new encrypted value and deletes the unencrypted value

You could then use the class as:

var password = SecureConfig.AppSettings("MyPassword");
var credentials = new NetworkCredential {
Domain ="MYDOMAIN",
UserName = "MYUSERNAME",
SecurePassword = password

The entire code is below. You need to add a reference to System.Security.