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
Note:
-tmeans type of algorithmn and GitHub specifically recommends ED25519 in their documentation.-Cmeans comment you can use any comment.-fmeans file to be created
2. Enter a secure passphrase when prompted (recommended).
Note:
Passphrase are random strings for encryptions. for example use something like sahdlkgflabfadn
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)"
What above cmd does?
- Starts a background SSH agent process
- Sets SSH_AUTH_SOCK environment variable (socket path for communication)
- Sets SSH_AGENT_PID environment variable (process ID)
- Makes your shell aware of the running SSH agent
# 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
Usefull tips fo Nano Editor:
ctrl + vfor pastingctrl + kremoving linectrl + xfor clasing editor- Save changes by pressing
ythenenterafterctrl + x
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