How to set up Git to use an SSH key for authentication

Arif Billah Babu

         

  git



Image not found!!

Setting up Git to use an SSH key for authentication involves a few steps. Here's a general guide:

1. Generate SSH Key Pair:

If you don't have an SSH key pair, you'll need to generate one. Open a terminal and run:

bash
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Follow the prompts, and you can leave the passphrase empty if you want.

2. Add SSH Key to SSH Agent (Optional, but recommended):

To avoid entering your passphrase every time you use your SSH key, you can add it to the SSH agent. Start the SSH agent:

bash
eval "$(ssh-agent -s)"

Add your SSH key to the agent:

bash
ssh-add ~/.ssh/id_rsa

3. Add SSH Key to Git:

Copy your public key to the clipboard:

bash
pbcopy < ~/.ssh/id_rsa.pub

If you're on Linux, you can use:

bash
xclip -sel clip < ~/.ssh/id_rsa.pub

4. Add SSH Key to Your Git Hosting Service:

Paste the copied SSH key into your Git hosting service (GitHub, GitLab, Bitbucket, etc.). The process might vary depending on the platform, but generally, you'll find a "SSH and GPG keys" section in your account settings where you can add your SSH key.

5. Verify SSH Configuration:

Make sure your SSH configuration is set up correctly. Check if your ~/.ssh/config file exists; if not, create one. Add the following content:

plaintext
Host * AddKeysToAgent yes UseKeychain yes IdentityFile ~/.ssh/id_rsa

This configuration ensures that your SSH key is added to the agent when you use Git.

6. Test the Connection:

Finally, test the SSH connection to your Git hosting service:

bash
ssh -T git@github.com

Replace github.com with your Git hosting service's domain. You should see a message indicating a successful authentication.

7. Use SSH URL for Git Repositories:

When you clone or set up a Git repository, make sure to use the SSH URL instead of HTTPS. For example:

bash
git clone git@github.com:username/repo.git

That's it! Your Git setup is now configured to use an SSH key for authentication.