Mastodon

Securing your data in Web.config

Jun 05, 2018 by Kolappan N

Why use Web.config instead of say database?

There are some advantages for storing data in web.config files.

How secure is web.config before?

The IIS Server will not serve the web.config file to the client. It is part of your source control, meaning a person having access to it will also have access to your API source code. So, it is somewhat secure file.

How do we secure it

There are options to secure entire sections of web.config files. But my approach is to encrypt the data string and store it in the config file.

  1. Create a helper function for decrypting and encrypting data based on a key.
  2. Encrypt your data with a key and store the encrypted string in the web.config.
  3. Use a helper function like the one below to decrypt the keys at runtime.
private const readonly string decryptKey = "";
public string GetFromConfig(string key)
{
   var encryptedText = System.Web.Configuration.WebConfigurationManager.AppSettings[key];
   var plainText = Decrypt(encryptedText, decryptKey);
   return plainText;
}

In this method, the decryption key will be stored in the code and is common for all the environments. But it allows you to change the data in the web.config without the need to recompile the application.

As a bonus, you can change the decryption key and with it the encrypted data with each version / release to further improve security.

This blog post is based on my answer in SO.