Skip to content

Question: how to generate a .pem file with private key from an X509Certificate2? #51597

@heng-liu

Description

@heng-liu

Description

May I know if there is any way to generate a .pem file with private key from an X509Certificate2?
I tried the following:
1.Create a self-issued X509Certificate2 certificate(cert) with private key (the key generation algorithm is RSA ), saved as attached file.

byte[] certbytes = cert.Export(X509ContentType.Pfx, "password"); 
File.WriteAllBytes(path, certbytes);

2.Wrote a console to:
1).Read the bytes, create an X509Certificate2 cert, Set a password to protect the cert.
2).Try to get the certificate, public key, private key to create a .pem file.

string path = "c:\\work\\0420\\cert";
            byte[] certbytes = File.ReadAllBytes(path);

            string password = "password";
            X509Certificate2 certWithPrivateKey = new X509Certificate2(certbytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            byte[] certificateBytes = certWithPrivateKey.RawData;
            char[] certificatePem = PemEncoding.Write("CERTIFICATE", certificateBytes);

            using (AsymmetricAlgorithm key = certWithPrivateKey.GetRSAPrivateKey())
            {
                byte[] pubKeyBytes = key.ExportSubjectPublicKeyInfo();
                char[] pubKeyPem = PemEncoding.Write("PUBLIC KEY", pubKeyBytes);

                byte[] encryptedPrivKeyBytes = key.ExportEncryptedPkcs8PrivateKey(
                    password,
                    new PbeParameters(
                        PbeEncryptionAlgorithm.Aes256Cbc,
                        HashAlgorithmName.SHA256,
                        iterationCount: 100_000));
                char[] privKeyPem = PemEncoding.Write("PRIVATE KEY", encryptedPrivKeyBytes);
            }

I could see non empty char arrays for above certificatePem, pubKeyPem and privKeyPem. But I'm not sure how to combine them into a .pem file.
I tried to convert them into string and concatenate them, but the .pem file generated in this way failed to be used in CreateFromEncryptedPemFile as CryptographicException as following:
cert = X509Certificate2.CreateFromEncryptedPemFile(options.CertificatePath, options.CertificatePassword)
The exception details is:
image

I'm wondering if you know how to generate a .pem file with private key (with or without password) from an X509Certificate2 cert? Thanks!

Attached is the cert file from step1.
cert.zip

Configuration

Regression?

Other information

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.SecurityquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions