TL;DR
This guide shows you how to use SSH keys for secure file access instead of passwords. It’s more secure and easier in the long run.
What are SSH Keys?
SSH (Secure Shell) keys let you log into a server or access files without typing your password every time. They work with a pair of keys: a private key (keep this secret!) and a public key (you share this).
Step 1: Generate an SSH Key Pair
- Open your terminal. This is where you’ll type commands.
- Run the following command:
ssh-keygen -t rsa -b 4096This creates a new RSA key pair with a strong 4096-bit length.
- Follow the prompts:
- Enter file in which to save the key (/home/your_user/.ssh/id_rsa): Press Enter to accept the default location (recommended).
- Enter passphrase (empty for no passphrase): It’s highly recommended to set a strong passphrase. This adds an extra layer of security even if your private key is stolen. Type it in and press Enter twice to confirm.
This will create two files in the ~/.ssh/ directory:
- id_rsa: Your private key – keep this safe!
- id_rsa.pub: Your public key – you’ll share this with the server.
Step 2: Copy your Public Key to the Server
There are several ways to do this. We’ll use ssh-copy-id, which is the easiest if it’s available.
- Use ssh-copy-id:
ssh-copy-id user@server_addressReplace
userwith your username on the server andserver_addresswith the server’s IP address or hostname. You’ll be prompted for your password one last time. - If ssh-copy-id isn’t available:
- Display your public key:
cat ~/.ssh/id_rsa.pub - Copy the entire output of this command.
- Log into the server using your password.
- Edit the
~/.ssh/authorized_keysfile: If it doesn’t exist, create it.nano ~/.ssh/authorized_keys - Paste your public key into this file. Make sure it’s on a single line and there are no extra spaces or characters.
- Save the file and exit the editor.
- Display your public key:
Step 3: Test your SSH Key Login
- Open a new terminal window.
- Try to log into the server:
ssh user@server_addressReplace
userandserver_addressas before. - If you set a passphrase, you’ll be prompted for it. If everything is configured correctly, you should log in without being asked for your password!
Step 4: Disable Password Authentication (Optional but Recommended)
To further improve security, disable password authentication on the server.
- Log into the server using SSH keys.
- Edit the SSH configuration file:
sudo nano /etc/ssh/sshd_config - Find these lines and change them as follows:
PasswordAuthentication noChallengeResponseAuthentication no(if present, set to ‘no’)
- Save the file and exit the editor.
- Restart the SSH service:
sudo systemctl restart sshd
Warning: Make sure you can log in with SSH keys before disabling password authentication. Otherwise, you might lock yourself out of your server!