Enabling SSH key-based authentication on a Linux machine

Enabling SSH key-based authentication on a Linux machine

It is recommended to use key-based authentication over passwords.

Generating a key pair on your local machine

We need a public-private key pair to authenticate with the server. If you have one already, skip this step. If not, enter the following command to generate a key pair.

ssh-keygen -t ed25519 -C "[email protected]"

You will be prompted to enter a path and file name for the keys. You can press Enter to save them in the default location with the default names: id_25519 and id_25519.pub in the ~/.ssh/ folder. Enter a memorable passphrase when prompted.

Install the private key on your local machine

Use ssh-agent to install the private key identity. Enter passphrase when prompted.

eval `ssh-agent -s`
ssh-add ~/.ssh/id_25519

If you encounter permission errors, run chmod 400 ~/.ssh/id_25519 and repeat the above step.

Install the public key on the target machine

Add the public key to the list of authorized keys on the server. This command uses SSH, enter your existing SSH password when prompted.

cat ~/.ssh/id_25519.pub | ssh user@hostname "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

Test your connection

On you local machine, try out your new key with a new SSH session

ssh user@hostname

If you key works, no password would be needed to access your target machine.