How to Set up SSH keys?
Secure Shell, most commonly known as SSH, is a common network protocol that enables users to securely access a computer/server over an unsecured network. SSH keys gives added security to SSH in the sense that a password need not be used when making use of SSH keys.
SSH key pair comprises of both a public key and private key, both of which are a long string of characters. The public key is saved in the server to which SSH connection is to be done and the private key is stored on the system/computer from which SSH connection is requested.
The below steps can be followed to set up SSH Key based authentication.
1. Create SSH Key pair
On the computer from which SSH connection is requested, make use of the below command to generate a key pair
ssh-keygen -t rsa
A sample output of this command will be as below:
ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:q5CKez4qSUCNiNbuNfy8B+3+XtCc9b/WYMp9WX6k7kw [email protected]
The key’s randomart image is:
|o + |
|o+ o |
|o . . . |
|. . + o o .|
|. . . + S . + .|
| . . . + o . o +|
|.. o = . =E==|
|o.o. . o o +ooo*|
|==o. . o.oo o=o.|
You may give a passphrase (password) at the time of key pair generation when prompted to. The passphrase adds extra security for the SSH key pair.
Once the command has been executed, the public key will be stored accordingly as id_rsa.pub and the private key as id_rsa in the path that has been specified at the time of key pair generation.
2. Copy the public key to the remote server
The public id_rsa.pub key then needs to be copied to the server to which the SSH connection is to be made. For this, there are two available options.
- Use the ssh-copy-id command as below, where user is the username with which you are connecting to the server with IP address 18.104.22.168
ssh-copy-id [email protected]
- You can alternatively copy the public key to the authorized_keys file located inside the .ssh folder in your server 22.214.171.124.
3. Test the SSH connection.
Once the public key has been added to the server, you can test the SSH connection to the server from the computer which has the private key, using the below command.
There will not be any prompt for the password. However, you may be prompted to enter the passphrase, if it had been set at the time of SSH key pair generation.
4. Disable SSH direct root login
Once you have confirmed that the server is accessible using SSH key pair, you can proceed to disable direct root login to your server through SSH. For this, the below steps can be followed.
- Open the SSH configuration file /etc/ssh/sshd_config
- Change the value of PermitRootLogin to no
- Restart SSH service using the below command
service sshd restart