Decrypting encrypted data in config file

This is something which has been available in the .NET Framework since, well, forever. I’m talking about encrypting data in the config file of your (web)application. Every time I studied for the Microsoft developer exams I was reminded on this feature and thought “Hey, I really should use this in the next project”. Up until now I’ve never used this feature though.

The project I’m currently working on has some setup which encrypts the the config file when it’s deployed. A great feature, but this means I can’t read and edit the config file anymore. Manually editing the file shouldn’t be done anyway, but reading it would be nice though.

I knew this data could be decrypted also, but not how to do it exactly. Lucky for me this is a really old feature and there are dozens of people who have written something about it. This article on MSDN helped me out the most. I also read the feature had became available in the .NET Framework 2.0, apparently this wasn’t available in version 1.1.

As with most encrypting algorithms you need some kind of seed to create a stronger (and safer) encryption. If I’m not mistaken this method used the machine key of the computer it’s encrypted on. That’s not all too bad, but this means you can’t decrypt the encrypted data on a system with a different machine key.

The linked article says the machine key is stored in %windir%\system32\Microsoft\Protect\S-1-5-18, which probably is right, but I haven’t checked that out as I can’t log in on the server(s).

If you have encrypted the files, or are able to retrieve the machine key, it’s possible to decrypt the data using the aspnet_regiis tool (Visual Studio Prompt).

If you’d want to decrypt the appSettings block of a website in a virtual directory called virtualDir, the following line should suffice:

aspnet_regiis -pd "appSettings" -app "/virtualDir"

I tried this myself and it didn’t work. The following error was thrown:

Failed to decrypt using provider 'DataProtectionConfigurationProvider'. Error message from the provider: Key not valid for use in specified state. (Exception from HRESULT: 0x8009000B) (C:\VRIESJAN\ApplicationDir\Source\CustomerApp\CustomerApp.Presentation\web.config line 104)

This probably had something to do with me not having the correct machine key on my system. Lucky for me the sysadmin could discover the values through IIS Manager so there wasn’t a real loss, but this is exactly the reason why I haven’t implemented such a thing in a solution of mine. It makes reading production data a lot harder.


comments powered by Disqus