X509Certificate - Keyset does not exist

Viewed 63420

I have a WinForms application that consumes a WCF, and pass as a parameter to a function a certificate:

mySvcClient.SendDocument(cert.Export(X509ContentType.SerializedCert, "password"));
...

In WCF service, I recreated the certificate from the array of bytes:

public void SendDocument (byte[] binaryCert)
{   
     X509Certificate2 cert = new X509Certificate2(binaryCert, "password");
...

But when using the certificate to sign a xml, I got the error "Keyset does not exist":

if (cert.HasPrivateKey) // WORKS!!!
{   
    signedXml.SigningKey = cert.PrivateKey; // THROW "keyset does not exist" EXCEPTION
...

In my computer, the application works 100%! But in the WebServer, I got this error!

The question is: even X509Certificate2 recreated from an array of bytes, I need some special permission to access private key?

Thank you!

9 Answers

Application Pool Identity accounts don't have access to the certificate store by default.

Either you change to Network Services account as pointed by Vaibhav.Inspired or you give access to the certificate.

To allow access do the following command:

WinHttpCertCfg.exe -g -c LOCAL_MACHINE\MY -s "IssuedToName" -a "AccountName"

Notes:

- The tool may need to be installed first. The setup will place the tool at `C:\Program Files (x86)\Windows Resource Kits\Tools\WinHttpCertCfg.exe`.
- `IssuedName` is the issuer property of the certificate that the application will attempt to access
- The command must be run from command prompt with elevated privileges

Reference :https://support.microsoft.com/en-us/help/901183/how-to-call-a-web-service-by-using-a-client-certificate-for-authentica Step 2

Also you need to enable the Mark this key as exportable option when installing the certificate.

couple of troubleshooting steps:

  1. Run your program as Administrator
  2. If it is web app deployed in IIS -> then add the IIS_IUSRS to the Certificate permissions. Select certificate in Personal, Right Click-> Manage Private Keys -> Add the user.
  3. Run Visual Studio in Admin mode if in Debug to get this problem sorted out

If you are able to debug the application, try running the IDE on admin mode..you can also add new users from MMC.

I had the same issue on c# console application and after reading answeres here I thought that problem was in permissions. Then I run visual studio as administrator and it worked.

Related