How To - SSH Key Generation

ssh-keygen

Ssh-keygen is a tool for creating new authentication key pairs for SSH. Such key pairs are used for automating logins, single sign-on, and for authenticating hosts.

1. Generate a ssh key

Open the Terminal app and run

$ ssh-keygen

Just hit enter a few times after you run the command ssh-keygen to take default values and you'll see:

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/XXXXXXX/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/XXXXXXX/.ssh/id_rsa.
Your public key has been saved in /Users/XXXXXXX/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:XXXXXXXXXXXX XXXXXXX@XXXXXXX-MacBook-Pro.local
The key's randomart image is:
+---[RSA 2048]----+
|          . .= ..|
|           o+ ooo|
|         o .. oo+|
|        .o+o . o+|
|       .S o.+  Eo|
|        +o = o  .|
|    ...=++o * .  |
|   . o++=o.+ +   |
|    . .==.. o.o. |
+----[SHA256]-----+

above I didn't set any passphrase. If you want extra security you can by running ssh-keygen again as it will overwrite your old key.


2. Copy ssh public key (the file ending in .pub)

Navigate to where ssh keys are stored.

$ cd ~/.ssh

This is where you should be able to find your keys.

If you run ls command you will see this:

$ cd ~/.ssh
$ ls
id_rsa      id_rsa.pub

id_rsa.pub is the public key. This is the one which should be added to services (for example Github) that need our ssh public key.

Open id_rsa.pub in your text editor. It should look something like:

ssh-rsa XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX@XXXXXXX-MacBook-Pro.local

To copy the key to clipboard use pbcopy:

$ cat ~/.ssh/id_rsa.pub | pbcopy


3. Test an ssh connection.

$ ssh <your-user>@<your-server-ip>

for example

$ ssh root@192.168.2.4

Now, you should have access to your server.

Did you find this article valuable?

Support Ashutosh Kumar Sinha by becoming a sponsor. Any amount is appreciated!