Certificate to pfx with private key...?

1.3k views Asked by At

I've certificate which I can install from dongle. When I view that installed certificate using IE. It shows me it has private key as below.

enter image description here

But when I try to export that certificate to .pfx using my c# code, the private key is null.

below is my code for exporting certificate to pfx, where private key always null

public static bool ExportCertificateToPFX(string certificateSerialNumber, string pxfFilepath, StoreName storeName, StoreLocation location)
{
    bool success = false;

    X509Store store = new X509Store(storeName, location);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSubject, true);

    if (certs != null && certs.Count > 0)
    {
        //BELOW CONDITION ALWAYS FALSE
        if (certs[0].HasPrivateKey)
        {
            MessageBox.Show(certs[0].PrivateKey.ToString());
        }
        byte[] data = certs[0].Export(X509ContentType.Pfx, "KALPESH");
        //HERE WRITE "data" TO "pxfFilepath" FILE
    }
    store.Close();


    return success;
}
1

There are 1 answers

0
Crypt32 On

There are two possibilites (starting from less-probable):

  1. Certificate's private key uses unsupported by .NET key storage provider to store the keys. For example, Microsoft KSP or its own.
  2. There is no private key at all. You can run certutil -store with appropriate parameters (depending on where the certificate is installed) to verify whether there is a private key. Also this command gives you an answer if the key uses unsupported key storage.