SSH Key-Pair Authentication

[1] Generate a key pair for the public user on your local computer, the private key is defined on your local computer, the public key is defined on your remote server, and you can log in.

# generate key pair on local computer
[[email protected] ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/future/.ssh/id_rsa): # Enter or input changes
Created directory '/home/future/.ssh'.
Enter passphrase (empty for no passphrase): # set passphrase (enter for blank password)
Enter same passphrase again:                # verify passphrase (enter for blank password)
Your identification has been saved in /home/future/.ssh/id_rsa
Your public key has been saved in /home/future/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:Ah2PVQqHxip7NAflh3NGRRhgKb0qzg9OVERFhNXfVhI [email protected]
...
[[email protected] ~]$ ll .ssh
total 8
-rw-------. 1 future future 2610 Sep 29 16:43 id_rsa
-rw-r--r--. 1 future future  578 Sep 29 16:43 id_rsa.pub

[2] Upload the public key of the key pair you created to the server you want to log into with key pair authentication.

[[email protected] ~]$ scp /home/future/.ssh/id_rsa.pub [email protected]:/root
[email protected]'s password:
id_rsa.pub                                          100%  578   125.7KB/s   00:00

[3] Login with password authentication via ssh to the server you want to login with key pair authentication. Then configure it for ssh login with key pair authentication.

[[email protected] ~]$ ssh [email protected]
[email protected]'s password:
Last login: Wed Sep 29 14:46:48 2021 from 192.168.1.2
[[email protected] ~]#

[4] If there is no .ssh directory for root, create it and set its permissions.

[[email protected] ~]# mkdir -p /root/.ssh
[[email protected] ~]# chmod 700 /root/.ssh

[5] Save the id_rsa.pub file that you copied from your local computer earlier in the /root/.ssh folder on the server you want to log on to, with the name authorized_keys and set its permissions.

[[email protected] ~]# mv id_rsa.pub .ssh/authorized_keys
[[email protected] ~]# chmod 600 /root/.ssh/authorized_keys

[6] If SELinux is activated, update the SELinux policies.

[[email protected] ~]# restorecon -R /root/.ssh

[7] Log out from the server you want to login to and verify access with key pair authentication.

[[email protected] ~]# exit
[[email protected] ~]$
# verify access
[[email protected] ~]$ ssh [email protected]
Last login: Wed Sep 29 17:47:55 2021 from 192.168.1.2
[[email protected] ~]#