SSH with Certificates

Using certificates to login via SSH is safer than using a password. And it’s more convenient if you’re using the same device to login. Here is the steps:

First, we need to generate certificates. You can generate SSH key pairs directly from PuTTY with PuTTYgen on Windows, or use OpenSSH integrated in the terminal for Mac OS.

On Windows, Run PuTTYgen as administrator, select SHA-1 RSA for key type and 2048 bits for length, and generate a key pair. Then fill in key comment and a passphase. A passphase is like a password for your private key, it’s not compulsory but recommended. Then save both of you public key and private key.

On Mac OS, use the following command in the terminal to generate key pairs:

  • ssh-keygen -t rsa

Leave the save location blank to save at default location, which is recommended (or you can specify a location if you want). Enter a passphase and verify (or you can leave them blank for no passphase). The key will be saved automatically.

Second, we need to copy the public key from PC to Raspberry Pi. Login to Raspberry Pi with SSH, then edit authorszed_keys file:

  • nano ~/.ssh/authorized_keys

Open your public key file. Paste the key in the file and save and exit nano. You can have multiple public keys each line in the file if you need to login to your Raspberry Pi from more than one device.

On Mac OS, the public key ends with “.pub”. You can use cat command to view and copy:

  • cat ~/.ssh/id_rsa.pub (if you save at default location)

Never share your private key!

Third, we need to edit sshd_config of Raspberry Pi, to disable login via password, open the file with the following command:

  • sudo nano /etc/ssh/sshd_config

Find the following lines:

  • #PasswordAuthentication yes no

We would like to delete the hash key at the front, and change yes to no. Then save and exit, and restart ssh service:

  • sudo service ssh restart

Now we can login to Pi using certificate. Only client with certificate that is registered on authorized_keys is allowed.

On Windows, you need to select your private key as login credential. Select SSH – Auth on the left menu and choose your private key, then enter your passphase if you have one. Then connect as normal.

On Mac OS, terminal will automatically use your private key to attempt to login, if there’s one in the default location. If you saved you private key in a different location, use “-i <private key file>” parameter on SSH command.

Note that if you lost all your keys, you will lose access via SSH. In such case, you need to use a keyboard and monitor to access just like the first time setup. You can edit the sshd_config to allow password login again.

Leave a Reply