Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 216
Degusto Avatar asked Jan 24 '17 18:01

Degusto


1 Answers

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.

like image 135
Degusto Avatar answered Nov 15 '22 00:11

Degusto