Export X509Certificate2 to byte array with the Private key

Erik Larsson picture Erik Larsson · Mar 21, 2012 · Viewed 33.4k times · Source

I have an X509Certificate2 certificate in my store that I would like to export to a byte array with the private key. The certificate byte array has to be so that when I then later would import the certificate from the byte array the private key would have the private key with it.

I have tried many wayes but has not succeded to export the certificate with the private key.

X509Store store = new X509Store(StoreLocation.CurrentUser);      

store.Open(OpenFlags.ReadOnly);

X509Certificate2 cert = store.Certificates[1];

byte[] certBytes = cert.GetRawCertData(); // Obviously does not work!

Is it possible to successfully export the certificate with private key to a byte array?

Help is very appreciated.

Answer

Hans picture Hans · Mar 21, 2012

The Export function of the X509Certificate2 class allows you to export a certificate with the private key to a byte array.

The following code demonstrates exporting a certificate with the private key:

X509Store store = new X509Store(StoreLocation.CurrentUser);

store.Open(OpenFlags.ReadOnly);

X509Certificate2 cert = store.Certificates[1];

// Export the certificate including the private key.
byte[] certBytes = cert.Export(X509ContentType.Pkcs12);

To secure your exported certificate use the following overload of the Export function:

byte[] certBytes = cert.Export(X509ContentType.Pkcs12, "SecurePassword");

BEGIN EDIT

To import the certificate use the following code:

X509Certificate2 certToImport = new X509Certificate2(arr, "SecurePassword");

// To mark it as exportable use the following constructor:
X509Certificate2 certToImport = new X509Certificate2(arr, "SecurePassword", X509KeyStorageFlags.Exportable);
// certToImport.HasPrivateKey must be true here!!

X509Store store2 = new X509Store(StoreName.TrustedPublisher,
                                 StoreLocation.CurrentUser);
store2.Open(OpenFlags.MaxAllowed);

store2.Add(certToImport);
store2.Close();

END EDIT