How to Set Up SSH Authentication for GitHub and Git

Category: Software Install and Setup

SSH authentication provides a secure and convenient way to access GitHub repositories without the need to enter passwords. If you frequently push or pull changes, using SSH keys can streamline your workflow and enhance security. This guide will take you through the process of setting up SSH authentication for Git and GitHub.

1. Check for Existing SSH Keys

Before generating a new SSH key, check if one already exists on your system:

ls -al ~/.ssh

If you see files like id_rsa and id_rsa.pub, you already have an SSH key.

2. Generate a New SSH Key

If you don’t have an SSH key, generate one using:

ssh-keygen -t ed25519 -C "[email protected]"

If your system does not support ed25519, use:

ssh-keygen -t rsa -b 4096 -C "[email protected]"

Follow the prompts and save the key in the default location.

3. Add Your SSH Key to the SSH Agent

To use your SSH key, ensure the SSH agent is running:

eval "$(ssh-agent -s)"

Add your SSH private key to the agent:

ssh-add ~/.ssh/id_ed25519

4. Add the SSH Key to Your GitHub Account

Copy your public SSH key:

cat ~/.ssh/id_ed25519.pub

Log in to GitHub SSH keys settings and:

  • Click New SSH Key.
  • Enter a title (e.g., "My Laptop").
  • Paste the public key and save it.

5. Test the SSH Connection

Verify the SSH connection with GitHub:

ssh -T [email protected]

If successful, you’ll see a message like:

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

6. Configure Git to Use SSH

Ensure Git is using SSH instead of HTTPS:

git remote set-url origin [email protected]:username/repository.git

7. Using SSH Authentication with Git

Once SSH is set up, use Git as usual:

# Clone a repository
    	git clone [email protected]:username/repository.git
# Push changes
    	git push origin main
# Pull changes
    	git pull origin main

8. Troubleshooting SSH Issues

If you encounter issues, try the following:

  • Ensure the SSH key is added to the agent:
ssh-add -l
  • Check the SSH key permissions:
chmod 600 ~/.ssh/id_ed25519
  • Verify your GitHub SSH settings are correct.

Conclusion

SSH authentication is a secure and efficient way to work with GitHub repositories. By setting up SSH keys, you can avoid repeatedly entering passwords while ensuring encrypted connections. For more details, check the official GitHub SSH guide.