Create SSH key pair and using it

technical
Author

Hiromi Suenaga

Published

February 15, 2022

1. Create SSH key pair

It is fairly simple to create a SSH key pair as ssh-keygen will guide you through the whole process.

ssh-keygen -t ed25519 -C "sunny@example.com"

-C is a comment that will be added at the end of the public key.

The series of questions after you run the above code looks something like:

Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/sunny/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

You can choose to use all default values or enter your own.

Once it is complete: - The public key is now located in /home/sunny/.ssh/id_ed25519.pub - The private key is now located in /home/sunny/.ssh/id_ed25519

2. Copy public key to the remote server:

Let’s say, the remote server is running SSH on a non-standard port. If your remote server is using the standard port, you can omit the port settings:

ssh-copy-id -i ~/.ssh/id_ed25519 -p 123 sunny@remote_server_address 

.pub is automatically added if you specify a filename that does not end with .pub.

This will add your public key to the remote server’s ~/.ssh/authorized_keys file. If you open it up, you will see the comment you added when generating via -C flag in step 1.

3. Add private key to the SSH agent:

[Optional] Start the ssh-agent if it isn’t already. If you are not sure, skip it for now and come back if the next step fails.

eval "$(ssh-agent -s)"

Add your SSH private key to the ssh-agent.

ssh-add ~/.ssh/id_ed25519

If you are curious which keys ssh-agent knows about, run:

ssh-add -L

4. Add the remote host to SSH config (just for convenience):

For simplicity, you can add the remote host to your SSH config file (~/.ssh/config). If this file does not exist, you can create it manually (touch ~/.ssh/config).

Add a block like this:

Host remote_server_name
        HostName 123.45.678.90
        User sunny
        IdentityFile ~/.ssh/id_ed25519
        Port 123

Now you can SSH to the server by:

ssh remote_server_name

Instead of:

ssh -i ~/.ssh/id_ed25519 -p 123 sunny@123.45.678.90

References