Bijay Das logo

How to set up SSH keys

2 min read
How to set up SSH keys

SSH keys offer a secure and convenient way to authenticate and access remote servers without the need for passwords. In this guide, we'll walk through the process of setting up SSH keys on a local machine, emphasizing the importance of secure file permissions.

Step 1: Generate SSH Key Pair

Open your terminal and run the following command to generate a new SSH key pair:

ssh-keygen -t rsa -b 4096 -C "your_email@domain.com"

This command creates a new RSA key pair with a specified email address as a comment.

Step 2: Choose Key File Location

You will be prompted to enter a file to save the new key pair. Press Enter to accept the default location (~/.ssh/id_rsa) or specify a different path.

Step 3: Create a Strong Passphrase

You can choose to create a passphrase for added security. Although optional, it's highly recommended. Enter a strong passphrase when prompted.

Step 4: Verify Key Generation

Confirm that the key generation was successful by navigating to the .ssh directory and listing the files:

cd ~/.ssh ls -l

Ensure that the private key (id_rsa) has the correct permissions. Run the following command if needed:

chmod 600 id_rsa

Step 5: Copy Public Key to Remote Server

Assuming you want to add the key to a remote server, use the following command to copy the public key to the server:

ssh-copy-id username@remote_host

Replace username with your remote username and remote_host with the IP address or domain of the remote server. Enter your user password when prompted.

Step 6: Test SSH Connection

Now, you should be able to log in to the remote server without a password:

ssh username@remote_host

If everything is set up correctly, you should be logged in without entering a password.

Optional: Use SSH Agent

To enhance security and convenience, you can use an SSH agent to manage your keys. Run the following commands:

eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_rsa

The first command starts the SSH agent, and the second command adds your private key to the agent.

Conclusion

Congratulations! You've successfully set up SSH keys for secure and passwordless authentication, with special attention to file permissions. Always ensure that your private key has the correct permissions (e.g., 600) to maintain a secure environment. Regularly update your keys and follow best practices for SSH security.