Sunday, June 27, 2010

Config Encryption for .Net

I know there are many examples of configuration file encryption on the net but I needed some place where I can go to remind myself how it works again without having to Google for long periods again in the future to figure stuff out.

I want to write about Executable configuration encryption and Web configuration encryption. It is actually simple but there are a few things you need to know before diving in. Executable and Web encryption (through the standard way) cannot be mixed, you can't for instance point to a web project in order to open with the ConfigurationManager and vice versa with the WebConfigurationManager. This is pretty obvious but sometimes when you're working with deployment code, you are sometimes tempted to try one with the other.

Secondly, when using the ConfigurationManager.OpenExeConfiguration() you have to give the full path to the EXE file. This EXE file must be found along with the configuration file.
With the WebConfigurationManager.OpenWebConfiguration() you have to give a full or relative path to an IIS Virtual Directory. If you just want to reference the Virtual Directory in the root path from DefaultWebsite, just add the '/' before the Virtual Directory name. This Virtual Directory needs to point to a directory with the web.config file.

Now once you have an instance of a Configuration (via ConfigurationManager or WebConfigurationManager) you can now finally decide which section you want to encrypt and encrypt it.

Configuration config = GetConfgiruation(); // Do as explained above
ConfigurationSection section = config.GetSection("appSettings"); // Example
SectionInformation sectionInfo = section.SectionInformation;
  sectionInfo.ForceSave = true;

There you have it. Just one thing though. You can't copy this file to another machine and attempt to decrypt it because .Net uses a generated token on your Machine to encrypt/decrypt.

No comments: