We will use a program called ssh-keygen to generate our SSH key. Run the following command:
$ ssh-keygen -t rsa -b 4096 -C <your-email-address>
Here, we are passing a few parameters to ssh-keygen, which instructs it to use the Rivest-Shamir-Adleman (RSA) cryptographic algorithm to generate key pairs of 4,096 bits in length. By default, ssh-keygen uses a key length of 2,048 bits, which should be sufficient, but since 4,096 is significantly harder to brute-force, why not enjoy that bit of extra security?
There are many algorithms that can be used to generate key pairs. ssh-keygen accepts DSA, RSA, Ed25519, and ECDSA.
DSA is an old algorithm that is superseded by RSA, and should not be used. Ed25519 and Elliptic Curve Digital Signature Algorithm (ECDSA) are from a newer breed of cryptographic algorithms that rely on the mathematical properties of some very particular elliptical curves. They may potentially supersede RSA, as they can provide the same level of security but with shorter keys.
You can use ECDSA in place of RSA by running ssh-keygen -t ecdsa -b 521 instead (note that 521 is not a typo), or Ed25519 by running ssh-keygen -t ed25519.
DSA is an old algorithm that is superseded by RSA, and should not be used. Ed25519 and Elliptic Curve Digital Signature Algorithm (ECDSA) are from a newer breed of cryptographic algorithms that rely on the mathematical properties of some very particular elliptical curves. They may potentially supersede RSA, as they can provide the same level of security but with shorter keys.
You can use ECDSA in place of RSA by running ssh-keygen -t ecdsa -b 521 instead (note that 521 is not a typo), or Ed25519 by running ssh-keygen -t ed25519.
After you execute the command, a wizard will ask you several questions:
- Enter file in which to save the key: By default, the keys will be saved under the .ssh directory in your home directory.
- Enter passphrase/Enter same passphrase again: Anyone with access to your private key will be able to log in to your server. If you want extra security measures to protect your private key, you can set a password on it. Doing so means that only people who have your private key and your password are able to log in.
Programs that run inside environments where user input is not possible may have to use an SSH key without a passphrase; otherwise, having a passphrase is recommended.
After you've answered those questions, ssh-keygen will generate a private key (id_rsa)/public key (id_rsa.pub) pair and save them under the ~/.ssh directory:
Your identification has been saved in $HOME/.ssh/id_rsa.
Your public key has been saved in $HOME/.ssh/id_rsa.pub.
If you do not set a passphrase on your private key, anyone with your private key is able to gain access to any servers that use the corresponding public key to authenticate you. Therefore, generally speaking, never share your private key.