Don't have PrivateKey after get X509Certificate2

10/3/2012 5:22:05 AM
Gravatar
Total Posts 1

Don't have PrivateKey after get X509Certificate2

Hi,

I have to export certificate from X509Certificate2, and here is my code:

            CryptokiCollection myTemplate = new CryptokiCollection();
            myTemplate.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_CERTIFICATE));
            myTemplate.Add(new ObjectAttribute(ObjectAttribute.CKA_CERTIFICATE_TYPE, Certificate.CKC_X_509));
            CryptokiCollection myObjects = session.Objects.Find(myTemplate, 1);
            if (myObjects.Count == 0)
            {
                Console.WriteLine("CERTIFICATE NOT FOUND");
            }
            Cryptware.NCryptoki.X509Certificate certificate = (Cryptware.NCryptoki.X509Certificate)myObjects[0];
            X509Certificate2 myCert = Utils.ConvertCertificate(certificate);
            X509Certificate2UI.DisplayCertificate(myCert);
            StreamWriter myStreamWriter = new StreamWriter("C:\\myCert.cer");
            myStreamWriter.Write(myCert.Export(X509ContentType.Cert));
            myStreamWriter.Close();

The code "X509Certificate2UI.DisplayCertificate(myCert);" was success, and it showed my Certificate Infomation. But when i opened myCert.cer file, it showed "This file is invalid for use as the following: Security Certificate". When i set break point to this line: "X509Certificate2UI.DisplayCertificate(myCert);", i saw myCert.HasPrivateKey = false, and myCert.PrivateKey = null. I think that why my certificate file was error. please help me solve my problem.

Thanks.

Hideo

10/3/2012 10:12:48 AM
Gravatar
Total Posts 300
Ugo Chirico http://www.ugochirico.com

Re: Don't have PrivateKey after get X509Certificate2

You are extracting the certificate, not the private key and the certificate contains the public key only, non the private key.

To extract the private key read this:

http://wiki.ncryptoki.com/How-to-extract-a-private-key.ashx