How to convert from X509 to PKCS1 encoded RSA key

3.5k views Asked by At

For context, I'm trying to use in M2Crypto in place of Python-RSA, but this question isn't really language or library specific.

If I have an RSA public key in X509 format (starts with ----BEGIN PUBLIC KEY---), what do I need to do to convert it to PKCS1 (starts with ----BEGIN RSA PUBLIC KEY----) format?

This thread seems to describe going in the opposite direction.

1

There are 1 answers

0
TheFortium On BEST ANSWER

Essenitally you need OpenSSL (Linux application). With OpenSSL you can run following command to convert from X509 to PKCS1:

openssl rsa -pubin -in x509_public.key  -RSAPublicKey_out > rsa_public.key

I had to extract a SSL-Certificate and the PKCS1-Keys from a PFX-file. To do so I used following commands:

openssl pkcs12 -in pfx_file.pfx -clcerts -nokeys -out certificate.cer

(Extracting the certificate)

openssl pkcs12 -in pfx_file.pfx -nocerts -nodes -out rsa_pair.key

(Extracting the RSA keypair)

openssl rsa -in rsa_pair.key -out rsa_private.key

(Extracting the RSA private key)

openssl rsa -in rsa_pair.key -pubout -out x509_public.key

(Extracting the "wrong" X509 Public Key)

openssl rsa -pubin -in x509_public.key  -RSAPublicKey_out > rsa_public.key

(Finally extracting the RSA-PKCS1 public key)

There are probably some better ways, but I searched a long time to get here. I hope I could save others from this long searching through the web.