SSH key-based authentication offers a much more secure method of accessing an SSH server compared to password-based authentication. It uses a pair of cryptographic keys—one public and one private—to authenticate users. The public key is placed on the server, while the private key remains on the client machine. If the keys match, access is granted without needing a password.
This method mitigates the risks associated with password-based logins, such as brute-force attacks, since the private key is never transmitted during the authentication process.
To use key-based authentication, you first need to generate an SSH key pair on the client machine (your local system).
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-t rsa: Specifies the type of key to generate (RSA in this case).
-b 4096: Sets the key length to 4096 bits, providing a higher level of security.
-C “your_email@example.com”: An optional comment to help identify the key (often an email address).
You will be prompted to enter a file path to save the key. Press Enter to use the default location (~/.ssh/id_rsa).
After that, you can choose to enter a passphrase (optional) to further secure your private key.
ls ~/.ssh/
You should see the following two files:
id_rsa (the private key, which must be kept secure).
id_rsa.pub (the public key, which can be shared with the server).
Next, you’ll need to copy the public key (id_rsa.pub) to the server where you wish to authenticate. The easiest way to do this is by using the ssh-copy-id command.
ssh-copy-id <username>@<server-ip>
This command will prompt you for the server’s password. Once entered, the public key will be added to the ~/.ssh/authorized_keys file on the server.

After setting up SSH key-based authentication, it’s a good idea to disable password-based authentication to prevent any potential brute-force attacks.
sudo nano /etc/ssh/sshd_config
PasswordAuthentication no
rm /etc/ssh/sshd_config.d/50-cloud-init.conf
sudo systemctl restart ssh
With this setting, SSH login will now only be possible using the private key and not a password.

To ensure everything is set up correctly, you can now attempt to SSH into the server without providing a password (since the server will authenticate you using your public key).
ssh <username>@<server-ip>
If key-based authentication is successful, you should log in without being asked for a password.
