wei f
wei f

Reputation: 3

How to convert a java generated public key to pem format with openssl

I've got a public RSA key which is as following:

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHn/hfvTLRXViBXTmBhNYEIJeGGGDkmrYBxCRelri
LEYEcrwWrzp0au9nEISpjMlXeEW4+T82bCM22+JUXZpIga5qdBrPkjU08Ktf5n7Nsd7n9ZeI0YoAKCu
b3ulVExcxGeS3RVxFai9ozERlavpoTOdUzEH6YWHP4reFfpMpLzwIDAQAB

I need to convert it into PEM format so that I can write my own python code using this public key, I see there're many answers to the opposite operation, but right now I need to convert it from JAVA style to PEM, can anyone help?

Upvotes: 0

Views: 1262

Answers (2)

oliv
oliv

Reputation: 13259

Just convert back the base64 encoded pub key and throw it to openssl:

echo "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHn/hfvTLRXViBXTmBhNYEIJeGGGDkmrYBxCRelriLEYEcrwWrzp0au9nEISpjMlXeEW4+T82bCM22+JUXZpIga5qdBrPkjU08Ktf5n7Nsd7n9ZeI0YoAKCub3ulVExcxGeS3RVxFai9ozERlavpoTOdUzEH6YWHP4reFfpMpLzwIDAQAB" | base64 -d | openssl rsa -inform der -pubin -out rsakey.pub

-inform der is telling to openssl to take the key as binary (default is PEM)

-pubin tells to expect a public (default is private)

-out is to write the key


Another way is to append the openssl tags before and after the base64 encoded rsa public key:

sed 's/^/-----BEGIN PUBLIC KEY-----\n/;s/$/\n-----END PUBLIC KEY-----/' <<< "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHn/hfvTLRXViBXTmBhNYEIJeGGGDkmrYBxCRelriLEYEcrwWrzp0au9nEISpjMlXeEW4+T82bCM22+JUXZpIga5qdBrPkjU08Ktf5n7Nsd7n9ZeI0YoAKCub3ulVExcxGeS3RVxFai9ozERlavpoTOdUzEH6YWHP4reFfpMpLzwIDAQAB" | openssl rsa -pubin

Upvotes: 1

CraigR8806
CraigR8806

Reputation: 1584

You could create a bash script like this:

#!/bin/bash

# Loop through all the certs in the current folder that have the .cer extension
for cert in *.cer
do

#get filename wihtout ext
filename="${cert%.*}"
#echo ${filename} 

#convert to PEM
openssl x509 -inform der -in ${cert} -outform pem -out ${filename}.crt

done

I used this to convert certificates to pem format. Hopefully it can help

Upvotes: 1

Related Questions