Convert pem key to ssh-rsa format
No need for scripts or other 'tricks': openssl
and ssh-keygen
are enough. I'm assuming no password for the keys (which is bad).
Generate an RSA pair
All the following methods give an RSA key pair in the same format
With openssl (man genrsa)
openssl genrsa -out dummy-genrsa.pem 2048
In OpenSSL v1.0.1
genrsa
is superseded bygenpkey
so this is the new way to do it (man genpkey):openssl genpkey -algorithm RSA -out dummy-genpkey.pem -pkeyopt rsa_keygen_bits:2048
With ssh-keygen
ssh-keygen -t rsa -b 2048 -f dummy-ssh-keygen.pem -N '' -C "Test Key"
Converting DER to PEM
If you have an RSA key pair in DER format, you may want to convert it to PEM to allow the format conversion below:
Generation:
openssl genpkey -algorithm RSA -out genpkey-dummy.cer -outform DER -pkeyopt rsa_keygen_bits:2048
Conversion:
openssl rsa -inform DER -outform PEM -in genpkey-dummy.cer -out dummy-der2pem.pem
Extract the public key from the PEM formatted RSA pair
in PEM format:
openssl rsa -in dummy-xxx.pem -pubout
in OpenSSH v2 format see:
ssh-keygen -y -f dummy-xxx.pem
Notes
OS and software version:
[user@test1 ~]# cat /etc/redhat-release ; uname -a ; openssl version
CentOS release 6.5 (Final)
Linux test1.example.local 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
OpenSSL 1.0.1e-fips 11 Feb 2013
References:
- Sysmic.org Convert keys betweens GnuPG, OpenSsh and OpenSSL
No need to compile stuff. You can do the same with ssh-keygen
:
ssh-keygen -f pub1key.pub -i
will read the public key in openssl format from pub1key.pub
and output it in OpenSSH format.
Note: In some cases you will need to specify the input format:
ssh-keygen -f pub1key.pub -i -mPKCS8
From the ssh-keygen docs (From man ssh-keygen):
-m key_format Specify a key format for the -i (import) or -e (export) conversion options. The supported key formats are: “RFC4716” (RFC 4716/SSH2 public or private key), “PKCS8” (PEM PKCS8 public key) or “PEM” (PEM public key). The default conversion format is “RFC4716”.