Raspberry Pi by default is accessible through SSH using a password or passphrase, the sshd is listening to any address (, this is susceptible to brute force attacks unless you have an Intrusion Detection/Prevention System like Fail2ban and a firewall (UFW uncomplicated firewall). In this post, I will show you on how to secure the Raspbian using Public-key authentication.

This is for GNU/Linux OS only for now. You need to check if you already have generated a key-pair (pub and priv):

 $ ls ~/.ssh

you should not see these files


if you do you can use them to login to Pi or just delete them so we can create a new key pair. The command below will generate 2048 bit keypair:
You will be asked on where to save the keys and just press enter also you will be asked if you want to password protect the private key if you are too lazy to provide you can just press enter (this proves the password-less authentication title of this post).

 $ ssh-keygen -t rsa -C user@pi
Sample output below:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user/.ssh/id_rsa
Your public key has been saved in /home/user/.ssh/id_rsa.pub
+---[RSA 2048]----+
|O@Xo..+x         |
|=====B=====      |
|..++..           |
|=.o.*.S . .      |
|++    o          |
|.E               |

The id_rsa is your private key (private private private!)
The id_rsa.pub is your public key you put this to the machines that you want to connect to.

You have enabled SSH to your pi (right?) if not then:

$ sudo raspi-config

and enable SSH daemon. You need to create .ssh folder if it does not exist as the standard user using ssh.
You need to put the id_rsa.pub contents to your Pi in /home/pi/.ssh/authorized_keys
this command will simply do it:
= Pi standard user
= your LAN address eg. 192.168.X.X,10.42.X.X

 $ cat ~/.ssh/id_rsa.pub | ssh @ 'cat >> .ssh/authorized_keys'

now try to login using SSH again and if it works you can now disable the password login in sshd_config.

 $ sudo nano /etc/ssh/sshd_config

Find the line:

 PasswordAuthentication and set it to no
 PasswordAuthentication no

If you are locked out of the Pi, you need to login using VNC if not then plug the Pi’s SD card to a GNU/Linux computer and mount the root partition edit the file /etc/ssh/sshd_config and set the PasswordAuthentication to yes.

Except where otherwise noted, this work is licensed under Creative Commons Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0/).
I hope that this post is useful to you, if you liked this post you may support me via liberapay. Thank you for your support.

Donate using Liberapay