What is SSH Key Authentication?
SSH key authentication replaces password-based login with a cryptographic key pair. It's more secure and enables passwordless automation.
How It Works
- You generate a key pair — a private key (stays on your machine) and a public key (goes on the server)
- When connecting, your SSH client proves it holds the private key
- The server checks the corresponding public key in
~/.ssh/authorized_keys
Tip SSH keys are significantly more secure than passwords — they can't be brute-forced and are immune to credential stuffing attacks.
Generating a Key Pair
# Ed25519 (recommended — fast, secure, compact)
ssh-keygen -t ed25519 -C "your@email.com"
# RSA 4096 (wider compatibility)
ssh-keygen -t rsa -b 4096 -C "your@email.com"
You'll be asked for a file location and optional passphrase:
| Option | Default | Recommendation |
|---|---|---|
| File | ~/.ssh/id_ed25519 |
Use default unless managing multiple keys |
| Passphrase | None | Always set one for production keys |
Copying Your Key to a Server
# Automatic method
ssh-copy-id user@your-server-ip
# Manual method
cat ~/.ssh/id_ed25519.pub | ssh user@your-server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Verifying It Works
ssh user@your-server-ip
# Should connect without asking for a password
Disabling Password Authentication
Once keys work, harden your server:
sudo nano /etc/ssh/sshd_config
Set these values:
PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no
Then restart SSH:
sudo systemctl restart sshd
Warning Always keep an active SSH session open while changing SSH config. If something goes wrong, you can fix it without being locked out.
Managing Multiple Keys
Use ~/.ssh/config to associate keys with hosts:
Host production
HostName 198.51.100.10
User deploy
IdentityFile ~/.ssh/id_prod
Host staging
HostName 198.51.100.20
User deploy
IdentityFile ~/.ssh/id_staging