In this article, we’ll look at how to configure a secure SSH connection to GitHub on Unix-like systems (macOS, Linux). Setting this up allows you to push and pull code without constantly entering your username and password.

1. Generate the SSH Keys

First, we need to generate a new SSH key pair. SSH keys are typically stored in the .ssh directory in your user profile.

  1. Open your terminal and navigate to the SSH directory:
1
cd ~/.ssh
  1. Generate a pair of RSA keys with 4096-bit encryption:
1
ssh-keygen -t rsa -b 4096
  1. Name your key:
    The tool will ask you to input a <filename>. It is best to give it a specific name (e.g., id_rsa_github) to avoid overwriting any existing default keys (like id_rsa).

    Warning: If you enter the name of a file that already exists, it will be overwritten. This action cannot be undone!

  2. Set a passphrase:
    Next, you will be asked for a passphrase. While you can leave this empty, it is highly recommended to set a passphrase for added security.

Once finished, you will have two new files:

  • <filename>: Your Private Key. Never share this with anyone.
  • <filename>.pub: Your Public Key. This is what you will share with GitHub.

2. Add the Public Key to GitHub

Now that you have your keys, you need to authorize the public key on your GitHub account.

  1. Copy the contents of your public key file (.pub). You can view it using cat <filename>.pub in your terminal.
  2. Visit the GitHub SSH Keys Settings page.
  3. Click the green New SSH key button.
  4. Give the key a name (e.g., “My Laptop”) and paste your public key into the “Key” field.
  5. Click Add SSH key.

3. Configure Your System

Finally, tell your system to use this specific key whenever you interact with GitHub. You can do this by editing the config file located in your .ssh folder.

Create or edit the file ~/.ssh/config and add the following block though nano, vim or any editor you like:

1
2
3
4
5
# GitHub
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/<filename>

What this does:

  • Host: Identifies that these rules apply when you connect to github.com.
  • IdentityFile: Tells SSH specifically which private key (<filename>) to use for this connection.

Or you could directly execute:

1
2
3
4
5
6
7
8
mkdir -p ~/.ssh && cat <<EOF >> ~/.ssh/config

# GitHub
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/<filename>
EOF

You are now ready to clone and push repositories using the SSH URL!