SSH Authentication With Keys Instead Passwords

SSH is a must have tool for every System administrator or DevOps Engineer. It provides you a secure way to access remote servers. But, if you use standard password authentication there is always a chance that someone will break into system due to weak password.  This potential risk increases if multiple users have SSH access to the server, because system administrator can’t influence to the users to make a better passwords.

The Idea Of Public Key Cryptography

The basic idea behind key-based SSH authentication rely on asymmetric cryptography also know as public key cryptography. This type of cryptographic algorithm require two separate keys. The first key is a secret or private key, and second is a public key. Public key is used to encrypt plaintext, whereas private key is used to decrypt ciphertext. You can learn more about public-key cryptography in this MDN (Mozilla Developer Network) article.

Generate Keys

First what you need to do on the client machine is to generate private/public keys. To generate private/public key set you need to run the following command:

Now you will have an option to name your key pair and set password.

Public Key Encryption

Transfer The Public Key To The Server

When you have generated private/public key-pair you need to transfer public key to the remote server. This public key will allow you to identify your self to the server. SSH comes with an utility called ssh-copy-id that simply copies content of public key to the server’s ~/.ssh/authorized_keys :

You should have output similar to this:

If you don’t have ssh-copy-id utility on your system, you can copy content of the public key and add it to the authorized_key by your self.

Disable Password Authentication

You can now connect to the remote server using a private key you generated, but your system isn’t secure just yet. You need to disable password-based and allow only key-based authentication. You can improve your server security by applying other measures, like changing default port or enabling host-based authentication, but that is not the topic of this article.

To disable password authentication open /etc/ssh/sshd_config and find the following line:

uncomment it, and set to no:

Now /etc/ssh/sshd_config should look like this:

Disable Password AuthenticationSave and restart SSH server:

If you try to connect to the server on the machine without private key, you’ll get this message:

But on your local machine, where you created private key, authentication should pass without problems:

If you have created password during key generation, you’ll be asked to enter it on each login:


Follow me

Mirza Pasic

Full Stack Developer at OLX
Web Developer. Geek. Systematic. Dreamer
Follow me

Published by

Mirza Pasic

Web Developer. Geek. Systematic. Dreamer