Blog

How to setup SSH Key-Based Authentication?

Learn how to set up SSH key-based authentication for secure, passwordless access to your Linux servers. This guide covers generating SSH keys, copying them to your server, and disabling password authentication.

March 10, 2024/2 min read

SSHLinuxSecurityDevOps

Secure Shell (SSH) is an encrypted protocol used to administer and communicate with servers. Most of the linux servers are operated over SSH through terminal session. Password-Based authentication is used by default. SSH Key-Based authentication is generally considered safer than Password-Based authentication.

Creating SSH Keys

1. Generate new SSH key

ssh-keygen -t rsa -b 4096

2. If you're managing multiple SSH keys name them with full location or continue with id_rsa by default. Add passphrase for the key if you prefer (recommended)

Eg: /home/username/.ssh/aws instead of /home/username/.ssh/id_rsa

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

3. After the key is successfully generated, you will get a similar output. Two keys will be generated id_rsa and id_rsa.pub. id_rsa is private key which should not be shared to anyone. id_rsa.pub is public key which can be shared.

Your identification has been saved in /home/username/.ssh/id_rsa
Your public key has been saved in /home/username/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:FFh+jfTHgzYrLL2GOnBUiOpzIY8pffH1qcb6WpMJGJE username@hostname
The key's randomart image is:
+---[RSA 4096]----+
|    .o +o .      |
|    E.o..o + o   |
|   ..  .o o * +  |
|  o oo...+ . + . |
| o =.=..S.+..    |
|. * = o. =oo     |
| . + o .*.o      |
|      .o+o       |
|      +*.        |
+----[SHA256]-----+

Copying the Public SSH Key to Server

1. Copy the output generated from the below command

cat ~/.ssh/id_rsa.pub

2. SSH into your server

echo paste-your-publickey >> ~/.ssh/authorized_keys

3. Try to SSH into your server. You will be logged in without password

Disable Password-Based Authentication

1. Open the sshd_config

sudo nano /etc/ssh/sshd_config

2. Change PasswordAuthentication to no

PasswordAuthentication no

3. Restart ssh daemon

sudo systemctl restart sshd