Vivendi
Vivendi

Reputation: 21067

Get PEM public and private keys or from PFX file

I have a PEM file that was generated with openssl using the following command:

.\openssl.exe  pkcs12 -in "C:\temp\mytest.pfx" -nokeys -out "C:\temp\mytest.publicchain.pem"

This generated a PEM file with the following content:

-----BEGIN CERTIFICATE-----
MIIJbTCCByGgAwIBAgITfgAAADLWmZPQJCEhKgAAAAAAMjBBBgkqhkiG9w0BAQow
NKAPMA0GCWCGSAFlAwQCAwUAoRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAwUA
... [removed rest of key for obvious reasons]
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
MIIHFzCCBP+gAwIBAgITHgAAAAR0/hITgHTMqgAAAAAABDANBgkqhkiG9w0BAQ0F
ADAcMRowGAYDVQQDExFFbmVjby1TQkRULVJvb3RDQTAeFw0xOTA4MjcyMjMwMjFa
... [removed rest of key for obvious reasons]
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
MIIFsDCCA5igAwIBAgIQM4wn3z5DLaxG8ARk2MpMJTANBgkqhkiG9w0BAQ0FADAc
MRowGAYDVQQDExFFbmVjby1TQkRULVJvb3RDQTAeFw0xODA5MTcwNzIyNDhaFw0y
... [removed rest of key for obvious reasons]
-----END CERTIFICATE-----

I am also using the AxualFramework from Apache, and I need to provide it with a PEM public and private key. Their description is:

Client's public key string (PEM format) used for authentication.

Client's private key string (PEM format) used for authentication.

Now my question is, how can I extract this from either my PEM file or from the PFX file? Which ever is easier to do?

I also have BouncyCastle installed as a Nuget package, but I'm not sure what methods to use.

I also tried to get it from the PFX file using things like:

X509Certificate2 cert = certificateCollection[0];
var pubKey = cert.PublicKey.Key.ExportSubjectPublicKeyInfo();
var pubKeyString = Convert.ToBase64String(pubKey); // Is this even correct?

// how to get private key...?

But I really have no clue if this is the way to do it...

Can any guide me in the right direction?

Upvotes: 7

Views: 17545

Answers (1)

poke
poke

Reputation: 388293

Since you are already using OpenSSL, you can use its command line tool to convert between the different formats. In your case, the pkcs12 command you already ran exported the certificates without its keys, so you won’t be able to use the mytest.publicchain.pem to extract the private key.

Instead, you can export the private RSA key from the PFX and then extract the public key from the private key:

openssl pkcs12 -in mytest.pfx -nocerts -nodes -out mytest.key
openssl rsa -in mytest.key -pubout -out mytest.pub

The files mytest.key and mytest.pub are then the private and public key respectively in PEM format.

Upvotes: 18

Related Questions