linux

SSH – creating a private/public key pair

2 min read

One of the essential tools for administering remote servers is the SSH client. It lets us establish a secure connection to a remote computer.

Besides password authentication (not recommended), we can authenticate with a private/public key pair. With these, once properly configured, we can authenticate without a password.

To create a key pair to use on our Linux system, we can run the following command in a terminal

text
ssh-keygen

While the keys are being created, you will be asked for the name and path of the key to create

text
Generating public/private rsa key pair.
Enter file in which to save the key (/home/youruser/.ssh/id_rsa):

If we don’t want to change the key’s name, we can confirm with “enter”.

Next we will be asked for a passphrase to encrypt the private key, so that it is not immediately usable if someone gets hold of it improperly. If we don’t want one, we can move on without a passphrase by pressing “enter” at this prompt and at the confirmation prompt that follows.

text
Enter passphrase (empty for no passphrase):

A private key and a public key (.pub) will then be created. The private key must not be disclosed to anyone; it should be properly protected and never shared.

text
Your identification has been saved in /home/youruser/.ssh/id_rsa
Your public key has been saved in /home/youruser/.ssh/id_rsa.pub

The key we should share is the public key, whose name usually ends with the “pub” extension.

What if we didn’t protect the private key when we created it and now want to?

To do that we use the following command

text
ssh-keygen -p -o -f /home/youruser/.ssh/id_rsa

You will be asked for the passphrase you want to use to protect the key, and the previous private key file will be overwritten.

text
Key has comment 'youruser@hostname'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:

From then on, whenever we want to use this key, we will be asked for the passphrase we set.

Photo by Markus Spiske on Unsplash

#ssh