SSH (Secure Shell) relies on public-key cryptography for secure logins. But how can you be sure your public and private key pair are actually linked? This blog post will guide you through a simple method to verify their authenticity in Linux and macOS.

Understanding the Key Pair:

Imagine a lock and key. Your public key acts like the widely distributed lock – anyone can see it. The private key is the unique counterpart, kept secret, that unlocks the metaphorical door (your server) for SSH access.

Using ssh-keygen

This method leverages the ssh-keygen tool, already available on most Linux and macOS systems.

1. Locate the keys :Open a terminal and use cd to navigate to the directory where your private key resides (e.g., cd ~/.ssh).
2. Use the command ‘ls -al’ to list all files in the directory, and locate your private/public keypair you wish to check.

Example:

ababwaha@ababwaha-mac .ssh % ls -al
total 32
drwx------   6 ababwaha  staff   192 Jun 24 16:04 .
drwxr-x---+ 68 ababwaha  staff  2176 Jun 24 16:04 ..
-rw-------   1 ababwaha  staff   411 Jun 24 16:04 id_ed25519 
-rw-r--r--   1 ababwaha  staff   103 Jun 24 16:04 id_ed25519.pub    
-rw-------   1 ababwaha  staff  3389 Jun 24 16:04 id_rsa            
-rw-r--r--   1 ababwaha  staff   747 Jun 24 16:04 id_rsa.pub        

3. Verify the Key Pair: Run the following command, replacing with the actual path to your private key file (e.g., ssh-keygen -lf ~/.ssh/id_rsa):

ssh-keygen -lf ssh-keygen -lf

This command displays fingerprint information about your key pair.

ababwaha@ababwaha-mac .ssh % ssh-keygen -l -f id_rsa
4096 SHA256:7qXL09ejiSkrKs8HfhEo8EXkUVFOsoPfv52QY/l/kzg ababwaha@ababwaha-mac (RSA)
ababwaha@ababwaha-mac .ssh % ssh-keygen -l -f id_rsa.pub 
4096 SHA256:7qXL09ejiSkrKs8HfhEo8EXkUVFOsoPfv52QY/l/kzg ababwaha@ababwaha-mac (RSA)
ababwaha@ababwaha-mac .ssh % 
ababwaha@ababwaha-mac .ssh % 
ababwaha@ababwaha-mac .ssh % 
ababwaha@ababwaha-mac .ssh % ssh-keygen -l -f id_ed25519
256 SHA256:4pWu5rdA1IvbbjD7/k4/k/7A4X6kft28MpKL1HMqmgQ ababwaha@ababwaha-mac (ED25519)
ababwaha@ababwaha-mac .ssh % ssh-keygen -l -f id_ed25519.pub 
256 SHA256:4pWu5rdA1IvbbjD7/k4/k/7A4X6kft28MpKL1HMqmgQ ababwaha@ababwaha-mac (ED25519)
ababwaha@ababwaha-mac .ssh % 

4. Match the Fingerprints: Compare the fingerprint displayed by ssh-keygen with the beginning of the text in your public key file. If they match, congratulations! Your public and private keys are a verified pair.

Remember:

  • Security: Always keep your private key secure. Avoid storing it on publicly accessible locations.
  • Permissions: Ensure your private key file has appropriate permissions (usually 600) to prevent unauthorized access.

    By following this method, you can easily verify the authenticity of your public and private SSH key pair, ensuring a secure connection to your server.