Inhaltsverzeichnis

Import/Export

Compact examples for import/export. → Details: Import/Export Scenarios


PEM Export

var cert = new X509Certificate2("certificate.pfx", "password");
 
// Certificate as PEM
string certPem = cert.ExportCertificatePem();
File.WriteAllText("certificate.pem", certPem);
 
// Private key as PEM (encrypted)
using var key = cert.GetECDsaPrivateKey();
string keyPem = key.ExportEncryptedPkcs8PrivateKeyPem(
    "password"u8, new PbeParameters(
        PbeEncryptionAlgorithm.Aes256Cbc,
        HashAlgorithmName.SHA256, 100000));
File.WriteAllText("private.key", keyPem);

Details: PEM Export


PFX/PKCS#12

// Export
var cert = new X509Certificate2("certificate.pfx", "old");
byte[] pfx = cert.Export(X509ContentType.Pfx, "new");
File.WriteAllBytes("exported.pfx", pfx);
 
// Import
var imported = new X509Certificate2("exported.pfx", "new",
    X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

Details: PFX Export


PKCS#7 Certificate Chain

// Export
var chain = new X509Certificate2Collection();
chain.Add(endEntity);
chain.Add(intermediate);
chain.Add(root);
 
byte[] p7b = chain.Export(X509ContentType.Pkcs7);
File.WriteAllBytes("chain.p7b", p7b);
 
// Import
var imported = new X509Certificate2Collection();
imported.Import("chain.p7b");

Details: PKCS#7 Chain


Cross-Platform (Java/OpenSSL)

// For Java: PKCS#12 with compatible algorithms
byte[] pfx = cert.Export(X509ContentType.Pfx, "password");
 
// For OpenSSL: PEM format
string pem = cert.ExportCertificatePem();
# OpenSSL: PEM -> PKCS#12
openssl pkcs12 -export -in cert.pem -inkey key.pem -out cert.pfx
 
# OpenSSL: PKCS#12 -> PEM
openssl pkcs12 -in cert.pfx -out cert.pem -nodes

Details: Interoperability


Format Overview

Format Extension Contents
PEM .pem, .crt, .key Base64 with header
DER .der, .cer Binary
PFX/PKCS#12 .pfx, .p12 Cert + key + chain
PKCS#7 .p7b, .p7c Certificates only

« <- Quick Reference | -> Import/Export Scenarios (Details) »


Wolfgang van der Stille @ EMSR DATA d.o.o. - Post-Quantum Cryptography Professional