Open In App

How To Generate SSH Key With ssh-keygen In Linux?

Secure Shell(SSH) is a cryptographic network protocol used for operating remote services securely. It is used for remote operation of devices on secure channels using a client-server architecture that generally operates on Port 22. SSH is the successor of Telnet. SSH uses public and private keys to validate and authenticate users. ssh-keygen is used to generate these key pairs.

You can learn more about SSH and Telnet here



How does SSH work?

How SSH works

SSH-KEYGEN

ssh-keygen is the utility used to generate, manage, and convert authentication keys for SSH. ssh-keygen comes installed with SSH in most of the operating systems. ssh-keygen is able to generate a key using one of three different digital signature algorithms.

Files generated by ssh-keygen



“.pub” files should be copied to the $HOME/.ssh/authorized_keys file of the remote system where a user wants to log in using SSH authentication.

Generating key pairs using ssh-keygen

Almost all Unix and Linux Distro’s come pre-installed with SSH and ssh-keygen, so we will have no need to install. We will get started directly. This process is almost similar to almost all Linux Distro’s

Open your terminal and type ssh-keygen

ssh-keygen

It asks for the names of the ssh key pairs. If you wish to enter the passphrase, go on and ssh-keygen will automatically create your keys.

//Output

Generating public/private rsa key pair.

// enter the name for ssh key pairs
Enter file in which to save the key (/home/kushwanth/.ssh/id_rsa): gfg

// enter passpharse for security
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 

// ssh keys generated
Your identification has been saved in gfg
Your public key has been saved in gfg.pub

ssh key gen created

A public key looks like the one below.

Sample public key

This is the key you need to copy into your remote device to get successful SSH authentication.

Copying Public key to the remote server

After the key pair is created, now we need to copy the public key into the server. There are 2 ways to do this, using ssh-copy-id (or) manually copying it into the server.

Using ssh-copy-id

Use the ssh-copy-id command to copy your public key file (e.g., $HOME/.ssh/id_rsa.pub) to your user account on the remote server.

ssh-copy-id -i $HOME/.ssh/id_rsa.pub <user>@<your-remote-host>

Manually copying the public key

Login to your remote server using the password and create a directory at $HOME/.ssh. You can use the command below.

ssh <user>@<your-remote-host> “umask 077; test -d .ssh || mkdir .ssh”

Now send your public key to the remote server,

cat $HOME/.ssh/id_rsa.pub | ssh <user>@<your-remote-host> “cat >> .ssh/authorized_keys”

Now you can logout and test whether you can connect to the remote server using the SSH protocol.

Article Tags :