6

I generated my public/private key pair using

ssh-keygen -t rsa -b 2048 -v

and then needed a .pem file and followed this https://serverfault.com/questions/706336/how-to-get-a-pem-file-from-ssh-key-pair

ssh-keygen -f id_rsa -e -m pem   
-----BEGIN RSA PUBLIC KEY-----

but then i found this https://gist.github.com/mingfang/4aba327add0807fa5e7f

openssl rsa -in ~/.ssh/id_rsa -outform pem
-----BEGIN RSA PRIVATE KEY-----

why is the output different?

2 Answers 2

5

That's how they are written; OpenSSH emits the public key material via a PEM_write_RSAPublicKey(stdout, k->rsa) call in the do_convert_to_pem function of ssh-keygen.c, while OpenSSL operates instead on the given private key. With OpenSSH, I'd imagine that the majority of cases would be to convert the public key into a form usable on some foreign server, with the private key remaining private on the client system, so operating on the public key of the keypair makes sense. With OpenSSL, there is no "get a public key into a form suitable for some other SSH server" concern, so that code operates directly on the private key. Different code, different intentions, different results.

1
  • uhm, I really don't understand this answer fully, namely it seems to me, that it does not answer the question at all. From what I understand, both transform commands get PRIVATE KEY as a input, and while second command should change this PRIVATE key to pem format, the first command returns PUBLIC key (-e flag). So that's the main difference IIUC. And the second command need to to work at all, as openssl reguses to work with openssh keys, producing: "unable to load Private Key". Nevertheless, these certificates stuff is in immense mess extremely poorly documented(considering it's crypto area) Commented Nov 12, 2019 at 10:43
1

For the openssl rsa command, you need the -pubout flag to output the public key instead of the private key. To output it as an RSA public key (the way ssh-keygen -e does), use the -RSAPublicKey_out flag instead:

openssl rsa -in id_rsa -outform PEM -RSAPublicKey_out
-----BEGIN RSA PUBLIC KEY-----

This gives the same output as

ssh-keygen -e -f id_rsa -m pem
-----BEGIN RSA PUBLIC KEY-----

The openssl command only works for me if my original ssh-keygen command to create the keys included the -m PKCS8 flag.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .