Git SSH Key

There are two ways to connect to a remote repository: HTTPS and SSH. With SSH you use a pair of keys, and you do not enter a username and password for each push. It is the preferred way for daily work.

How SSH keys work

  • The private key stays on your computer. Never share it.
  • The public key is given to GitHub or GitLab, in your account settings.
  • When you connect, the server checks that your private key matches the public key you gave. If yes, you are in.

Step 1: Check for existing keys

Terminal output

$ ls ~/.ssh
ls: /home/robin/.ssh: No such file or directory

If the folder is empty or does not exist, you have no key yet. If you see files like id_ed25519 and id_ed25519.pub, you already have a key, and you can use it.

Step 2: Generate a new key

ssh-keygen -t ed25519 -C "robin@example.com"

The program asks where to save the key (press Enter for the default) and for a passphrase. A passphrase is an extra password for the key, and it is a good idea to set one. Here we skip the questions to show the result:

Terminal output

$ mkdir -p ~/.ssh
$ ssh-keygen -t ed25519 -C "robin@example.com" -f ~/.ssh/id_ed25519 -N "" -q
$ ls ~/.ssh
id_ed25519
id_ed25519.pub

Two files were created: id_ed25519 (private) and id_ed25519.pub (public). If your system is old and does not support Ed25519, use ssh-keygen -t rsa -b 4096 -C "your email".

Step 3: Add the key to the SSH agent (optional)

The agent remembers your passphrase so you do not type it every time.

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

Step 4: Copy the public key

Print the public key and copy the full line. Never copy the file without .pub.

cat ~/.ssh/id_ed25519.pub

It is one line which starts with ssh-ed25519 and ends with your email.

Step 5: Add the public key to GitHub or GitLab

  • GitHub: Settings, then SSH and GPG keys, then New SSH key. Paste the key and save.
  • GitLab: Preferences, then SSH Keys. Paste the key, give a title and click Add key.

Step 6: Test the connection

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

The first time, you will be asked to confirm the server fingerprint. Type yes. A success message says that you are authenticated.

Use SSH for a repository

git clone git@github.com:username/project.git
git remote set-url origin git@github.com:username/project.git

SSH vs HTTPS

TopicSSHHTTPS
LoginKey pair, no password promptsUsername and token (password is not accepted now)
SetupOne time key setupEasier first time, but needs a credential helper
Works behind strict firewallsSometimes blocked (port 22)Usually works
URL looks likegit@github.com:user/repo.githttps://github.com/user/repo.git
Note: If someone gets your private key, they can act as you. Use a passphrase, and if a key is lost, remove it from your GitHub or GitLab account at once. Next: Git Submodule.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.