Storing Sensitive Data in Config Files

Many people usually ask how they can store sensitive data in configuration files.Configuration files are definitely a bad place to store sensitive data like user credentials or connection strings.

Here and here you will find some guidelines about storing sensitive data in configuration files.

You won’t find a silver bullet that solves these issues. In order to mitigate the threads associated with this topic, you should add as many security levels as you can (WhatIsThePrincipleOfDefenseInDepth).
One common approach is to store a registry path in your config file and save in that registry entry (with a strong ACL) the encrypted data with DPAPI (local machine mode). You just have a tool (aspnet_setreg.exe) that does this here.

The main goal of this tool is to encrypt sensitive data in the following configuration sections:·         <identity userName= password= /> ·         <processModel userName= password= /> ·         <sessionState stateConnectionString= sqlConnectionString= /> However, you might use this handy tool to your own config sections. To encrypt some sensitive data (ie some connection string) you may follow these steps: 1) Alter installing the above tool, run this from the command prompt:   aspnet_setreg.exe -k:Software\YourCompany\YourKey -c:"Data Source=local;Initial Catalog=MyDB;User ID=neo;Password=Logos$31687#" 2) On your connection element of the configuration file put something like this:   <connection name="myName" value="registry:HKLM\Software\YourCompany\YourKey\ASPNET_SETREG,sqlConnectionString" /> 3) Set the registry entry ACL as stated on the tool download link above.


To decrypt this data you might use this sample:

 string connection = Encoding.Unicode.GetString( ProtectedData.Decrypt(                                                               registryBytes ) ); 

ProtectedData is the managed DPAPI wrapper in the Open Source NCrypto Proyect.
registryBytes is the byte array from the registry entry that create the tool
mentioned above. You may use the managed registry API located in the “Microsoft.Win32” namespace to read these bytes.

If you want to use a full source code solution (not using the aforementioned tool), it’s very easy to use the same ‘ProtectedData’ class to make the encryption process and store the encrypted data in whatever registry entry you like. However you will have to code a bit more and don’t forget to add a strong ACL to your registry entry.
Enjoy it. In case you don´t know how to grab those encrypted bytes from the registry, here is a small snippet:


byte[] registryBytes;
using( RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"Software\YourCompany\YourKey\ASPNET_SETREG"))
{
      registryBytes = (byte[])reg.GetValue("sqlConnectionString");
}


 

3 Comments

Comments have been disabled for this content.