SSH keys are generated in pairs and stored in plain-text files. The keypair consist of two parts: a private key and a public key. Do not share your private key with anyone. Private SSH keys should be kept safe and secure. The private key is stored on your local computer. The public key is place on the server you intend to log into.
In this section, we will generate our key using the ssh-keygen tool. OpenSSH and ssh-keygen are included by default on Linux and MacOS.
Run the command below to generate a new key using the Ed25519 encryption algorithm.
ssh-keygen -t ed25519
If you prefer a different encryption algorithm, replace Ed25519 with your desired algorithm type. The command below would generate a new key using the RSA algorithm instead. It’s recommended to specify a bit length of 4096 for RSA keys.
ssh-keygen -t rsa -b 4096
The -t option defines the type of algorithm that’s used.
The -b option is used to specify the bit length when generating RSA keys.
When prompted for the file name, press Enter to use the default name and path. SSH keys are usually stored in the ~/.ssh/ directory.
Next, enter a passphrase. This is optional but is recommended.
Private keys using Ed25519 are saved with the file name id_ed25519 by default.
Public keys are the same file name with .pub appended (for example: id_ed25519.pub)
Private keys using RSA are saved with the file name id_rsa by default.
Public keys are the same file name with .pub appended (for example: id_rsa.pub)
Upload the public key to your remote system to start using your SSH key pair.
Enter the command below. ssh-copy-id is a utility included with OpenSSH
ssh-copy-id [user]@[ipaddress]
ssh-copy-id [user]@[ipaddress] copies the public key of the private/public key-pair into ~/.ssh/authorized_keys on the remote host. After entering your remote user’s password, your public key should be copied to the server’s authorized_keys file.
Set access permissions:
chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys
Disable Password Authentication
Open the SSH configuration file on your remote machine
vim /etc/ssh/sshd_config
To search in vim
Press /
Type the search pattern
Press enter to perform the search
Press n to find the next occurrence or N to find the previous occurrence.
To go into insert mode type i
To go back to command mode type the esc key
Disable SSH password authentication. Make sure the line is uncommented by removing the leading #
PasswordAuthentication no
Restart the SSH service using systemctl for distributions with systemd (for example: CentOS 9)
systemctl restart sshd