I generated a key pair vis OpenSSH and later wanted to generate PEM encoded public key. I noticed that generated public key differs when generated by OpenSSH vs OpenSSL when using same format name (PEM)... After some testing (see below), I found that public keys are the same only when generated a) as PKCS8 in OpenSSH and b) as PEM in OpenSSL
- Why is PEM output of OpenSSH different than PEM format of OpenSSL?
- If this is just a parameter naming mismatch, am I correct in my assumption that to get the same public key, I have to use PCKS8 in OpenSSH and PEM in OpenSSL?
Here is my test:
# -----------------------------------------------------------------------------
# Using OpenSSH
# -----------------------------------------------------------------------------
# generate test key pair
[root@localhost key-test]# ssh-keygen -t rsa -b 2048 -f test.ssh
#
# get MD5 fingerprint of generated public key
#
[root@localhost key-test]# cat test.ssh.pub | openssl md5 -c
(stdin)= 3e:b6:6f:95:d2:1d:ca:7a:f3:88:2e:3a:ca:c3:b7:a3
#
# get MD5 fingerprint of generated public keys (RFC4716, PEM, and PKCS8 formats)
#
# header => ---- BEGIN SSH2 PUBLIC KEY ----
[root@localhost key-test]# ssh-keygen -y -e -m RFC4716 -f test | openssl md5 -c
(stdin)= 0d:da:5b:27:e9:cd:32:25:e5:c8:4e:2b:c2:0f:47:aa
# header => -----BEGIN RSA PUBLIC KEY-----
[root@localhost key-test]# ssh-keygen -y -e -m PEM -f test | openssl md5 -c
(stdin)= c5:38:c0:41:f8:76:41:7b:49:03:42:c6:21:dd:1c:2f
# header => -----BEGIN PUBLIC KEY-----
[root@localhost key-test]# ssh-keygen -y -e -m PKCS8 -f test | openssl md5 -c
(stdin)= 84:e8:54:5f:16:9f:92:48:67:99:54:65:13:ad:64:ad
# -----------------------------------------------------------------------------
# Using OpenSSL
# -----------------------------------------------------------------------------
#
# get MD5 fingerprint of the generated public key (PEM format)
#
# header => -----BEGIN PUBLIC KEY-----
[root@localhost key-test]# openssl rsa -in test -pubout -outform PEM | openssl md5 -c
(stdin)= 84:e8:54:5f:16:9f:92:48:67:99:54:65:13:ad:64:ad
-----BEGIN PUBLIC KEY-----
, the keys should be the same. Inside, they are ASN.1/DER encoded sequences and bit strings (with additional PEM and Base64 encoding on top). The ASN.1/DER is effectively the pair{Algorithm,Public Key}
, where the algorithm is a OID. The various public keys (----BEGIN SSH2 PUBLIC KEY----
,-----BEGIN RSA PUBLIC KEY-----
) encode the algorithm into the pre-encapsulated header boundary. SSH keys also use a triple that is{Algortihm,Public Key,Email}
.