Post

ssh-keygen: Connecting to a server with ease and security

Let me explain how to connect via SSH using a private key.

ssh-keygen: Connecting to a server with ease and security

0. Version

SSH Client: MacOS sequoia 15.3.1
SSH Server: Ubuntu 24.04
OpenSSH_9.8p1

1. Generate a new user to login (Optional)

Server

Generate a new user named alice

1
sudo adduser alice

Screenshot: Creating a new user Creating a new user with sudo privileges

If you want to delete the user and the user’s home directory, run the following command:

1
sudo deluser --remove-home alice

If you want to see users who can connect via SSH, run the following command:

1
sudo awk -F: '$3 >= 1000 && $7 != "/usr/sbin/nologin" && $7 != "/bin/false" {print $1}' /etc/passwd

2. Make a public key and a private key.

Client

1
2
# -t: key type (ed25519), -C: comment/description
ssh-keygen -t ed25519 -C "your_command"

Screenshot: Generating SSH keys Generating a new SSH key pair using ED25519 algorithm

ssh-keygen docs


Your private key should not be exposed to others!!!

Keys may be created under the folder you designated I deleted these keys before posting (your_key_name: private key, your_key_name.pub: public key.)

These keys are only used for demonstration purposes and have been deleted.

Public-key cryptography

3. Copy the public key to the server

There are two ways to copy. Choose the one you prefer.

3-1. Using ssh-copy-id

Client

Use the following command to copy your public key to the server in one command:

1
ssh-copy-id -i ~/.ssh/your_key_name.pub -p 22 user@your.server.ip 

3-2. Manual Method

Client

1
cat ~/.ssh/your_key_name.pub | ssh -p 22 user@your.server.ip 'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'

4. Verify connecting to a server using a private key

Client

The system will first attempt to authenticate using your private key before requesting a password.

1
ssh -p 22 user@your.server.ip

Screenshot: SSH connection without password Successfully connected to the server using SSH key authentication

5. Disable password authentication (Optional)

Server

To enhance security, you can disable password authentication and allow only key-based authentication. Edit the SSH configuration file:

1
sudo nano /etc/ssh/sshd_config

Find and modify these lines:

1
2
3
4
5
6
# Disable password authentication
PasswordAuthentication no
# Disable root login
PermitRootLogin no
# Enable public key authentication
PubkeyAuthentication yes

After making changes, restart the SSH service:

1
2
3
4
5
# Restart the service
sudo systemctl restart sshd

# Verify the service status
sudo systemctl status sshd

Make sure you have successfully set up key-based authentication before disabling password authentication. Otherwise, you might get locked out of your server.

This post is licensed under CC BY 4.0 by the author.