Setting Up SSH Key Authentication and Communication with GitHub

When connecting to an existing GitHub repository, you can use SSH keys (public and private) for authentication. For instructions on how to create an SSH key and add it to GitHub, refer to the official GitHub documentation: https://docs.github.com/cn/authentication/connecting-to-github-with-ssh.

Key steps to note:

  1. You need to create a .ssh folder in your home directory and copy the SSH private key into it. You do not need to copy the public key into this folder. Instead, paste the contents of your public key into the Settings section of your GitHub account by following the steps here: Adding a new SSH key to your GitHub account.
  2. The file name of your SSH private key should be id_rsa, as this is one of the default names git looks for when locating the private key. If the file is named differently, you will encounter an error such as “[email protected]: Permission denied (publickey).” If this happens, rename your private key file to id_rsa.
  3. If you’re using a Linux-based OS like Ubuntu, ensure that no other users can read or write to the private key file. Run the following commands:
chmod o-rwx ./id_rsa
chmod g-rwx ./id_rsa

After completing the setup, you can use the SSH private key in your .ssh folder for authentication and communication with GitHub. To verify the setup, open Git Bash and run the following command:

ssh -T [email protected]

If you see a message like this:

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

It means you’ve successfully set up SSH key authentication with GitHub.

References:

设置通过SSH秘钥与GitHub进行认证和通信

连接GitHub已有的代码仓库时,可以使用SSH秘钥(公私钥)进行认证。如何创建SSH秘钥并将其添加至GitHub,请参考GitHub的帮助文档https://docs.github.com/cn/authentication/connecting-to-github-with-ssh。

需要注意的步骤是:

  • 你需要在家目录里创建.ssh文件夹,把SSH私钥拷贝进去,公钥不用拷贝进去。公钥的内容需要粘贴到你的GitHub账户网站的设置里,请参考https://docs.github.com/cn/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account。
  • SSH私钥的文件名应该是id_rsa,因为id_rsa是git默认查找的私钥名字之一,否则就找不到私钥,会报错“[email protected]: Permission denied (publickey).”。如果你的SSH私钥的文件名不是id_rsa,那么应该改名为id_rsa。
  • 如果你使用的是Ubuntu等Linux操作系统,私钥文件不能有被其他人读写的权限:
chmod o-rwx ./id_rsa
chmod g-rwx ./id_rsa

完成设置后,就可以用家目录里的.ssh文件夹里的SSH私钥与GitHub进行认证和通信了。打开Git Bash,执行命令:

ssh -T [email protected]

如果输出以下信息:

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

说明通过SSH秘钥与GitHub进行认证和通信设置成功。

参考

https://docs.github.com/cn/authentication/connecting-to-github-with-ssh https://docs.github.com/en/authentication/troubleshooting-ssh/error-permission-denied-publickey