Using an SSH Key to Authenticate to GitHub

I did these steps on Ubuntu 22.04.

If you don't already have git installed, run this command to install it:

sudo apt install git -y

Create a public/private key pair

Run this command to create a key pair:

ssh-keygen

Run this command to see the public and private key files:

ls -al ~/.ssh/

You should see the following two files:

Display the contents of the public key by entering this command:

cat ~/.ssh/id_rsa.pub

You should see something that looks similar to this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDAREZ5BUAjsLs8cCfruJiFc9QMYgCuH1QpmVPxSdvPrm23p8fI6WJRMKSkpEeKdXtR/pmmNx6EOgsRoq2fE+SRLsFMALSSXh2HQ8hM9+bGsfqryr4SUxur7tXiiXiSLTIEgZJRMZCMc1Jgr6FdgFPG6UDah4dUGc4eQQmmTaQ/5LoBZIAQZDb5PKCoxseFIXzfMufM9p5/KHovatAoqnZFXPddFEUNFbYbD3usyO9HGpXfOCTCIPfuy8X3XscH2JWeEO6n7e1lpmg5acGDxsuh4rGylf/yK/EzhQolKosCopbBQEkV/fOAq5JzCoemYlRHDHeNzTK50Um25AMF3Zsa5bAk23edw2L/5v6xC2CW9LqMDTRX1hH0H7+euu7t0nXDgFD8XQJ2kn7dMtLlQ4SkV74rVfh6fcKpo7CcpN2klDoWov9lM601J1qewfJ8aVGSuW8UMXJAp+pk1sP9XKnOOn2YsBhshpK5MVEA2NZuVyZkM8DKsaYLyY5/t5PXO1k= ubuntu@ip-172-31-9-166

Copy the contents of the public key file, but be careful not to include any spaces at before or after the file contents.

Set up the (public) SSH key in GitHub

When you set up an SSH key for your account, it can be used to access any repository in the account.

Here are the steps to set the SSH key for your account:

  1. Log into GitHub
  2. Click on your user icon in the upper right corner and choose Settings
  3. In the left nav, click SSH and GPG Keys
  4. Click New SSH Key
  5. In the Title textbox, enter a name for the ssh key
  6. Paste the public key contents into the textbox for the Key
  7. Click Add SSH Key

Create an SSH config file

Back in the Ubuntu 22.04 terminal, run the following commands to cd into the .ssh folder and create a config file:

cd ~/.ssh
nano ~/.ssh/config

Copy and paste this into the file:

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

Note that the user should always be set to 'git', because it's the git account that will run the git commands on your behalf.

To save the file, press Ctrl+x then press Enter.

Run this command to set the permissions of the config file:

chmod 600 ~/.ssh/config

Run this command to test the configuration and authentication:

ssh -T git@github.com

Enter 'yes', then enter the passphrase you created for the key pair, you should see a message saying that you successfully authenticated to your GitHub account.

Finally, you can clone a repository from your GitHub account with a command that looks something like this (you'll have to use your own repository url, but make sure it's an SSH url):

git clone git@github.com:your-username/your-repository.git

Note that if you are doing this activity on an AWS EC2 instance, it seems to be customary to clone repos into the /opt folder. But you'll have the change the permissions on this folder:

sudo chown ubuntu.ubuntu -R /opt