In order to securely manage multiple SSH keys and authenticate them with GitHub, it's important to follow the
correct steps.
Having multiple SSH keys is useful when you're using different machines or need to access different GitHub
accounts.
Here's a step-by-step guide on managing multiple SSH keys and authenticating them with GitHub:
$ ls -al ~/.ssh
If keys exist, it will be listed in the .ssh directory. Most of the time, the directory path will be (C:/Users/YOU)
-rw-r--r-- 1 user 197121 419 Nov 29 2022 id_ed25519 // private key
-rw-r--r-- 1 user 197121 106 Nov 29 2022 id_ed25519.pub // public key
If your machine doesn't support Ed25519 algorithm, your keys might have been generated with RSA or ECDSA algorithm:
Depending on which algorithm is supported by your local machine, you should generate a new key with your desired email, which can be different from the initial email used with the existing key.
$ cd ~/.ssh
$ ssh-keygen -t ed25519 -C "your_email@example.com"
$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
$ Enter file in which to save the key(c/users/you/.ssh/id_ed25519: "unique-key-name")
The last step is to enter a passphrase of your choice, or press enter to leave it blank.
$ ls -al ~/.ssh
You should be able to see the old & new keys as follows:
-rw-r--r-- 1 user 197121 419 Nov 29 2022 id_ed25519 // OLD private key
-rw-r--r-- 1 user 197121 106 Nov 29 2022 id_ed25519.pub // OLD public key
-rw-r--r-- 1 user 197121 419 Jul 23 2023 unique-key-name // NEW private key
-rw-r--r-- 1 user 197121 106 Jul 23 2023 unique-key-name.pub // NEW public key
If you have more than one pair of keys, you will have to create a config file in your .ssh directory to specify which key to use for each account, as the ssh-agent can't handle multiple keys:
config
file at .ssh directory path by running:$ notepad config
config
file.personal account
is the previously existed account with id_ed25519
#personal account
Host github.com
#work account
Host github.com-work
Double-check the config
is created properly by running:
$ ls -al ~/.ssh
In case you find the config
file saved as text file, run:
$ mv config.txt config
To authenticate your SSH keys, you need to add them to your GitHub account. Follow these steps:
cat .pub
in git bash to display the public key, which you
will then copy.Now that your SSH keys are set up and connected to your GitHub account, you can clone or update repositories without having to enter your credentials each time. Simply use the appropriate host alias and repository URL in your terminal. For example:
# Clone a repository using the default SSH key
$ git clone git@github.com/username/repository.git
# Clone a repository using the second SSH key
$ git clone git@github.com-work/username/repository.git
Note in the second cloned repository, we added the key word work
to
git@github.com-work
which was customized in the
config
file to the
Host.