Securitybeginner8 min read

SSH Key Authentication

Set up SSH key-based authentication. Generate key pairs, configure servers, manage multiple keys, and harden your SSH setup.

How SSH Key Authentication Works

SSH key authentication uses a pair of cryptographic keys instead of passwords:

  • Private key — stays on your machine, never shared. This is your identity.
  • Public key — placed on servers you want to access. Anyone can have it.

When you connect, the server sends a challenge encrypted with your public key. Only your private key can decrypt it, proving your identity without transmitting a password.

Generating a Key Pair

Use Ed25519 — it's faster and more secure than RSA for new keys:

# Generate an Ed25519 key (recommended)
ssh-keygen -t ed25519 -C "walid@devforge"

# If you need RSA compatibility (older systems)
ssh-keygen -t rsa -b 4096 -C "walid@devforge"

# Keys are saved to:
# ~/.ssh/id_ed25519       (private — never share)
# ~/.ssh/id_ed25519.pub   (public — copy to servers)

Deploying Your Public Key

Copy your public key to the remote server:

# Easiest method
ssh-copy-id user@server.example.com

# Manual method
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# Fix permissions (required for SSH to accept the key)
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

Managing Multiple Keys with SSH Config

Use ~/.ssh/config to manage different keys for different hosts:

# ~/.ssh/config
Host github
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_github

Host production
    HostName 10.0.1.50
    User deploy
    IdentityFile ~/.ssh/id_ed25519_prod
    Port 2222

Host staging
    HostName 10.0.1.51
    User deploy
    IdentityFile ~/.ssh/id_ed25519_prod

Related Tutorials