How to Add a Public Key to authorized_keys
In the realm of secure remote access, SSH (Secure Shell) stands as a cornerstone technology. It provides a secure way to access and manage remote servers. One of the key aspects of SSH is the use of public and private key pairs for authentication. This article will guide you through the process of adding a public key to the authorized_keys file, which is crucial for granting secure access to your server.
Understanding the authorized_keys File
The authorized_keys file is located in the .ssh directory of a user’s home directory on the server. It contains a list of public keys that are allowed to authenticate and access the server. When a user attempts to connect to the server using SSH, their public key is checked against the entries in the authorized_keys file. If a match is found, access is granted; otherwise, the connection is denied.
Generating SSH Key Pair
Before you can add a public key to the authorized_keys file, you need to generate an SSH key pair. This can be done using the ssh-keygen command. Here’s how to generate a key pair:
1. Open a terminal or command prompt.
2. Run the following command: `ssh-keygen -t rsa -b 4096`
3. Follow the prompts to specify a file location and enter a passphrase (optional).
4. Once the key pair is generated, you will have two files: `id_rsa` (private key) and `id_rsa.pub` (public key).
Adding the Public Key to authorized_keys
Now that you have the public key, you can add it to the authorized_keys file. Here’s how to do it:
1. Log in to the server using SSH.
2. Navigate to the user’s .ssh directory: `cd ~/.ssh`
3. If the authorized_keys file does not exist, create it using the following command: `touch authorized_keys`
4. Open the authorized_keys file in a text editor: `nano authorized_keys`
5. Copy the contents of the id_rsa.pub file and paste it into the authorized_keys file.
6. Save and close the file.
Testing the SSH Connection
To ensure that the public key has been added correctly, test the SSH connection from the client machine. Open a terminal or command prompt on the client machine and run the following command:
“`
ssh username@server_ip
“`
If the connection is successful, you have successfully added the public key to the authorized_keys file and granted secure access to your server.
Conclusion
Adding a public key to the authorized_keys file is a fundamental step in securing SSH access to your server. By following the steps outlined in this article, you can ensure that only authorized users can access your server, thereby protecting your data and maintaining the integrity of your system.