Search code examples
c#windows-servicesprivate-keyx509certificate2

Setting private key in certificate hangs windows service


I have application and I have to use a certificate which requires a pin from prompt window.

I have following code.

SecureString password = GetPassword();
X509Certificate2 certificate = GetCertificate();

var cspParameters = new CspParameters(1,
                                     "ProviderName",
                                     "KeyContainerName",
                                     null,
                                     password);

certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);

Everything works fine in console application but when I run that code in windows service or console application started from task scheduler then application freezes on that line.

certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);

No exceptions, no progress.

I'm running windows service with the same credentials as an application.

Windows 10 / Windows Server 2012

Do you have any ideas what is wrong?


Solution

  • Ok, after a break I have found solution.

    I had to add impersonation around this line:

    certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);
    

    I used the same credentials like in my service and set LogonType as Interactive.