Public/private key authentication using SSH

ssh

If your home directory does not have an .ssh directory - start by creating one:

1
mkdir -p $HOME/.ssh   

Set the permissions on it so that only you can see whats in it and read from it:

1
 chmod 0700 $HOME/.ssh

Generating your private/public keypair requires the use of the ssh-keygen command:

1
 ssh-keygen -t rsa

SSH-Keygen then prompts you the Key Pair location and name, It provides a sensible default($HOME/.ssh/id_rsa), and unless you already have a keypair stored at that location i recommend using the default setting. SSH-Keygen also prompts for whether you want to set a password for your key, -this is highly recomended in order to strengthen security. Example key generation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/sshuser/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/sshuser/.ssh/id_rsa.
Your public key has been saved in /Users/sshuser/.ssh/id_rsa.pub.
The key fingerprint is:
40:de:ad:be:ef:ca:fe:ba:be:b0:a1:c2:fa:83:b2:a3 sshuser@workmachine
        The key's randomart image is:
+--[ RSA 2048]----+
| oo    ......     |
|.oo  .. .ooo     |
|o .o. . .o  .    |
| o ...+o.        |
|  o .=.=S        |
| .  .Eo .        |
|                 |
|                 |
|                 |
+-----------------+

Once the keys are generated, you will have two new files in the $HOME/.ssh/ directory:

  • $HOME/.ssh/id_rsa - contains your private key.
  • $HOME/.ssh/id_rsa.pub - contains your public key.

The private key must be carefully protected (even if you have set a password).

In order to use your key pair to log in to remote servers, you need to transfer the public key to your existing account on the server. you can use either SCP to do a direct copy or use ssh-copy-id:

Now that the keys are uploaded, you can connect to the server in the usual way:

If you have taken care to password protect your key file, you will be asked for the password, and then you are logged in.