Setting up SSH Keys

This is a quick tutorial on how to set up SSH keys on any *nix machine, including Linux and MacOSX.

SSH keys work by generating a private key and a public key. The private key remains with you, and can be protected by a password (recommended). You then give the public key out to all the servers you would like to authenticate with. This guide will cover both of these, from generation of the keys to implementation.

Firstly, let's generate a key.

ssh-keygen -t rsa

It will ask you some questions about where to save and passcode.


$ ssh-keygen -t rsa

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/joshcurry/.ssh/id_rsa):  (press enter)
Enter passphrase (empty for no passphrase): (super-secret-password)
Enter same passphrase again: (super-secret-password)
Your identification has been saved in /Users/joshcurry/.ssh/id_rsa.
Your public key has been saved in /Users/joshcurry/.ssh/id_rsa.pub.

The key fingerprint is: SHA256:some-fingerprint
The keys randomart image is:

'+---[RSA 2048]----+
ASCII art
+----[SHA256]-----+'

 

Now, you can copy your public key to any server you would like to log into remotely. Dont copy your private key by mistake!

scp ~/.ssh/id_rsa.pub [email protected]:~/.ssh/authorized_keys

You will have to put your password in this time to copy the file, but after that point, if the server accepts SSH keys as by default, then your computer should log in automatically. You will, however, have to put in your password if you set one.

A quick note on key security. If you ever believe that your private key, located here in ~/.ssh/id_rsa has been compromised (if someone else could have gotten ahold of it, especially if it's not password protected), it's very important that you generate a new one and remove your public key from all servers you have uploaded it to as soon as possible. With your non-password-protected private key, a person could log in as you.

To remove your old private/public key pair and start again,

Run this command on servers you have uploaded your public key to:

rm ~/.ssh/authorized_keys

 

Run this command on the computer where you want to generate a new key, to remove the old one.

rm ~/.ssh/id_rsa.pub ~/.ssh/id_rsa[/cc]

 

And finally, the following command to start again and generate a new key (see above)

ssh-keygen -t rsa

 

Have fun using SSH keys!

Published 2016-09-03