London, United Kingdom

(+44) 0785.600.3479 MariusCucuruz@gmail.com

SSH Keys on Linux

SSH keys and GitHub on Ubuntu 18.04.3 LTS 

The very first step is to ensure you have SSH installed and enabled. The command starts the ssh-agent in the background:
eval "$(ssh-agent -s)"
If you get an error with the above then you probably need to install the service:
sudo apt-get install openssh-server

Enable and then start the ssh service by typing:
sudo systemctl enable ssh
sudo systemctl start ssh

You’ll then need to create public / private key pairs with relevant names for the services you’ll be using them for. I suggest using separate keys and clear, relevant names to avoid confusion and make your life easier going forward. The command to create a key pair is:
ssh-keygen -t rsa -b 4096 -N 'optional-passphrase' -C "your.name@email.com" -f ~/.ssh/service-name

For instance, I would generate my GitHub keys (without a passphrase in this example) like so:
ssh-keygen -t rsa -b 4096 -N '' -C "your.name@email.com" -f ~/.ssh/github

Next step is setting the correct permissions and it’s also important otherwise you might get the infamous permission denied error:
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

You don’t need sudo here. Actually, don’t use sudo to manipulate your own files, as it can only lead to mistakes. Bellow are the correct permissions to set on the .ssh directory and files (https://gist.github.com/grenade/6318301):
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 600 ~/.ssh/github_rsa
chmod 600 ~/.ssh/mozilla_rsa
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts
chmod 644 ~/.ssh/config
chmod 644 ~/.ssh/id_rsa.pub
chmod 644 ~/.ssh/github_rsa.pub

Or, you can achieve the exact same result by running these commands in this order:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*
chmod 644 -f ~/.ssh/*.pub ~/.ssh/authorized_keys ~/.ssh/known_hosts

Next step is to add your SSH key(s) to the ssh-agent. Following on my GitHub example you could run the following command:
ssh-add ~/.ssh/github_rsa

You should also run that for all the other private keys you might have set up, if any, in the first step.

Find and take a note of your public key fingerprint. If you’re using OpenSSH 6.7 or older:
ssh-add -l

The next step is to publish your public key(s) to the appropriate service by copying the contents of the relevant public key. Again following the GitHub example, you would run xclip to get the key into your clipboard:
xclip -sel clip < ~/.ssh/github_rsa.pub

  • If you don’t have xclip you can install it with: sudo apt-get install xclip

You will need to go to Settings > SSH keys and GPG keys (https://github.com/settings/keys) and add a new SSH key where you’ll paste the previously copied public key.

Finally you should also check that the key is being used by trying to connect to git@github.com:
ssh -vT git@github.com

That should be it really.

Thanks for reading.