Setting up key-pair ssh on Raspberry Pi
If you plan to use a Raspberry Pi board as a home server you will most likely install an OS that does not come with an UI. In this case you will need to use ssh to remotely access and manage the server. In this article I am presenting how to setup using ssh with a key pair.
1. Generate private/public key pair on the client
There are multiple tools and libraries that facilitate key-pair generation. A common one is OpenSSL. In this tutorial I will be using a tool integrated in the macOS terminal, ssh-keygen.
Run the following command:
ssh-keygen -t rsa
Provide the path for the key pair to be stored at, for example:
~/.ssh/rpi_rsa
It is recommended to provide a passphrase when asked, but you will be asked for it each time you ssh into RPi.
At this point you should have two files at the location you provided, in my case the files are rpi_rsa and rpi_rsa.pub. The private key is kept secret and should never be shared. The public key can be freely distributed.
2. Copy the generated public key to the RPi
ssh-copy-id -i ~/.ssh/rpi_rsa.pub <RPi_USER>@<RPi_IP>
When a user attempts to connect to an SSH server, the server requests authentication. The user then presents their public key to the server.
The server verifies the authenticity of the public key by checking if it matches any of the authorized public keys stored on the server.
3. Secure SSH into the server
Now you should be able to execute the following command and ssh into the server without being asked for a password.
ssh <RPi_USER>@<RPi_IP>
When the public key is recognized, the server generates a challenge that can only be decrypted with the corresponding private key. The user’s SSH client uses the private key to decrypt the challenge and proves its identity to the server.
The decrypted challenge matches the expected response and access is granted to the user.
[DEBUG]
If you are still asked for the password you can check if the ssh-copy-id command worked.
SSH into the RPi and run the following command.
nano ~/.ssh/authorized_keys
You should find the content of the public key (the rpi_rsa.pub file) in here. If it is not here it means that the ssh-copy-id command failed.