Extracting a public key from an SSH private key is a common task when setting up secure access to remote servers. The public key is used to authenticate your identity without exposing your private key. This method enhances security by allowing you to distribute the public key to multiple servers while keeping the private key safe.

The private key contains all the information needed to generate the corresponding public key. Using specific commands, you can easily extract the public key from the private key file. This process is essential when you need to add a public key to a remote server's authorized keys.

Follow these steps to extract a public key from an SSH private key.

Steps to extract a public key from an SSH private key:

  1. Launch the terminal on your local machine.
  2. Locate your SSH private key file.
    $ ls ~/.ssh/id_rsa

    The private key file is usually stored in the ~/.ssh directory.

  3. Check the format of your private key file.
    $ file ~/.ssh/id_rsa

    The private key should be in PEM format for OpenSSH. If the format is different, it may need conversion.

  4. Extract the public key from the private key file in SSH2 format (for use with non-OpenSSH systems).
    $ ssh-keygen -e -f ~/.ssh/id_rsa -m PKCS8

    This command exports the public key in SSH2 format (RFC4716).

  5. Extract the public key from the private key file in OpenSSH format.
    $ ssh-keygen -y -f ~/.ssh/id_rsa

    This command prints the public key in OpenSSH format to the terminal.

  6. Extract the public key and automatically save it to a file.
    $ ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

    This command generates the public key and saves it as id_rsa.pub in the same directory.

  7. Check the format of the generated public key file.
    $ file ~/.ssh/id_rsa.pub

    Verify that the public key file is in OpenSSH format.

  8. Optionally, copy the public key to the remote server's authorized keys file to enable key-based authentication.
    $ ssh-copy-id user@remotehost

    This command adds the public key to the authorized_keys file on the remote server.

Discuss the article:

Comment anonymously. Login not required.