How to use the ssh-keygen Command in Linux

Use the ssh-keygen command to generate a public/private authentication key pair. Authentication keys allow a user to connect to a remote system without supplying a password. Keys must be generated for each user separately. If you generate key pairs as the root user, only the root can use the keys.

The following example creates the public and private parts of an RSA key:

# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:z6zTVQ/PJYt2o96DrVYClmfcqBG8Pdb8nzqY2m2HjeY root@geeklab
The key's randomart image is:
+---[RSA 2048]----+
|         .       |
|          o      |
|           * =   |
|          * O B .|
|        S. B + O.|
|         +. = = =|
|         .+ooB+.o|
|        ..oo=Bo+.|
|        .o.+*E=. |
+----[SHA256]-----+

Use the –t option to specify the type of key to create. Possible values are “rsa1” for protocol version 1, and “dsa“, “ecdsa“, or “rsa” for protocol version 2.

You have the option of specifying a passphrase to encrypt the private part of the key. If you encrypt your personal key, you must supply the passphrase each time you use the key. This prevents an attacker, who has access to your private key and can impersonate you and access all the computers you have access to, from being able to do so. The attacker still needs to supply the passphrase.

The ssh-key command in the example generated two keys in the ~/.ssh directory:

$ ls ~/.ssh
id_rsa
id_rsa.pub

To log on to, or copy files to, a remote system without supplying a password, copy the public key (~/.ssh/id_rsa.pub in this example) to ~/.ssh/authorized_keys on the remote system. Set the remote ~/.ssh directory permissions to 700. You can then use the ssh or scp tools to access the remote system without supplying a password.

To allow multiple connections, append the public key to the authorized_keys file on the remote system instead of copying it. The following example appends the public key:

$ cat id_rsa.pub >> authorized_keys

You can improve system security even further by disabling the standard password authentication, and enforcing the key-based authentication. To do so, set the PasswordAuthentication option to no in the /etc/ssh/sshd_config configuration file as follows:

# vi /etc/ssh/sshd_config
PasswordAuthentication no

This disallows users whose keys are not in the authorized_keys file of the specific user on the server to connect via ssh. The connection is denied and the following message appears:

$ ssh host01
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

Setting the PasswordAuthentication option to yes, which is the default, permits a user to use a password for authentication.

Related Post