Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

X509Certificate2 p12 is store required?

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?

like image 299
Rutger Avatar asked Sep 11 '12 08:09

Rutger


1 Answers

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.

like image 122
akton Avatar answered Nov 03 '22 10:11

akton