Convert PEM-Encoded Public Key to OpenSSH Format using ssh-keygen

Convert PEM-Encoded Public Key to OpenSSH Format using ssh-keygen

When working with public keys, you'll often encounter different encoding formats depending on the tool or system in use. Two common formats are PEM (a base64-encoded, human-readable representation) and the OpenSSH format (used in authorized_keys files and by the ssh client). This tutorial explains how to convert PEM-encoded public key to OpenSSH format using ssh-keygen.

Suppose you have a public key saved in a file named test.pub with the following content:

-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAN/ovAmhoNOnE2VoJeUunpEB+CwTyPbK
I8VnQ+rLa75riBtmfYrGdUD8Cv/p+ioL86xwSvX+HYXnkPffEXc7IlUCAwEAAQ==
-----END PUBLIC KEY-----

To convert this PEM-encoded public key into a OpenSSH format, run the following ssh-keygen command:

ssh-keygen -i -m PKCS8 -f test.pub > id_rsa.pub

Explanation of options:

  • -i - instructs to import a key from another format.
  • -m PKCS8 - specifies the input format as PKCS#8.
  • -f test.pub - points to the file containing the input key.
  • > id_rsa.pub - writes converted key to the output file.

Output:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQDf6LwJoaDTpxNlaCXlLp6RAfgsE8j2yiPFZ0Pqy2u+a4gbZn2KxnVA/Ar/6foqC/OscEr1/h2F55D33xF3OyJV

Leave a Comment

Cancel reply

Your email address will not be published.