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