Retrieve X509Certificate2

10/4/2017 11:27:46 AM
Gravatar
Total Posts 1

Retrieve X509Certificate2

I have to retrieve X509Certificate2 from the currently inserted SmartCard for passing Client Credentials in an https Connection to and digitally signing message.
I try:

            CryptokiCollection template = new CryptokiCollection();

            template.Clear();

            template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, Storage.CKO_CERTIFICATE));
            template.Add(new ObjectAttribute(ObjectAttribute.CKA_CERTIFICATE_TYPE, Certificate.CKC_X_509));


            // Launchs the search specifying the template just created
            CryptokiCollection objects = session.Objects.Find(template, 10);

            //Cryptware.NCryptoki.X509Certificate cert;

            foreach (Object obj in objects)
            {
                X509Certificate2 cert2 = Utils.ConvertCertificate((Cryptware.NCryptoki.X509Certificate)obj);
                Utils.ShowCertificate(cert2);
                MessageBox.Show(cert2.HasPrivateKey.ToString());
            }

but HasPrivateKey is always FALSE.
When I install certificate in Windows store and read them, HasPrivateKey is True and I can use this to
create X509SecurityToken (WSE3.0).

How can I retrieve X509Certificate2 with PrivateKey from SmartCard ?

 

Thanks for your help,

10/9/2017 10:51:15 AM
Gravatar
Total Posts 300
Ugo Chirico http://www.ugochirico.com

Re: Retrieve X509Certificate2

Your code is correct and you are able to get a X509Certificate2.

An X509Certificate2 object has the private key only if it comes from the MS CSP (Cryptographic Service Provider).

In your case you are getting such a certificate from a PKCS#11 module, via NCryptoki. In this case you don't have the private key linked because it doesn't come from the CSP.

Using  a PKCS#11 module, the private key is usually linked to a certificate by CKA_ID or CKA_LABEL attributes and you can get an handle to the private key by searching the a private key object with a given CKA_ID value using the Find method