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 here.
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
Warning: Don't use RSA nor DSA.
ssh-keygen -o -a 100 -t ed25519 -C "firstname.lastname@example.org" -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
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 -i ~/.ssh/example_com.pub email@example.com
If your system doesn't have this program or you prefer to do this manually follow the steps given below:
scpto 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
~/.sshyet, create it:
- If this directory doesn't contain a file
authorized_keys, create it:
- Append the public key you just uploaded to the
cat ~/example_com.pub >> ~/.ssh/authorized_keys
- Remove the file you uploaded:
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:
To do the equivalent of:
ssh -i ~/.ssh/example_com -p 1234 firstname.lastname@example.org
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