Why use an SSH key?
When connecting to a Linux server, we often use SSH (Secure Shell). By default, SSH allows login with a password — but this is not secure.
The best practice is to use an SSH key, a kind of digital password that is much harder to guess or break.
1. Generate an SSH key pair
On your local computer, open a terminal and run:
ssh-keygen -t rsa -b 4096 -C "your.email@example.com"
Explanation:
-t rsa→ key type (RSA here, 4096 bits)-b 4096→ key length, the longer, the more secure-C→ optional comment
Just press Enter to accept the default file location:
Enter file in which to save the key (/home/you/.ssh/id_rsa):
Then enter an optional passphrase (don’t forget it!)
This will create two files:
id_rsa→ private key (never share this)id_rsa.pub→ public key (copy this to the server)
2. Copy the public key to the server
Use this command:
ssh-copy-id user@server_ip_address
The system will:
- connect using your current password,
- copy your public key to the
~/.ssh/authorized_keysfile on the server.
✅ You can now log in without a password:
ssh user@server_ip_address
3. Disable password authentication
Once your key-based login works, disable password login to prevent brute-force attacks.
On the server, open the SSH config file:
sudo nano /etc/ssh/sshd_config
Edit or add these lines:
PasswordAuthentication no
PermitRootLogin no
💡 You can also use
PermitRootLogin prohibit-passwordif you want to allow root access by SSH key only.
Then restart the SSH service:
# Debian/Ubuntu
sudo systemctl restart ssh
# Red Hat/CentOS/Rocky
sudo systemctl restart sshd
4. Test the connection
Before closing your current terminal, open a new SSH session to verify everything is working.
If you connect successfully, your key setup is correct ✅
5. Bonus: Protect your private key
Your private key (~/.ssh/id_rsa) must remain secret.
Best practices:
- Use a passphrase when generating it
- Never send it by email
- Never upload it to Git repositories
Summary
| Step | Command or Action |
|---|---|
| Generate SSH key | ssh-keygen |
| Copy public key to the server | ssh-copy-id user@ip |
| Disable password login | PasswordAuthentication no |
| Restart SSH | systemctl restart ssh or sshd |
| Test connection | ssh user@ip |
🔐 Your server is now much more secure against attacks! Don’t hesitate to include this setup in your future deployments.