How to Create an SSH Key in Linux Using ssh-keygen

When you connect to a remote Linux server via SSH, you typically use a password. However, typing complex passwords every time you log in is tedious, and relying purely on passwords leaves your server vulnerable to brute-force hacking attacks.

The industry standard for secure server authentication is using an SSH Key Pair. This acts like a digital lock and key: you place the public lock on the server, and you keep the private key safely on your personal computer.

Here is how to generate a brand new SSH key pair using the ssh-keygen command.

How to Generate the SSH Key

You must run this command on your local personal computer (the one you are sitting in front of), not on the remote server.

  1. Open your Terminal.
  2. Type the following command and press Enter:
    ssh-keygen -t rsa -b 4096

Breaking down the command:

  • -t rsa: Tells the system to use the RSA cryptographic algorithm (the most universally supported standard).
  • -b 4096: Tells the system to make the key 4096 bits long, which is incredibly secure and virtually uncrackable by modern computers.

Answering the Prompts

After hitting enter, the terminal will ask you a series of questions.

1. “Enter file in which to save the key:”
The system will suggest a default hidden folder, usually /home/username/.ssh/id_rsa. Unless you are managing dozens of different keys, just press Enter to accept the default location.

2. “Enter passphrase (empty for no passphrase):”
This is an optional extra layer of security. If you add a passphrase, your computer will ask you for it every time you try to use the key. If your laptop is stolen, the thief cannot use your SSH key without this phrase. Type a passphrase and press Enter, or simply leave it blank and press Enter for automatic logins.

3. “Enter same passphrase again:”
Confirm your choice by pressing Enter.

The system will instantly generate your keys and print a strange-looking \”randomart image\” to the screen confirming the process is complete.

What Did the Command Do?

The ssh-keygen command created two distinct files in your hidden .ssh folder:

  • id_rsa (Your Private Key): This is your secret digital identity. NEVER share this file, upload it to GitHub, or give it to anyone. Keep it secure on your computer.
  • id_rsa.pub (Your Public Key): This is the file you must copy and paste onto the remote servers you want to log into. When the server sees you trying to connect, it will check if your private key mathematically matches this public key before letting you in.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.