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 "john@example.com" -f ~/.ssh/example_com
-
-o
: Save the private key using the new OpenSSH format. Ed25519 keys always use the new format. -
-a
: Specifies the number of KDF (key derivation function) rounds used. Higher numbers result in slower passphrase verification and increased resistance to brute-force password cracking (should the keys be stolen). -
-t
: Specifies the type of key to create, in this case Ed25519. -
-C
: Provides a comment, in this case we use the email address of the owner of the key. -
-f
: Specifies the filename of the key file.
Make sure you enter a strong passphrase. After running this command two files are created in ~/.ssh
: example_com
and example_com.pub
. 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/example_com.pub user@example.com
If your system doesn't have this program or you prefer to do this manually follow the steps given below:
- Use
scp
to copy the public key to the remote host:
scp ~/.ssh/example_com.pub user@host:
- Login to the remote host.
- If your account doesn't have a directory
~/.ssh
yet, create it:
mkdir ~/.ssh
- If this directory doesn't contain a file
authorized_keys
, create it:
touch ~/.ssh/authorized_keys
- Append the public key you just uploaded to the
authorized_keys
file:
cat ~/example_com.pub >> ~/.ssh/authorized_keys
- Remove the file you uploaded:
rm ~/example_com.pub
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
HostName example.com
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 john@example.com
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.