How to Use Public Key Authentication with SSH
Posted on
TABLE OF CONTENTS
- Understanding SSH Keys vs. Password Security
- Prerequisites
- Step 1: Generate an SSH Key Pair Locally
- Step 2: Copy the Public Key to Your Remote Server
- Step 3: Verify the Key Authentication Pipeline
- Step 4: Disable Legacy Password Authentication
- Configuring SSH Public Keys on Windows Operating Systems
- Defensive Infrastructure Best Practices
- Commands Reference Summary
SSH public key authentication replaces traditional password logins with cryptographic key pairs. This method shifts your server security from easily guessable or brute-forced strings to asymmetrical encryption. By verifying connections using math rather than static credentials, you systematically eliminate automated password spraying attacks and simplify secure automation workflows across infrastructure.
Quick Answer: The 4-Command Setup
For users who need to establish a connection immediately, run these four commands sequentially:
# 1. Generate a modern secure key pair locally
ssh-keygen -t ed25519 -C "your_email@example.com"
# 2. Export the public key to the remote server
ssh-copy-id username@server_ip
# 3. Establish the secure cryptographic connection
ssh username@server_ip
# 4. Enforce key-only authentication (inside /etc/ssh/sshd_config)
PasswordAuthentication no
The mechanism functions via asymmetric cryptography. You generate two matching digital files: a private key (kept strictly confidential on your local system) and a public key (uploaded onto the target server). The server grants shell access only when a challenge phrase encrypted by the public key is deciphered successfully by the corresponding local private key.
Understanding SSH Keys vs. Password Security
Relying on traditional passwords introduces structural vulnerabilities to internet-exposed servers. Automated bots crawl public IP blocks constantly, executing thousands of concurrent dictionary attacks. Below is a comparative breakdown of how key authentication changes server exposure:
| Security Vector | Password Authentication | SSH Public Key Authentication |
| Brute-Force Resistance | Vulnerable to dictionary attacks and distributed botnets. | Virtually immune; keys use 256-bit or greater complexity. |
| Operational Efficiency | Requires manual interactive password input for each session. | Enables seamless passwordless execution via active agents. |
| Credential Exposure | Credentials can be intercepted via memory dumps or keyboard logging. | The private key never leaves the origin hardware platform. |
| Automation Readiness | Hardcoding passwords into bash or Ansible scripts is insecure. | Natively compatible with safe continuous integration workflows. |
Prerequisites
Ensure the following foundational environments are in place before continuing:
- An active SSH client on your terminal (native on OpenSSH-supported engines).
- A remote server running a Linux distribution (e.g., Ubuntu, Debian, Rocky Linux, CentOS).
- A valid non-root or root user profile on that remote infrastructure.
Step 1: Generate an SSH Key Pair Locally
Modern security standards prioritize the Ed25519 algorithm over legacy RSA due to its superior performance, smaller file size, and resistance to known cryptographic side-channel attacks.
Open your local terminal shell and execute the initialization script:
ssh-keygen -t ed25519 -C "your_email@example.com"
The console tool will prompt for structural inputs:
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/user/.ssh/id_ed25519):
Press Enter to preserve the default pathing structure. Next, the wizard will ask for a passphrase:
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Security Note: Omitting a passphrase allows automated configurations to run scripts without human intervention. However, assigning a passphrase encrypts the key file on your local storage, meaning an attacker cannot use your key even if they clone your local hard drive.
Step 2: Copy the Public Key to Your Remote Server
Choose one of the two following methods to map your public identity file onto the target server environment.
Method A: Automated Deployment via ssh-copy-id (Recommended)
If your local workstation includes the OpenSSH toolkit utility, run the deployment utility directly:
ssh-copy-id username@remote_server_ip
The utility scans your local directories for id_ed25519.pub, connects via the server’s current password configuration, and appends the line into the appropriate file profile automatically.
Method B: Manual Public Key Append Setup
If automated utilities are missing or administrative firewall parameters block automated setups, manually append the key file:
- Output the plaintext string of the local public key data:
cat ~/.ssh/id_ed25519.pub
Copy the output stream starting with ssh-ed25519… precisely.
- Connect to your server using temporary credentials and configure the base directories:
# Create the hidden folder if it does not exist
mkdir -p ~/.ssh
# Enforce exclusive user read/write access
chmod 700 ~/.ssh
- Edit the key registration system file via nano or text editor:
nano ~/.ssh/authorized_keys
Paste the exact key content string on a brand-new line. Save the file and exit the editor.
- Secure the authorized keys file configuration permissions tightly:
chmod 600 ~/.ssh/authorized_keys
Step 3: Verify the Key Authentication Pipeline
Before closing out active management terminals, establish a brand new concurrent terminal session to ensure the key exchange passes successfully:
ssh username@remote_server_ip
If an encrypted passphrase was mapped during Step 1, the operating system prompts you for that phrase entry. If no passphrase was specified, the shell should immediately open to the server prompt without asking for the account password.
Step 4: Disable Legacy Password Authentication
Once you verify that key-based logins work perfectly, lock down the server daemon config to drop standard user password validation entirely.
- Open the SSH engine system daemon file:
sudo nano /etc/ssh/sshd_config
- Locate the following parameters, uncomment them if needed, and change the flags to match exactly:
Plaintext
PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no
- Cycle the system service controller to immediately apply configuration logic:
# For Ubuntu / Debian Families
sudo systemctl restart ssh
# For CentOS / RHEL / Rocky Linux Families
sudo systemctl restart sshd
Warning: Do not terminate your existing terminal window until you have successfully opened a completely separate terminal window and verified that you can still log in via your SSH key. This prevents accidental lockouts.
Configuring SSH Public Keys on Windows Operating Systems
Windows 10 and 11 environments include native OpenSSH client infrastructure embedded inside PowerShell.
- Launch a PowerShell window and run the standard key generation routine:
ssh-keygen -t ed25519
The tracking files will save cleanly to your user profiles folder location: C:\Users\YourUsername\.ssh\id_ed25519 (Private) and id_ed25519.pub (Public).
- To connect via PuTTY instead, load your generated private key into PuTTYgen, click “Convert”, and save it as a native .ppk file format required by older legacy client wrappers.
Defensive Infrastructure Best Practices
- Enforce Key Rotation: Re-generate primary system keys every 12 to 24 months to minimize long-term exposure.
- Utilize SSH Agents: Execute ssh-add to securely hold decrypted keys in system memory, avoiding re-typing passphrases during your active session.
- Audit Authorized Lists regularly: Inspect ~/.ssh/authorized_keys files periodically to remove obsolete workstation accounts.
Commands Reference Summary
| Target Command Syntax | Core Infrastructure Operational Objective |
| ssh-keygen -t ed25519 -C “tag” | Initializes a new asymmetric cryptographic key pair using the Ed25519 protocol. |
| ssh-copy-id username@server_ip | Safely appends local public key files directly into the target environment asset system. |
| chmod 700 ~/.ssh | Secures the vital root configuration folder to restrict read/write access to the owner only. |
| chmod 600 ~/.ssh/authorized_keys | Locks configuration identities to prevent unauthorized users from editing access rights. |
| sudo systemctl restart ssh | Forces the active SSH daemon to apply modifications made inside sshd_config. |
HAVE A QUESTION OR WANT TO GET A CUSTOM SOLUTION?
CONTACT SALESFAQs
The public key is stored on the server and can be shared. The private key remains on your device and should never be shared.
For most modern deployments yes. Ed25519 generates smaller keys and provides strong security.
Yes. Windows supports OpenSSH and tools like PuTTY.
Yes. Different keys can be used for different servers or projects.
Yes, after confirming key authentication works correctly.
Typically in ~/.ssh/ on Linux and macOS or C:\Users\username\.ssh\ on Windows.
SSH keys do not expire automatically, but periodic rotation is recommended.