SSH key authentication uses asymmetric encryption technology to authenticate using public and private key pairs, which is more secure and convenient than password authentication.
Key Pair Generation
Use the ssh-keygen command to generate key pairs:
bash# Generate RSA key (default) ssh-keygen -t rsa -b 4096 # Generate ED25519 key (recommended, more secure and efficient) ssh-keygen -t ed25519 # Specify filename and comment ssh-keygen -t ed25519 -f ~/.ssh/my_key -C "user@example.com"
Key Pair Components
- Private Key: Must be kept secret, typically stored in
~/.ssh/id_rsaor~/.ssh/id_ed25519 - Public Key: Can be public, typically stored in
~/.ssh/id_rsa.pubor~/.ssh/id_ed25519.pub
Configuration Steps
- Generate key pair: Run
ssh-keygenon the client - Copy public key to server:
bash
# Method 1: Use ssh-copy-id ssh-copy-id user@hostname # Method 2: Manual copy cat ~/.ssh/id_ed25519.pub | ssh user@hostname "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys" - Set permissions:
bash
chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys
Advantages
- Higher Security: Private keys are hard to crack, no password transmission needed
- Convenience: No need to enter password each time, supports automation scripts
- Multi-factor Authentication: Can be used with passphrase
- Fine-grained Control: Can restrict commands, IPs, etc. in
authorized_keys
Configuration Example
You can set restrictions in ~/.ssh/authorized_keys:
bash# Restrict to specific command only command="echo 'Hello'" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... # Restrict source IP from="192.168.1.0/24" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... # Disable port forwarding no-port-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI...
Best Practices
- Use ED25519 or RSA 4096-bit keys
- Set strong passphrase for private keys
- Rotate keys regularly
- Use SSH agent (ssh-agent) to manage keys
- Disable password authentication on servers, use key authentication only