With SSH Keys, SSH (Secure Shell) provide a more secured solution to login on your server than password authentification, because SSH keys are almost impossible to crack with brute-force attacks (consists to try each possible password). It’s also a way to make SSH connections easier, and it provide the ability to give an SSH access to somebody without having to share a password.
SSH Keys concept
We talk about “SSH Keys” because it’s a matching pair of cryptographic keys (public and private). The public key need to be added on the remote server, and when you will launch your ssh connection, it will check if the public and the private key match, if not, you will be prompt for a password or disconnected if password authentification isn’t allowed.
Generate SSH keys
To generate ssh keys, we will use the openssh built-in tool
ssh-keygen. By default the command
ssh-keygen will generate an RSA 2048 bits private-key, but you can also generate ECDSA or ED25519 ssh keys which provide a better encryption, with shorter public keys using the Elliptic curves algorithm.
To generate ED25519 ssh keys, you can use the command :
ssh-keygen -t ed25519
You will be prompt for the path to store the keys and for a password. You can keep the default path for keys storage but it’s recommended to set a password to secure your private key because without password, anybody with your private key will be able to login on your server without password.
Install your public key on a remote server
If password authentification is allowed on your second server, you can use the command
ssh-copy-id to automatically install your ssh public key from the first server :
Install your ssh public key manually
Otherwise, you just have to copy the first server public key and to add it in the file
.ssh/authorized_keys on the new server.
To display the public key, you can use the command :
It should display something like that :
ssh-ed25519 AAAAC3FzaC1lZDI1NTE5GGGAIEwb9hr5bNmB/+3oLJgixkj29l5rzKsfs5C+BlqTnPes root@old-vps
On new-vps, create the folder .ssh in your user home directory if it doesn’t exist yet with
mkdir $HOME/.ssh before adding your public key. You can add it using
echo like in the following example :
echo 'ssh-ed25519 AAAAC3FzaC1lZDI1NTE5GGGAIEwb9hr5bNmB/+3oLJgixkj29l5rzKsfs5C+BlqTnPes root@old-vps' >> $HOME/.ssh/authorized_keys
You should now be able to login on your server with the command :
Disable password authentication
If you managed to login successfully on your server using ssh-keys, disabling password authentication is a good way to harden security on your server.
To do so, you just need to edit the file
/etc/ssh/sshd_config and to make sure the following settings are set :
# disable root password authentication PermitRootLogin prohibit-password # disable password authentication PasswordAuthentication no
Then restart ssh service to apply changes.
If you want to harden your ssh server security, you can use our recommended configuration available on Github