5

Question when running the following code:

X509Certificate2 cert = new X509Certificate2(@"C:\file.p12", "password", X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)cert.PrivateKey;

I get the following error: Keyset does not exist.

I have not added the certificate to a store, is this required to be able to access the private key?

1 Answer 1

12

Add the X509KeyStorageFlags.PersistKeySet option to the last argument of the X509Certificate2 constructor. Otherwise, when it loads the p12 file, it will not load the private key. Specifically:

X509Certificate2 cert = new X509Certificate2(@"C:\file.p12", "password",    
    X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)cert.PrivateKey;

If that fails, it may be a file permission issue on where the key is stored. See X509Certificate - Keyset does not exist for an explanation and example.

4
  • @Rutger I added an additional check in the answer.
    – akton
    Sep 11, 2012 at 8:51
  • I have not added the certificate to a store, is this required?
    – Rutger
    Sep 11, 2012 at 8:55
  • @Rutger The code is not adding to a certificate store but it is storing the private key in the key store (related but different concept). The issue maybe access to the key store.
    – akton
    Sep 11, 2012 at 8:58
  • It was indeed an access issue with the key store.
    – Rutger
    Sep 13, 2012 at 9:23

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.