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

What is the principle and configuration method of SSH public key authentication?

2月19日 19:31

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

  1. 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
  2. Authentication Process:

    • Client initiates connection request to server
    • Server checks if client's public key exists in ~/.ssh/authorized_keys file
    • 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

AlgorithmKey LengthSecurityPerformanceCompatibility
RSA2048/4096HighMediumBest
ECDSA256/384HighFastGood
Ed25519256Very HighFastestNewer

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

  1. Private Key Protection:

    • Set strong passphrase
    • Set correct file permissions (600)
    • Do not share private keys across multiple devices
  2. Server Configuration:

    • Disable password authentication: PasswordAuthentication no
    • Disable root login: PermitRootLogin no
    • Restrict login users: AllowUsers username
  3. 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.

标签:SSH