How to Solve Permission Denied Publickey Error When Using Git

Git is a distributed version control system that is widely used for managing and maintaining codebases.

Despite its popularity and user-friendly interface, it can be challenging to work with at times, especially when faced with errors.

One such error that users often encounter is the “Permission Denied Publickey Error”.

In this tutorial, we will discuss the cause of this error and provide step-by-step instructions on how to solve it.


What is the “Permission Denied Publickey Error”?

This error message occurs when a user tries to access a remote Git repository using SSH (secure shell) and the server rejects the connection due to an incorrect or invalid SSH key.

In simple terms, the error means that the server doesn’t recognize the public key of the user trying to access the repository, hence denying permission to connect.

Why does the “Permission Denied Publickey Error” occur?

There are several reasons why this error occurs, including:

  • Incorrect SSH Key: The most common cause of this error is the use of an incorrect or invalid SSH key. The public key must match the private key stored on the server to establish a secure connection.
  • SSH Key not registered on the server: If the public key is not registered on the server, the connection will be rejected.
  • Misconfigured Git repository: If the repository is misconfigured, it may result in the error message.

How to Solve the “Permission Denied Publickey Error”

Here are the steps to resolve this error:

  1. Check the SSH Key: The first step is to check that the correct public key is being used to connect to the Git repository. You can use the following command to list the SSH keys in your ~/.ssh directory:
$ ls ~/.ssh
  1. Generate a new SSH Key: If the public key is incorrect, you can generate a new one using the following command:
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
  1. Register the SSH Key on the Server: Once you have generated the SSH key, you need to register it on the server. You can use the following command to copy the key to the clipboard:
$ clip < ~/.ssh/id_rsa.pub
  1. Add the Key to the Git Repository: Finally, add the key to the Git repository by going to the repository’s settings and selecting the “SSH and GPG keys” option.
  2. Test the Connection: Once you have completed all the steps, test the connection by running the following command:
$ ssh -T [email protected]

If the connection is successful, you will see a message similar to the following:

Hi username! You've successfully authenticated, but GitHub does not provide shell access.

Conclusion

The “Permission Denied Publickey Error” is a common issue that users face when using Git.

However, it is relatively easy to solve by following the steps outlined in this tutorial.

If you still face the error, it is recommended to check the server logs for more information.