SSH Authentication using a Public/Private Key Pair

I always have to remind myself how to setup SSH authentication using a public/private key pair when I install a Linux server as it's something I usually setup and forget about until I have to do it again. So this is here as a reminder to myself.

Overview: The public/private key pair is generated on the client, the public key is then copied onto the server. Only a client that has the private key can respond to an auth challenge issued by the server using the public key.

Use the ssh-keygen command to generate the public/private key pair on the client, by default your private key is stored in /home/user/.ssh/id_rsa and your public key is stored in /home/user/.ssh/

user@client:~$ ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/
The key fingerprint is:
23:2c:5e:45:f9:c5:10:d8:67:6f:b6:45:c7:28:4e:a8 user@client
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|      . +        |
|o. . o o         |
|+.o o * A        |
| o.=.* .         |
| -oo= -          |
|. Fo -           |
|  . .            |

Use the ssh-copy-id command to automatically add your public key to /home/user/.ssh/authorized_keys on your server. If the file doesn't already exist it will be created using mode 600.

user@client:~$ ssh-copy-id user@server
user@server's password: 
Now try logging into the machine, with "ssh 'user@server'", and check in:


to make sure we haven't added extra keys that you weren't expecting.

That's it, next time you SSH to your server you should be logged in without having to type in a password.

I should point out it's good security practice to encrypt your key pair with a passphrase, however doing so will mean that you will be required to enter your passphrase each time you try to connect to your server.