Best way to store encryption keys in .NET C#

ganeshran picture ganeshran · Feb 11, 2011 · Viewed 59.1k times · Source

In our application we have a lot of sensitive configuration settings, which we are storing in a xml file which is again encrypted.

This secure file has to be decrypted in runtime and the configuration values read. but an issue arises that the key and initialization vector is hardcoded in the code and hence anyone can read it using Reflector.

What is the best way to store encryption keys in .NET so no one can read them using Reflector?

Answer

GvS picture GvS · Feb 11, 2011

If you want to protect your data from other users. Take a look at the ProtectedData class.

(Disclaimer: Protecting your data to create a copy protection scheme is not covered in this answer).

This classes uses the DPAPI from Windows, to encrypt and decrypt data on user or machine level.

Using ProtectedData/DPAPI frees you from handling keys and securing the data yourself. And you can choose to protect the data for the current user. The data can be read from different computers, by the same domain users.

If you want create your own key. You can create a key per user/machine, and store this key in the registry. Because the registry can be secured, only the current user can read the key back. I know the registry has bad karma, but is actually very good at storing data like this.

PS: Do not put the IV in your code. Create a new IV every time, and put it in front of the data.