Generate SSH Keys for Secure Linux Access
This guide explains how to create and configure an SSH key pair to establish secure, passwordless authentication for a Linux server. By generating a private and public cryptographic key pair on your local system, transferring the public key to the remote Linux host, and verifying the connection, you can significantly enhance your server's security posture over traditional password-based logins.
Step 1: Generate the Key Pair Locally
Open a terminal on your local computer. The recommended modern algorithm is Ed25519, which provides better security and performance than legacy algorithms. Run the following command:
ssh-keygen -t ed25519 -C "your_email@example.com"If your environment does not support Ed25519, use a 4096-bit RSA key instead:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"Step 2: Save the Key and Set a Passphrase
The prompt will ask where to save the key file. Press
Enter to accept the default file location
(~/.ssh/id_ed25519 or ~/.ssh/id_rsa).
Next, you will be prompted to enter a passphrase. Adding a passphrase is recommended, as it encrypts the private key on your local disk. Enter a secure passphrase, or press Enter twice to leave it empty for automated, completely passwordless access.
Once finished, the tool generates two files in your
~/.ssh/ directory:
id_ed25519(Private key: Keep this secure and never share it)id_ed25519.pub(Public key: This goes to your remote Linux server)
Step 3: Copy the Public Key to the Remote Server
To authorize your key on the target Linux system, append your public
key to the remote user's ~/.ssh/authorized_keys file.
The fastest method is using the ssh-copy-id command:
ssh-copy-id username@remote_hostReplace username with your remote Linux user account and
remote_host with the server's IP address or domain name.
Enter the remote user's current password when prompted.
If ssh-copy-id is unavailable on your system, pipe the
key over SSH directly:
cat ~/.ssh/id_ed25519.pub | ssh username@remote_host "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"Step 4: Test Your Key-Based Authentication
Verify that the key works by initiating an SSH session:
ssh username@remote_hostIf configured correctly, the server will authenticate you using the SSH key. If you protected the private key with a passphrase, enter it when prompted; you will not be asked for the Linux user account password.
Step 5: Disable Password Authentication (Optional)
To maximize security, disable password authentication on the Linux server so that only key-based access is permitted.
- Log into your server and open the SSH daemon configuration file:
sudo nano /etc/ssh/sshd_config - Locate the
PasswordAuthenticationline and change it to:PasswordAuthentication no - Save the file and restart the SSH service:
sudo systemctl restart sshd