Skip to content

Instantly share code, notes, and snippets.

@6aditya8
Last active April 2, 2019 09:51
Show Gist options
  • Save 6aditya8/58ff8993c891b34fb4d1b46224f4ad30 to your computer and use it in GitHub Desktop.
Save 6aditya8/58ff8993c891b34fb4d1b46224f4ad30 to your computer and use it in GitHub Desktop.
Generating a new SSH key and adding it to the ssh-agent & to your github account

Checking for existing SSH keys

Before you generate an SSH key, you can check to see if you have any existing SSH keys.
1. Open Terminal
2. Enter ls -al ~/.ssh to see if existing SSH keys are present. This lists the files in your .ssh directory, if they exist. Check the directory listing to see if you already have a public SSH key.

If you don't have an existing public and private key pair, or don't wish to use any that are available to connect to GitHub, then generate a new SSH key.

If you receive an error that ~/.ssh doesnt exist, dont worry! We will create it when we generate a new SSH key.

Generating a new SSH key

After you've checked for existing SSH keys, you can generate a new SSH key to use for authentication
1. Open Terminal
2. Enter ssh-keygen -t rsa -b 4096 -C "your_email@example.com" substituting in your GitHub email address. This creates a new ssh key, using the provided email as a label.

> Generating public/private rsa key pair.

3. When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.

> Enter a file in which to save the key (/home/you/.ssh/id_rsa): [Press enter]

4. At the prompt, type a secure passphrase.

> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]

Adding your SSH key to the ssh-agent

1. Start the ssh-agent in the background.

$ eval "$(ssh-agent -s)"
> Agent pid 59361

2. Add your SSH private key to the ssh-agent. If you created your key at a different location, or if you are adding an existing key that has a different name, replace id_rsa in the command with the name of your private key file.

$ ssh-add ~/.ssh/id_rsa

Adding SSH key to your GitHub account

1. Copy the contents of the file ~/.ssh/id_rsa.pub
2. To add the SSH key to your account, Go to:
Settings -> SSH and GPG keys -> New SSH Key
3. To add the SSH key only to a specific repository, Go to:
Your Profile -> Repositories -> Your Repository -> Settings -> Deploy Keys -> Add deploy key
4. Provide a title, paste in your public key.
5. Select Allow write access if you want this key to have write access to the repository. A deploy key with write access lets a deployment push to the repository.
6. Click Add key.

Setting your git repository to use the SSH key

Now cd to your git clone folder and:

git remote set-url origin git@github.com:username/your-repository.git
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment