How to generate SSH keys
Guide to Creating and Managing Multiple SSH Keys on Your System
Creating different SSH keys is useful when you have multiple accounts, servers, or services. Here's a straightforward guide on how to create and manage multiple SSH keys on your system:
Step 1: Generate a New SSH Key
To generate a new SSH key, you can use the following command:
ssh-keygen -t ed25519 -C "your_email@example.com"
-t ed25519specifies the key type. Ed25519 keys are recommended for their security and performance. Alternatively, you can use RSA (-t rsa -b 4096) if Ed25519 is not supported by your server.-C "your_email@example.com"is a comment to easily identify the key.
Step 2: Specify a Custom Key Name
When prompted, enter a custom file name to distinguish keys. For example:
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/user/.ssh/id_ed25519): /home/user/.ssh/id_ed25519_github
This will create two files:
- Private key: ~/.ssh/id_ed25519_github
- Public key: ~/.ssh/id_ed25519_github.pub
Step 3: Add the SSH Key to Your SSH Agent
To use the new SSH key conveniently, firstly ensure your SSH agent is running by executing:
eval "$(ssh-agent -s)"
Then, add your private key to the SSH agent:
ssh-add ~/.ssh/id_ed25519_github
Step 4: Add the SSH Public Key to Your Server or Service
You must add the public key (~/.ssh/id_ed25519_github.pub
) to your server or service (such as GitHub, GitLab, Bitbucket, or your remote server's authorized_keys
file).
- For GitHub/GitLab/Bitbucket: Copy the content of your public key file (
cat ~/.ssh/id_ed25519_github.pub) and paste it in their web interface under your account settings → SSH keys. - For remote Linux servers: Append the public key to the
authorized_keysfile:
ssh-copy-id -i ~/.ssh/id_ed25519_github.pub user@your_server_ip
or manually:
cat ~/.ssh/id_ed25519_github.pub | ssh user@your_server_ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Step 5: Using Different SSH Keys for Different Hosts
Edit your SSH configuration file (~/.ssh/config
) to specify which key should be used for which host:
vim ~/.ssh/config
Example content:
``` Host github.com HostName github.com User git IdentityFile ~/.ssh/id_ed25519_github
Host myserver HostName your_server_ip User your_username IdentityFile ~/.ssh/id_ed25519_server ```
After this configuration, you can connect directly with:
ssh myserver
or clone repositories directly from GitHub without further configuration.
Step 6: Test Your Setup
Test the SSH key setup by connecting to your server or service:
ssh -T git@github.com
or
ssh your_username@your_server_ip
If configured correctly, you'll see a successful authentication message.
Summary
You can create and manage multiple SSH keys by:
- Generating keys with unique names.
- Adding them to your SSH agent.
- Specifying which key to use for each host in your SSH configuration.
This approach helps you manage multiple accounts and servers securely and efficiently.