Setup SSH keys for GitHub and Gitlab

1. Open Terminal and run:


                # For GitHub
ssh-keygen -t ed25519 -C "your-email@example.com" -f ~/.ssh/id_github
 
# For GitLab  
ssh-keygen -t ed25519 -C "your-email@example.com" -f ~/.ssh/id_gitlab
            

3. Start SSH Agent

You often don’t need this command because macOS usually runs SSH agent automatically. But for compatibility across different systems we can use this command.


                eval "$(ssh-agent -s)"
            

                # See if agent is already running
echo $SSH_AUTH_SOCK
 
# If it returns a path, agent is already running
# If empty, then you need eval "$(ssh-agent -s)"
            

4. Create and modify: ~/.ssh/config:


                touch ~/.ssh/config
nano ~/.ssh/config
            

Add this configuration:


                Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_github
  AddKeysToAgent yes
  UseKeychain yes
 
Host gitlab.com
  HostName gitlab.com
  User git
  IdentityFile ~/.ssh/id_gitlab
  AddKeysToAgent yes
  UseKeychain yes
            

5. Add keys to keychain:


                ssh-add --apple-use-keychain ~/.ssh/id_github
ssh-add --apple-use-keychain ~/.ssh/id_gitlab
            

6. Copy public keys (one at a time):


                # Copy GitHub key, then paste in GitHub Settings > SSH Keys
pbcopy < ~/.ssh/id_github.pub
 
# Copy GitLab key, then paste in GitLab Settings > SSH Keys  
pbcopy < ~/.ssh/id_gitlab.pub
            

7. Test the connection:


                ssh -T git@github.com
ssh -T git@gitlab.com