常见的 SSH 登录密钥使用 RSA 算法。RSA 经典且可靠,但性能不够理想。

只要你的服务器上 OpenSSH 版本大于 6.5(2014 年的古早版本),就可以利用 Ed25519 算法生成的密钥对,减少你的登录时间。如果你使用 SSH 访问 Git,那么就更值得一试。

Ed25519 的安全性在 RSA 2048 与 RSA 4096 之间,且性能在数十倍以上。

准备工具

你需要用到 ssh-keygen,它是 OpenSSH 的组件,在 Linux 和 macOS 中一般都自带了。

如果你使用 Windows,安装 Git for Windows 时会一并安装 OpenSSH 到系统中。建议 Windows 用户使用 Git Bash 完成文中操作。

生成密钥

先上车再解释,让我们直接开始:

mkdir -p ~/.ssh && cd ~/.ssh
# 我在 GitHub
ssh-keygen -t ed25519 -f my_github_ed25519  -C "me@github"
# 我在 Gitee
ssh-keygen -t ed25519 -f my_gitee_ed25519   -C "me@gitee"
# 我在 GitLab
ssh-keygen -t ed25519 -f my_gitlab_ed25519  -C "me@gitlab"
# 我在企业
ssh-keygen -t ed25519 -f my_company_ed25519 -C "email@example.com"

▲ 注意修改 [-C "注释"] 部分。

添加到配置文件

将常用 SSH 信息写进全局配置文件,省得连接时配置。

编辑 ~/.ssh/config 文件:

# 关于别名
# Host 是别名,HostName 是真正的域名。
# 得益于别名,你可以直接以别名访问地址。例如:
# 无别名: git clone git@github.com:torvalds/linux.git
# 有别名: git clone github:torvalds/linux.git
# 本例中使用与域名一致的别名,以免错误的配置导致登录不上。

# 关于代理
# SOCKS 代理格式: ProxyCommand connect -S localhost:1080  %h %p
# HTTP 代理格式: ProxyCommand connect -H localhost:1080  %h %p
## SSH 代理依赖外部程序,这里使用了 Git for Windows 同捆的 connect.exe。
## Linux 下使用该代理方式需要额外安装 connect-proxy。

# 我在 GitHub
Host github.com
  Hostname github.com
#  ProxyCommand connect -H localhost:1080  %h %p
  User git
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/my_github_ed25519

# 我在 GitLab
Host gitlab.com
  Hostname gitlab.com
#  ProxyCommand connect -H localhost:1080  %h %p
  User git
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/my_gitlab_ed25519

# 我在 Gitee
Host gitee.com
  Hostname gitee.com
  User git
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/my_gitee_ed25519

# 我在企业
Host example.com
  Hostname example.com
  Port 22
  User git
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/my_company_ed25519

配置完毕。现在把 .pub 公钥文件发给服务器。

如果你懒得在每台机器上都配置一遍,把 ~/.ssh 下的文件放在安全的地方拷走即可。


解释: ssh-keygen 的命令含义

举例:

ssh-keygen -t rsa -b 4096 -f my_id -C "email@example.com"

其中:

  • [-t rsa] 表示使用 RSA 算法。
  • [-b 4096] 表示 RSA 密钥长度 4096 bits(默认 2048 bits)。Ed25519 算法不需要指定。
  • [-f my_id] 表示在【当前工作目录】下生成一个私钥文件 my_id (同时也会生成一个公钥文件 my_id.pub)。
  • [-C "email@example.com"] 表示在公钥文件中添加注释,即为这个公钥“起个别名”(不是 id,可以更改)。

在敲下该命令后,会提示输入 passphrase,即为私钥添加一个“解锁口令”。

解释:最佳实践

私钥必须要有 passphrase。如果私钥文件遗失,没有 passphrase 也无法解锁(只能暴力破解)。不要偷懒,passphrase 一定要加。

一对密钥只对应一个 Git 服务。一对密钥通吃各 Git 服务不太明智。

严格来讲,你应该在不同的机器上用不同的密钥,出了问题好排查处理。但实际上复杂的管理反而更容易让人犯错,选择你能 hold 住的方式更为重要。

标签
作者
评论