Generating and using an SSH key

For anyone that uses Secure Shell (SSH) on a regular basis, the ability to use a key to secure an SSH session is invaluable. An SSH key can be used to automate secure access without having to manually put in your credentials every time you login to a host. You can even add your public key to some LDAP systems, making it easier to authenticate in a corporate environment.
All the examples were done on Linux or MacOS, but should work on any *nix like system.
Let’s start with the easiest part of the process, creating your key. This process will generate two files, your private key and your public key. An example of the key generation command is below:
ssh-keygen -t rsa -b 4096 -C "your-email-address@example.com" -f my_key
When prompted for a passphrase, pick something complex. You do not want to leave it empty. Without a passphrase, anyone who gets their hands on your private key can use it as you.
Lets discuss the command to generate the key. The -t rsa
tells ssh-keygen to generate an RSA key. The -b 4096
says to create a 4096 bit key. The -C
option followed by your email address (obviously, don’t us “your-email-address@example.com”) is put in the comments field. This is generally considered a good practice. The -f
option gives you the ability to name your key files. By default they would be id_rsa for your private key and id_rsa.pub for your public key. When using the -f
option, you can name the files what ever you want. For my own reference, I tend to name them something to easily identify the keys. For a work set of keys I might call the file id_rsa_4096_work.
Now that you have your new key, lets send it over to a host that you have access to.
ssh-copy-id -i ~/.ssh/my_key user@host1.example.com
It will ask you for your password then adds your my_key.pub file to the ~/.ssh/authorized_keys file on host1.example.com.
Since you have not used this key before, you will need to add it to your SSH agent. There are two ways to do it:
- Using the ssh-add utility:
ssh-add
This will prompt you for your passphrase. - The easiest way is to just connect to the host with ssh:
ssh user@host1.example.com
This too will prompt you for you passphrase.
As long as your private key is loaded in your SSH agent and you are logging into a host that has your public key, you will no longer need to type in your passphrase when logging in.