Setting Up SSH Key for GitHub


Back to All Posts

If you're facing the error Permission denied (publickey) when trying to push to a GitHub repository, it means your SSH key is either missing or hasn't been added to your GitHub account for authentication. Follow these steps to resolve the issue.

Step 1: Check if You Have an SSH Key

First, check if you already have an SSH key on your system:

ls -al ~/.ssh

If you see id_rsa and id_rsa.pub (or similar key pairs), it means you have an SSH key already.

Step 2: Generate an SSH Key (if needed)

If you don't have an SSH key, you can generate one:

ssh-keygen -t ed25519 -C "your_email@example.com"
  • When prompted, save the file in the default location by pressing Enter.
  • You can set a passphrase if you want additional security, but it's optional.

Step 3: Add Your SSH Key to the SSH Agent

Now, add the SSH key to your SSH agent:

  1. Start the SSH agent in the background:

    eval "$(ssh-agent -s)"
    
  2. Add the SSH private key to the agent:

    ssh-add ~/.ssh/id_ed25519
    

    (If your key is named id_rsa, use that instead of id_ed25519).

Step 4: Add SSH Key to Your GitHub Account

Copy the contents of your public key (id_ed25519.pub or id_rsa.pub):

pbcopy < ~/.ssh/id_ed25519.pub

If you use id_rsa, replace id_ed25519 with id_rsa.

Then:

  1. Go to GitHub SSH settings.
  2. Click New SSH key.
  3. Paste the key into the "Key" field.
  4. Give it a title (e.g., "Macbook Key") and click Add SSH key.

Step 5: Test the SSH Connection

Verify that your SSH key is working by running:

ssh -T git@github.com

If successful, you should see a message like:

Hi username! You've successfully authenticated, but GitHub does not provide shell access.

Step 6: Push Your Changes Again

Now, try pushing to your repository again:

git push -u origin main

This should work if everything is set up correctly.


You are now ready to use SSH for pushing to your GitHub repositories!