RLH RLH - 9 months ago 38
C# Question

How can a user encrypt a configuration file, for use by a service application?

Ok, I'm asking a rather generic question to a specific problem. I have searched this more ways than I can count, and nothing seems to work. Let me explain my need, and I'll then mention a few of the best solutions I've found and why they don't work in my case.

I have an application that a user launches and uses to setup various configuration values that are saved to an app.config file. This is a WPF application. Specifically, some of these values are HIGHLY sensitive, sysadmin accounts.

This data needs to encrypted, in some form or fashion, and it needs to be decrypted by Windows Service that will be launched by the application, once the configuration is finished. The general solution given for this scenario is to use DPAPI which has two modes for encryption-- User and Local Machine.

If you user User, then your application an encrypt and decrypt data as much as it desires, so long as the current user that initially encrypts the data is doing the decryption. My problem is that when the service is started, it also have to restart on reboots and will specifically be running under a different user account.

The next approach, using DPAPI, is to encrypt the data as the Local Machine. This means that when ANYONE logs into the machine, they can decrypt the sensitive data. This is a BIG no-no!

What I need is to have a way for a user to specify the data they want to encrypt and then specify an account (in this case, what will be the service account) and use that account for data encryption.

I can't find how to do this. This MSDN article alludes that can be done. (See section 'Web Farm Scenarios'.) The TL;DR on that article is that for ASP.Net applicataions, you can use the RsaProtectedConfigurationProvider to encrypt your data, and export the keys for use with a specific web account. This is close to what I want, but in my case I need to create the data in a WPF application, and store it for use in a Windows Server Service.

How can this be done?

Answer Source

You can accomplish something similar to this using something as mundane as EFS, but unlike raw DPAPI, a recovery key might bypass the protection. In either case, a local admin could replace your program with his own and it would have full access to the decrypted data.

As for setting this up, the easiest way to do that would be to interactively log on with the service account and either create the protected data using System.Security.Cryptography.ProtectedData or create a file in a directory marked with the "encrypt" attribute.