Secure Shell or SSH is a technology which gives you access to a remote machine. SSH server runs on port 22
by default.
SSH connection is encrypted and give you access either by username password authentication or a public-private key pair. Generally, it is secure and ergonomic to use a public-private key pair to access a host via SSH. These keys are called SSH keys.
How to generate an SSH key
You can generate an SSH key pair using ssh-keygen
command on Linux.
ssh-keygen
This command generate an RSA key pair. Give the key a name and save it inside your ~/.ssh
directory. Optionally, you can use a password to make your key more secure.
If you don’t want to go with a rsa
key pair, you can choose a different algorithm to generate the key using the -t
flag.
ssh-keygen -t dsa
ssh-keygen -t ecdsa
ssh-keygen -t ecdsa-sk
ssh-keygen -t ed25519
ssh-keygen -t ed25519-sk
ssh-keygen -t rsa
You can also select the number of bits a key should have used the -b
flag. For an RSA key pair, the minimum size is 1024 bits. If you are not sure, ssh-keygen
has some sane defaults. So you don’t have to worry about this.
Send Public key to the remote machine.
The ssh-keygen
command generate 2 files. One is the private key and the other is the public key. The public key has .pub
extension by default. You have to install this public key in the remote machine.
After installation, when you try to connect that machine using ssh, you are authenticated using your private key and remote machine’s public key.
Now, the best and easiest way to send the public key to the remote machine is using the ssh-copy-id
command.
ssh-copy-id -i ~/.ssh/your_key.pub username@hostIP
Replace the your_key.pub
with your public key, and add your username and remote machine’s IP address in username@hostIP
section.
This command first check if your public key is already present in the remote machine. If not, ssh-copy-id
command take your your_key.pub
public key and add in ~/.ssh/authorized_keys
file in the remote machine.
Establish an SSH connection.
After sending the public key using ssh-copy-id
, now test the SSH connection.
ssh username@hostIP
If you are able to log in without entering the password, you are authenticated using the SSH key. Congratulations.
Conclusion
In this blog, you have learned 1. How to generate SSH key pair 2. How to send ssh key to the remote machine 3. How to establish an SSH connection using the key pair. Hope you like this blog. Do check out other blogs and articles in this website.