Perl programmer for hire: download my resume (PDF).
John Bokma's Hacking & Hiking

SSH Public Key Authentication How To

May 27, 2019

I recently helped someone out with creating a key pair for SSH public key authentication. Because this might be useful for others I decided to write down my notes in this blog post.

Generating a key pair

Public key authentication requires two keys: a private one and a public one. A key pair is generated on the command line using the ssh-keygen program.

Warning: Don't use RSA nor DSA.

ssh-keygen -o -a 100 -t ed25519 -C "" -f ~/.ssh/example_com

Make sure you enter a strong passphrase. After running this command two files are created in ~/.ssh: example_com and Be aware that the former is the private key and should not be copied to the server.

Uploading the public key

The easiest way to upload your public key is using ssh-copy-id:

ssh-copy-id -i ~/.ssh/

If your system doesn't have this program or you prefer to do this manually follow the steps given below:

  1. Use scp to copy the public key to the remote host:
scp ~/.ssh/ user@host:
  1. Login to the remote host.
  2. If your account doesn't have a directory ~/.ssh yet, create it:
mkdir ~/.ssh
  1. If this directory doesn't contain a file authorized_keys, create it:
touch ~/.ssh/authorized_keys
  1. Append the public key you just uploaded to the authorized_keys file:
cat ~/ >> ~/.ssh/authorized_keys
  1. Remove the file you uploaded:
rm ~/

Using a configuration file

On your local system check if there is a file ~/.ssh/config. If not, create a new file with the following settings at the very top:

ServerAliveInterval 30
ServerAliveCountMax 4

This will keep your SSH connection alive even if you're not using it for a while.

Next, create an entry for your server as follows:

Host ex
     User john
     Port 1234
     IdentityFile ~/.ssh/example_com

With the above settings you can just use:

ssh ex

To do the equivalent of:

ssh -i ~/.ssh/example_com -p 1234

Note: if you use the default port there is no need for a Port entry. Also, if the remote username is the same as the local user there is no need for a User entry.