How to use SSH public key authentication

SSH

One of the ways to access a remote server is using a ssh with password and another cool way is to use public-key authentication where you don’t need to type a password along with that we store necessary details in ~/.ssh/config so that with minimal keystroke we will be able to access the remote server.

What all things need to be done for that:

  1. Create a public-private key pair
  2. SSH into the server using a password add the public key of your PC to ~/ssh/authorized_keys of the server
  3. Update your PC’s ~/.ssh/config file to store important details like IP, username.

STEP 1: Create a public-private key pair using the following command.

ssh-keygen -t ed25519

-t is an option that allows us to select the algorithm to generate public-private key pair. You can use RSA, DSA, etc. I have used ed25519. If you are interested to go into algo details. please refer this article.

STEP 2:

Copy the public key, you can find the public key at ~/.ssh/id_ed25519.pub . The file name will be different if you are using another algorithm, just make sure you pick a file with *.pub extension.

cat ~/.ssh/id_ed25519.pub

Copy the output of that command and SSH into the host machine using the password. Example command

ssh username@hostname -p portNumber

Then you have to type your password. Once done you are logged into the server. Now add your public key to the host’s authorized keys

vi ~/.ssh/authorized_keys

This will open the file in vim, copy your public key here. This will tell the server whoever holds the private key of this public key is a trustable entity.

Step 3: Configuring ~/.ssh/config file

We will use this file so we don’t have to type the entire username hostname and port number whenever we do ssh.

vi ~/.ssh/config

Add the following lines to the file

Host {alias}
    Hostname {ip/hostname}
    User {username}
    Port {portnumber}
    IdentifyFile ~/.ssh/id_ed25519

Example:

Host bhanu
   Hostname blog.bhanunadar
   User bhanu
   Port 2700
   IdentifyFile ~/.ssh/id_ed25519

Once done save this file.

Step 4: Now do ssh

ssh bhanu

Voila!!! no need to remember the port, hostname, and password.

Related Post

2 Replies to “How to use SSH public key authentication”

  1. +1 for adding the config details for SSH.
    That part some how is missed by most tutorials.
    One suggestion that I have is, add your ~/.ssh/config file to some git repo.

    You can then keep track of it across your devices

Leave a Reply

Your email address will not be published. Required fields are marked *