SSH (Secure Shell) is a widely used protocol for secure communication between two systems. It relies on key pairs—a public key and a private key—to authenticate users and establish secure connections. The public key is shared with remote servers, while the private key remains confidential on your local machine.
In this article, we’ll focus on extracting the public key from an existing private key using the ssh-keygen
utility. This process is essential when you want to add your public key to a remote server’s authorized_keys
file for passwordless authentication.
Prerequisites
Before we proceed, ensure that you have the following:
- SSH Private Key: You should already have an existing an SSH private key, usually named
id_rsa
. ssh-keygen
: ssh-keygen tool usually comes with the Linux system.
Steps to Retrieve the Public Key
- Open a Terminal or Command Prompt:
- On Linux or macOS, open your terminal.
- On Windows, use the Command Prompt or PowerShell.
- Navigate to the Directory Containing Your Private Key:
cd ~/.ssh
- Generate the Public Key: Use the
-y
option withssh-keygen
to output the public key from the private key:ssh-keygen -y -f id_rsa > id_rsa.pub
Theid_rsa.pub
file now contains your public key. - Optional: Add a Comment to the Public Key: By default, the comment associated with the public key is lost during this process. If you need to include a comment (e.g., your username or a description), manually edit the
id_rsa.pub
file and add a comment to the first line, separated by a space from the key data. - Restrict Permissions on Your Private Key: Ensure that your private key file (
id_rsa
) is readable only by your user:chmod 400 id_rsa
This prevents unauthorized access to your private key.
Conclusion
You’ve successfully extracted the public key from your private key using ssh-keygen
. Now you can securely share your public key with remote servers for authentication. Remember to keep your private key confidential and never share it with anyone.
Feel free to explore additional options provided by ssh-keygen
, such as converting key formats or specifying key types. Happy secure shell adventures!