Public key authentication is not only more convenient than entering a password but also far more secure. On any given day your server or machine if SSH is on default port 22 and you have a public IP, it will probably receive at least 1,000 login attempts. These are all automated processes created in order to gain access to a server. They are not after your server, but they are after any server they can get their hands on.

When you generate a public key you are creating a random encrypted password, which is not easily hacked and tied to your particular machine. Only the machine that has the matching private key will be able to gain access.

The steps for generating a public key are rather simple. First generate a private and public key on the local machine, then copy the public key to the host. It’s that simple, but let’s go through all the steps:

1. Generate the public key

Make sure you are logged as the user you want to generate a public key for. To generate the public and private key we are going to use the ssh-keygen command.

If you notice I passed the argument -t rsa this specifies that I want to use the rsa protocol for generating the key. I also did not enter a password. You may enter a password if you wish. It would defeat the purpose of password less authentication but it will make login more secure.

If you look at your home directory, there is now a .ssh folder. This contains your private and public key.

id_rsa is your private key and your public key.

2. Prepare your host to receive the public key

To copy your public key to your host you need access to it. So of course you need to have a password.

In order to copy over the public key we need to create the .ssh folder on your host. Login as your user and in your home directory create a .ssh folder and chmod it to 700.

We also need to create the authorized_keys file, this is where we will copy out public key into. This file contains all of the public keys that are authorized to login to this machine.

3. Copy the public key to your host

Go back to your machine and make sure you are logged in as the user you generated the public and private keys for.

Type in the following to copy over your public key. Replace YOUR_USERNAME with your user and YOUR_HOSTNAME_OR_IP with your host’s hostname or ip. The command will ask you for your password since you haven’t yet added the public key to the host.

Your public key is now setup on your host. You can now ssh into your host without the need of a password:

4. Optional – Delete your password from the host machine

If you want to be really secure, you can delete your password from the host. This will ensure that only the machine with the private key will have access to this user. Note, that if you ever lose the private key you will lose access to the host.