How to setup SSH Key-Based Authentication?
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
- Generate new SSH key
ssh-keygen -t rsa -b 4096
- 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:
- After the key is successfully generated, you will get a similar output. Two keys will be generated
id_rsa
andid_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
- Copy the output generated from the below command
cat ~/.ssh/id_rsa.pub
- SSH into your server
echo paste-your-publickey >> ~/.ssh/authorized_keys
- Try to SSH into your server. You will be logged in without password
Disable Password-Based Authentication
- Open the
sshd_config
sudo nano /etc/ssh/sshd_config
- Change
PasswordAuthentication
tono
PasswordAuthentication no
- Restart ssh daemon
sudo systemctl restart sshd