常見的 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 住的方式更為重要。