乐闻世界logo
搜索文章和话题

How to configure SSH key authentication? What are the advantages of key authentication over password authentication?

3月6日 23:38

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_rsa or ~/.ssh/id_ed25519
  • Public Key: Can be public, typically stored in ~/.ssh/id_rsa.pub or ~/.ssh/id_ed25519.pub

Configuration Steps

  1. Generate key pair: Run ssh-keygen on the client
  2. 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"
  3. Set permissions:
    bash
    chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys

Advantages

  1. Higher Security: Private keys are hard to crack, no password transmission needed
  2. Convenience: No need to enter password each time, supports automation scripts
  3. Multi-factor Authentication: Can be used with passphrase
  4. 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
标签:SSH