3

I've got a Windows service that needs to decrypt a config file, which I've encrypted on the same computer. (It doesn't need to be exportable.) I've been trying to overcome the ol' "The RSA key container could not be opened" error. I was able to do it manually:

c:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT AUTHORITY\NETWORK SERVICE"

but I need to accomplish this programatically. Based on two posts (one from SO and the other from CodeProject), I tried this:

private void GrantAccessToDecryptConfigFile()
{
    // programatically execute this command:
    //      c:\Windows\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT AUTHORITY\NETWORK SERVICE"

    string command = "-pa";
    string keyName = "NetFrameworkConfigurationKey";
    string userName = @"NT AUTHORITY\NETWORK SERVICE";
    string arguments = string.Format("{0} \"{1}\" \"{2}\"", command, keyName, userName);

    var psi = new ProcessStartInfo(@"C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe")
    {
        Arguments = arguments,
        UseShellExecute = false,
        CreateNoWindow = true
    };
    Process.Start(psi);
}

...but I'm still getting the same error when the Windows service tries to read the config file. What am I doing wrong?

Community
  • 1
  • 1
Eliezer
  • 429
  • 1
  • 9
  • 20
  • use string.Format function to avoid all the quotes here is where you can follow a simple example - http://stackoverflow.com/questions/13653991/passing-quotes-in-process-start-arguments – MethodMan Aug 19 '15 at 16:00
  • @MethodMan, I've edited my code above to reflect your suggestion. It's prettier now, but still doesn't work :-) / :-( – Eliezer Aug 19 '15 at 16:25

1 Answers1

0

I think all you need is a user with administrator privileges to run the Windows service. I'm guessing you run that command on an elevated command prompt because that's the only way I could make it work.

Similarly when I tried to run it on Visual Studio I got the same error. I started the Visual Studio with "Run as Administrator" and it succeeded.

Volkan Paksoy
  • 6,727
  • 5
  • 29
  • 40