Skip to content

如何理解并使用 ssh 公钥

理解

SSH(Secure Shell,安全外壳)是一种网络安全协议,通过加密和认证机制实现安全的访问和文件传输等业务。

首先一台电脑可以生产一个公钥和私钥,公钥可以保存我们信任的第三方平台服务器里(比如 gitee),而私钥只保存在我们自己的电脑上。

公钥和私钥保证了客户端和服务器之间的数据传输安全。

windows 默认支持生成 ssh 公钥和私钥。

gitee 中设置 ssh

生成 SSH 公钥

Windows 用户建议使用 Windows PowerShell 或者 Git Bash,在 命令提示符 下无 cat 和 ls 命令。

1、通过命令 ssh-keygen 生成 SSH Key:

shell
# 复杂
ssh-keygen -t ed25519 -C "my lenovo computer"
# 或者简单
ssh-keygen -t rsa -C "mechrev_computer"
  • -t key 类型
  • -C 注释

输出:

$ ssh-keygen -t ed25519 -C "my lenovo computer"
Generating public/private ed25519 key pair.
Enter file in which to save the key (/c/Users/LuxCurl-user1/.ssh/id_ed25519):
Created directory '/c/Users/LuxCurl-user1/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/LuxCurl-user1/.ssh/id_ed25519
Your public key has been saved in /c/Users/LuxCurl-user1/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:jokuES4Jx8eWDrgVDGJCjMPpM1F0WNfGVQY61ln2I+s my lenovo computer
The key's randomart image is:
+--[ED25519 256]--+
|O=+ooo .o .oo=   |
|*=o.. .  +o = .  |
|.+.o .  .+ o . o |
|o+* =   . .   o .|
|.*o*    S    .   |
|+ o .. +    .    |
| . .. o .    E   |
|  ..             |
|   ..            |
+----[SHA256]-----+
  • 中间通过三次回车键确定

2、查看生成的 SSH 公钥和私钥:

shell
ls ~/.ssh/

输出:

id_ed25519  id_ed25519.pub
  • 私钥文件 id_ed25519
  • 公钥文件 id_ed25519.pub

3、读取公钥文件 ~/.ssh/id_ed25519.pub:

shell
cat ~/.ssh/id_ed25519.pub

输出,如:

shell
ssh-ed25519 AAAA***5B Gitee SSH Key

复制终端输出的公钥。

设置账户 SSH 公钥

用户可以通过主页右上角「个人设置」->「安全设置」->「SSH 公钥」->「添加公钥」 ,添加生成的 public key 添加到当前账户中。

需要注意:添加公钥需要验证用户密码

通过 ssh -T 测试,输出 SSH Key 绑定的用户名:

shell
$ ssh -T git@gitee.com
Hi USERNAME! You've successfully authenticated, but GITEE.COM does not provide shell access.

在添加完公钥后,用户可以在「个人设置」->「安全设置」->「SSH 公钥」浏览查看当前账户已经添加的 SSH 公钥,并对公钥进行管理/删除操作。

这些步骤完成后,就可以使用 ssh 的方式克隆、拉取、推送代码了。

可能报错

git 如何解决 The authenticity of host can't be established

新生成密钥的时候,git clone 或者 push 的时候,可能会报这样的错误:

The authenticity of host 'gitee.com (xxx.xxx.xxx.xxx)' can't be established.
ECDSA key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxx.

Google 之后明白,文件夹内少了一个 known_hosts 文件,本来密钥文件应该是三个,现在只有两个,便报了这样的错误,此时输入 yes 回车之后,生成了缺少了的 known_hosts 文件,便可解决这个问题:

Released under the MIT License.