How to Set Up SSH Keys with Linux Commandline

In this tutorial we are going to setup encrypted keys for authentication through SSH. There are many benefits to this type of setup which include:

  • No longer needing to enter a password (unless you encrypt your keys with password protection *recommended*)
  • Once public/private key pair authentication is configured, you can disable password authentication completely and only allow access via the key. Stops brute force attacks in its tracks.

We first need to create a public/private key pair on the client that we will use to connect to the server.

You will run the below command. Be sure to change the “solarvps_key” comment to reflect your key comment that you wish to have to help remember what the key is for.

The -b is using 2048bit encryption and the -t is type RSA. Be sure to give your key a passphrase for extra security!

ssh-keygen -b 2048 -t rsa -C "solarvps_key"

Output should look like:

# ssh-keygen -b 2048 -t rsa -C "solarvps_key"
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:
45:15:66:f2:03:a6:e9:0e:49:a4:12:b7:61:f9:f4:8e solarvps_key

The command will create two files in your (hidden) ~/.ssh directory called id_rsa and id_rsa.pub. id_rsa is your private key and id_rsa.pub is your public key.

Let’s now set permissions on the key files:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa

The above permissions are required if StrictModes is set to yes in /etc/ssh/sshd_config (the default).

Now copy the contents of id_rsa.pub file so we can put the public key onto the server we are trying to access via ssh keys only. To do this you can follow How to add your SSH public key to CentOS.

# cat id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAt+PzzOFcecabwsXnjPPd+eqrqF5d2qh6kRIbnInSgwqWlPvnyfxa2Ye1xhGjCssbYdPWA7epJ/42yMFQfg6RGynW9XjWMomWeA/1+2LGY4B7JBJQfuTdDB/AimJRQvlSmxklfktmuqx0S8u67mLdkRWY+uQD8Ec7TCxWC9pU5Hv3Hq4Rfg5KLZl/gcJyMCr3nhKXXnL65pAM0EdCmkefHxvHJ4InVuzXmDru7GVQXH1bd3Uy9UIRhIs9wORlTvwesUzWEH/eTCjGSTgGRaEguo9FISRcilODuYQrcrvN8eILZxXNsiprw0azMibonkb3yuQ6mfVxtRoB4JL3vsFIbw== solarvps_key

Wayne Egerer

Leave a Reply