SSH public key authentication is a more secure and convenient identity verification method than password authentication. It is based on asymmetric encryption technology, using a pair of keys (public key and private key) for authentication.
Public Key Authentication Principle
-
Key Pair Generation: Client generates a pair of keys
- Private key: Stored locally on the client, must be kept strictly confidential
- Public key: Uploaded to the server, can be shared publicly
-
Authentication Process:
- Client initiates connection request to server
- Server checks if client's public key exists in
~/.ssh/authorized_keysfile - If public key exists, server generates a random challenge string
- Client signs the challenge string using private key
- Server verifies signature using corresponding public key
- After verification passes, authentication succeeds
Key Type Comparison
| Algorithm | Key Length | Security | Performance | Compatibility |
|---|---|---|---|---|
| RSA | 2048/4096 | High | Medium | Best |
| ECDSA | 256/384 | High | Fast | Good |
| Ed25519 | 256 | Very High | Fastest | Newer |
Generating SSH Keys
bash# Generate RSA key ssh-keygen -t rsa -b 4096 -C "your_email@example.com" # Generate Ed25519 key (recommended) ssh-keygen -t ed25519 -C "your_email@example.com"
Configuring Public Key Authentication
bash# Copy public key to server ssh-copy-id user@hostname # Or manually copy cat ~/.ssh/id_rsa.pub | ssh user@hostname "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Security Best Practices
-
Private Key Protection:
- Set strong passphrase
- Set correct file permissions (600)
- Do not share private keys across multiple devices
-
Server Configuration:
- Disable password authentication:
PasswordAuthentication no - Disable root login:
PermitRootLogin no - Restrict login users:
AllowUsers username
- Disable password authentication:
-
Key Management:
- Regularly rotate keys
- Use different key pairs for different servers
- Revoke unused public keys promptly
Advantages
- Security: Private keys are not transmitted over the network, difficult to steal
- Convenience: No need to enter password every time
- Automation: Easy to use in scripts and automation tools
- Auditability: Can track which key logged in at what time
Public key authentication has become the standard practice for modern server management, especially suitable for DevOps and automated operations scenarios.