locked
Problem with X509Certificate2 Export RRS feed

  • Question

  • I'm trying to export a certificate and it's private key along with a password programatically with .NET2. It works fine to do the export from the MMC console and import it on another computer. However, when trying to import the certificate saved by my code on another computer via the MMC console (or double-clicking it) I receive the following error message:

     

    Invalid Public Key Security Object File

    This file is invalid for use as the following: Personal Information Exchange.

     

    I suspect there is only some minor detail that I've overlooked in the code. This is what I do:

     

    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

    store.Open(OpenFlags.ReadOnly);

    X509Certificate2Collection coll = store.Certificates.Find(X509FindType.FindBySerialNumber, "123", false);

    store.Close();

    X509Certificate2 x509cert = new X509Certificate2( coll[0].RawData, "test1234", X509KeyStorageFlags.Exportable);

     

    byte []bCertExported = x509cert.Export(X509ContentType.Pkcs12, "test1234");

     

    File.WriteAllBytes("c:\test.pfx", bCertExported);

     

    I've tried setting different X509KeyStorageFlags and X509ContentType's but the error remains the same.

     

    Please advice and thanks in advance!

    Monday, November 26, 2007 9:50 AM

Answers

  • I'll answer myself here. I solved it in an ugly way by using CAPICOM v2.1 and did like this:

     

    CertificateClass cs = new CertificateClass();

    cs.CertContext = (int)x509cert.Handle;

    cs.Save(@"c:\test.pfx", "test1234", CAPICOM_CERTIFICATE_SAVE_AS_TYPE.CAPICOM_CERTIFICATE_SAVE_AS_PFX, CAPICOM_CERTIFICATE_INCLUDE_OPTION.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN);

     

    This works fine. But I'd rather not use CAPICOM with .NET2.

    There has to be a proper way to solve this by using only .NET2?

    Monday, November 26, 2007 1:12 PM