身份认证

当本地Git仓库与Git远程仓库进行通信的时候,需要通过SSH进行身份认证。

创建SSH Key

打开根目录下的.ssh目录,查看是否已经存在id_ras文件和idras.pub文件,代码如下所示。

  1. ~ cd .ssh
  2. .ssh ll -a
  3. total 24
  4. drwx------ 5 xuyisheng staff 170B 10 26 15:12 .
  5. drwxr-xr-x+ 37 xuyisheng staff 1.2K 12 14 21:10 ..
  6. -rw------- 1 xuyisheng staff 1.6K 10 26 15:08 id_rsa
  7. -rw-r--r-- 1 xuyisheng staff 403B 10 26 15:08 id_rsa.pub
  8. -rw-r--r-- 1 xuyisheng staff 2.4K 11 3 14:30 known_hosts

这里由于已经使用过Git,所以生成了两个文件。如果没有这两个文件,那么可以通过命令生成这两个文件,代码如下所示。

  1. ssh-keygen -t rsa -C "youremail@example.com"

执行指令后效果如下所示。

  1. .ssh ssh-keygen -t rsa -C "xuyisheng89@163.com"
  2. Generating public/private rsa key pair.
  3. Enter file in which to save the key (/Users/xuyisheng/.ssh/id_rsa):
  4. Enter passphrase (empty for no passphrase):
  5. Enter same passphrase again:
  6. Your identification has been saved in /Users/xuyisheng/.ssh/id_rsa.
  7. Your public key has been saved in /Users/xuyisheng/.ssh/id_rsa.pub.
  8. The key fingerprint is:
  9. SHA256:CVBfuQyPdtlDWHpS1he46drRe1noZVY0ZxERr/z8524 xuyisheng89@163.com
  10. The key's randomart image is:
  11. +---[RSA 2048]----+
  12. | ... .++..**|
  13. | . ...o+....*|
  14. | . .=o=. o++|
  15. | .o.*oo+ ..|
  16. | .S. ..+..|
  17. | o.+=|
  18. | o..+*|
  19. | . ..oE|
  20. | +*|
  21. +----[SHA256]-----+

该命令生成的id_rsa和id_rsa.pub两个文件就是SSH Key的秘钥对。id_rsa是私钥用于验证自己的身份,而id_rsa.pub是公钥用在Git远程服务器上表明自己的身份。

添加SSH Key

下面需要把生成的SSH的公钥保存到Git远程服务器上。例如在Github上,可以在个人的配置界面找到添加SSH Key的设置,如图2.8所示。

身份认证 - 图1 图2.8 Github Setting

选择右边列表上的“Add an SSH Key”,将生成的id_ras.pub文件内容复制到Key输入框中即可。