SSH key authentication
You create a pair of keys: a private key that stays on your computer and a public key that you put on the server. When you connect, the server checks that you hold the private key. The key itself never travels over the network.
Pros
- Very hard to guess or brute force.
- No password to type, which is good for scripts and automation.
- Can be protected with a passphrase.
- Easy to remove for a single person (delete one line on the server).
Cons
- You must keep the private key safe. Anyone who has it can log in.
- A little more work for the first setup.
Password authentication
You type a username and a password.
Pros
- Simple, with nothing to set up.
- Works from any computer.
Cons
- Weak or reused passwords can be guessed.
- Servers on the internet get thousands of password-guessing attempts a day.
- Passwords can be stolen with phishing or keyloggers.
Comparison
| SSH key | Password | |
|---|---|---|
| Security | Very high | Depends on the password |
| Brute force | Practically impossible | Possible |
| Convenience | Automatic login | Type each time |
| Setup | A few steps | None |
| Automation | Easy | Hard |
Keys are the better choice for servers.
Set up key authentication
1. Create the key pair on your computer
ssh-keygen -t ed25519 -C "you@example.com"
The keys are saved in ~/.ssh/. Use a passphrase.
2. Copy the public key to the server
ssh-copy-id user@server_ip
3. Test the login
ssh user@server_ip
4. Disable password login on the server
Only after the key login works. Edit /etc/ssh/sshd_config:
PasswordAuthentication no
PubkeyAuthentication yes
Restart SSH:
sudo systemctl restart sshd
Test again from a new terminal before you close the old one.
Use an SSH key
- Make sure you have a key pair (
ls ~/.ssh). - Add the public key to
~/.ssh/authorized_keyson the server. - Connect with your SSH client. To use a specific key:
ssh -i ~/.ssh/id_ed25519 user@server_ip. - If the private key has a passphrase, enter it. Use
ssh-agentto type it only once per session.
Keep keys safe
- Never share the private key.
- Set the right permissions:
chmod 600 ~/.ssh/id_ed25519. - Use a separate key for each computer, and remove old keys from the server.
- Back up the private key in a safe place.
Quick recap
- Use SSH keys for servers and turn off password login.