When working with Git using the command line, the most common and secure way to handle authentication is through the use of SSH keys. This guide will walk you through the process of setting up SSH keys for Git.
SSH keys on your computer
SSH keys are stored in the ~/.ssh
folder on your computer. You can store multiple keys in this folder, as SSH keys are used for purposes other than just Git. To view all your SSH keys, open your command line and type:
ls -al ~/.ssh
You’ll notice that SSH keys are stored in pairs, with one file containing the public key and another file with a .pub
extension containing the private key. It’s important to never share your private key.
Generating a new SSH key
To generate a new SSH key, you need to use the ssh-keygen
command. This command is available on macOS, Linux, and modern Windows computers with the Linux subsystem or the Git for Windows package installed.
Use the following command to generate a new SSH key:
ssh-keygen -t rsa -b 4096 -C "[email protected]"
Replace [email protected]
with your email or any other identifier. This comment is useful for future reference if there is ambiguity in key ownership.
During the key generation process, you’ll be asked where you want to save the key. For the first key, it’s suggested to use id_rsa
as the filename, but you can choose a name that helps you identify the service it’s used for, such as github_rsa
.
You can also add an optional password to your SSH key for added security. It’s highly recommended to set a password, as macOS will store it in the Keychain, so you don’t have to enter it repeatedly.
Adding the key to GitHub (or other Git platforms)
To use your SSH key with GitHub (or any other Git platform), you need to add it to your account settings. Here’s how to do it with GitHub:
-
Go to your GitHub account settings and navigate to the “SSH and GPG keys” section.
-
Click on “New SSH key” to add a new key.
-
Give the key a meaningful title, something you’ll remember in the future.
-
In the key field, copy the content from the
.pub
file of the SSH key you generated earlier. You can use a command likecat id_rsa.pub
to view the contents of the file and copy it. -
Save the key. Once you’ve added the key to GitHub (or any other service), your Git client will have the necessary credentials to communicate securely with the remote server.
Using multiple keys
It’s recommended to use a different SSH key for each service you plan to use. This allows you to easily invalidate a key on a specific service without affecting other services. If a key is compromised or publicly exposed, you can simply generate a new key for that specific service without impacting all your other services.
Tags: Git, SSH, authentication, security, SSH keys