SSH key authentication provides stronger security than traditional password authentication by using cryptographic key pairs. This method eliminates brute-force attacks targeting passwords and enables automated secure connections. Major cloud providers like AWS and GitHub recommend this as the default authentication method.
ssh-keygen -t ed25519 -C "your_email@example.com"
# For legacy systems:
# ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
This creates two files in ~/.ssh/:
- id_ed25519 (private key - NEVER share this)
- id_ed25519.pub (public key - this gets deployed)
For a typical Linux server:
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@hostname
# Alternative manual method:
cat ~/.ssh/id_ed25519.pub | ssh user@hostname "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Edit /etc/ssh/sshd_config:
PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
PermitRootLogin without-password
Then restart SSH:
sudo systemctl restart sshd
ssh -T user@hostname
# Should connect without password prompt
For additional security:
# Limit specific keys to specific commands:
command="uptime" ssh-rsa AAAAB3...== user@host
# Add expiration dates:
from="192.168.1.*",expiry-time="20231231" ssh-rsa AAAAB3...==
- Verify file permissions: ~/.ssh should be 700, authorized_keys 600
- Check server auth logs: /var/log/auth.log or /var/log/secure
- Test with verbose mode: ssh -vvv user@hostname
Key-based authentication provides stronger security than passwords by using cryptographic key pairs. It eliminates brute-force attacks and enables automated logins for scripts and CI/CD pipelines.
On your local machine run:
ssh-keygen -t ed25519 -C "your_email@example.com"
For legacy systems, use RSA:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Use ssh-copy-id for the easiest method:
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@your.server.com
Alternatively, manually append your public key:
cat ~/.ssh/id_ed25519.pub | ssh user@host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Edit /etc/ssh/sshd_config:
PubkeyAuthentication yes PasswordAuthentication no ChallengeResponseAuthentication no
Then restart SSH:
sudo systemctl restart sshd
Verify connection works:
ssh -v -i ~/.ssh/id_ed25519 user@host
If connection fails, check permissions:
chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys
For multiple keys, use ~/.ssh/config:
Host myserver
HostName server.example.com
User myuser
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
Enable agent forwarding carefully:
ssh -A user@host