MEHDI.
RETURN_TO_INDEX

SSH Keys Explained: From Generation to Deployment

3 min read
#Security#DevOps#SSH#Linux

Introduction

As a developer, I have come to realize the importance of SSH keys in securely accessing and managing servers. In this article, I will explain the basics of SSH keys, their types, generation, and deployment.

What are SSH Keys?

SSH keys are used to authenticate a user when connecting to a server using the Secure Shell (SSH) protocol. They provide a more secure way of accessing servers compared to traditional password authentication.

Types of SSH Keys

There are two main types of SSH keys: RSA and Ed25519.

  • RSA keys are the traditional and most widely supported type of SSH key. They are available in various key sizes, with 2048 bits being the minimum recommended size.
  • Ed25519 keys are a more recent and secure type of SSH key. They offer better performance and are less prone to certain types of attacks.

Generating SSH Keys

To generate an SSH key pair, you can use the ssh-keygen command. For example, to generate a 2048-bit RSA key, you can use the following command:

ssh-keygen -t rsa -b 2048

To generate an Ed25519 key, you can use the following command:

ssh-keygen -t ed25519

By default, the generated keys will be stored in the ~/.ssh directory.

Adding SSH Keys to the SSH Agent

The SSH agent is a program that runs in the background and manages your SSH keys. To add your SSH key to the SSH agent, you can use the ssh-add command:

ssh-add ~/.ssh/id_rsa

Replace id_rsa with the name of your SSH key file.

Deploying SSH Keys to Servers

To deploy your SSH key to a server, you need to copy the public key to the server's ~/.ssh/authorized_keys file. You can do this using the ssh-copy-id command:

ssh-copy-id user@server

Replace user with your username on the server and server with the server's hostname or IP address.

Common Permission Issues

One common issue when working with SSH keys is permission errors. On Windows, the ~/.ssh directory and its contents should have the correct permissions to prevent errors. You can set the correct permissions using the following command:

icacls ~/.ssh /reset

On Linux and macOS, you can use the chmod command to set the correct permissions:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa

Practical Takeaways

  • Use Ed25519 keys for better security and performance.
  • Always generate a passphrase when generating an SSH key.
  • Use the ssh-add command to add your SSH key to the SSH agent.
  • Use the ssh-copy-id command to deploy your SSH key to a server.
  • Check the permissions of the ~/.ssh directory and its contents to prevent errors.