Friday, 21 July 2017

C# - Encrypting the App.config

Sometimes when you are storing sensitive information in the App.config e.g. API keys or database connection strings, you don't want to store them in plain text. Fortunately, visual studio provides a command line tool that enables you to encrypt sections of your App.config. These are automatically decrypted by the ConfigurationManager when you try to access the settings.
  1. Create a copy of your App.config called web.config. This is because the command line tool you will use to encrypt your settings will look for a web.config.
  2. Open the Developer Command Prompt for VS
  3. Enter the following command:
    aspnet_regiis -pef [section to encrypt] [path containing web.config]
  4. Copy the contents of the web.config into the App.config.

It is best that you have a separate section from appSettings for your encrypted settings as this will mean you will be able to change plain-text settings e.g. API URLs or retry attempts, without having to go through the encryption process. To create this section your App.config before encryption could look as follows:

  <?xml version="1.0" encoding="utf-8" ?>
      <section name="EncryptedSettings" 
               type="System.Configuration.NameValueSectionHandler" />
      <supportedRuntime version="v4.0" 
                        sku=".NETFramework,Version=v4.5" />
      <add key="RetryAttempts" value="3" />
      <add key="username" value="username" />
      <add key="password" value="password" />

If your web.config existed in your C:\Encryption directory, it could be encrypted using the command:
aspnet_regiis -pef "EncryptedSettings" C:\Encryption
This section of the App.config can be accessed from the code as follows:

  string devUrl = string.Empty;
  var settings = ConfigurationManager.GetSection("EncryptedSettings") 
                 as NameValueCollection;
  var username = settings["username"];