...
Skip to main content
Print

How to Generate an SSH Key and Log In With It

You create an SSH key with the ssh-keygen command on your own computer. Then you copy the public key to your server, so you log in without a password and far more securely. In this article you read step by step how to create an SSH key on Windows, macOS and Linux, how to put it on your VPS and how to disable password login afterwards.

What is an SSH key?

An SSH key consists of two parts: a private key that stays on your own computer, and a public key that you put on the server. When you log in, the server checks whether your private key matches the public key. An SSH key cannot be guessed like a password, so brute-force attacks stand no chance.

Step 1: create an SSH key

Open PowerShell on Windows, or the Terminal on macOS and Linux, and run this command:

ssh-keygen -t ed25519 -C "jouw@email.nl"

Press Enter to save the key in the default location. Then choose a passphrase: it protects your private key if someone gains access to your computer. The keys are stored in the .ssh folder in your user folder:

  • id_ed25519: your private key. Never share it with anyone.
  • id_ed25519.pub: your public key. This is the one you put on the server.

If you work with an older system that does not support Ed25519, use a 4096-bit RSA key:

ssh-keygen -t rsa -b 4096

Step 2: put the public key on your VPS

On macOS and Linux you copy the public key to your server in one go:

ssh-copy-id root@JOUW-IP

On Windows ssh-copy-id is not available. Use this command in PowerShell instead:

type $env:USERPROFILE\.ssh\id_ed25519.pub | ssh root@JOUW-IP "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

You log in with your password one last time. The public key is added to the ~/.ssh/authorized_keys file on the server.

Step 3: log in with your SSH key

Log in again. If everything is set up correctly, the server no longer asks for your password, at most for the passphrase of your key:

ssh root@JOUW-IP

Step 4: disable password login

Once logging in with your key works, disable password login. Adjust these lines in the SSH configuration file:

PasswordAuthentication no
PubkeyAuthentication yes

Then restart SSH with systemctl restart ssh. On AlmaLinux the service is called sshd. Check in a second window that you can still log in before you close your current session.

Troubleshooting

  • The server still asks for a password: check that the public key is in ~/.ssh/authorized_keys and that the permissions are correct with chmod 700 ~/.ssh and chmod 600 ~/.ssh/authorized_keys.
  • Permission denied (publickey): you are probably using a different key or user. Specify the key explicitly with ssh -i ~/.ssh/id_ed25519 root@JOUW-IP.
  • Locked out: via the noVNC console in the client area you can always reach your VPS and restore the setting.

Related articles

Table of Contents