macOS生成密钥对教程
在 macOS 下生成密钥对(如 SSH 密钥)可通过终端命令完成,以下是详细步骤:
方法 1:使用 ssh-keygen
生成 SSH 密钥对(推荐)
-
打开终端
通过 Spotlight 搜索(Command + 空格
)输入Terminal
并打开。 -
生成密钥对
输入以下命令(推荐使用更安全的ed25519
算法,或兼容性更好的RSA
):# 使用 ed25519 算法(更安全高效) ssh-keygen -t ed25519 -C "your_email@example.com"# 或使用 RSA 算法(兼容旧系统) ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-C
后可替换为你的邮箱或注释(非必需)。-b 4096
指定 RSA 密钥长度(默认为 3072 位)。
-
指定保存路径
按提示输入密钥保存路径(默认~/.ssh/id_ed25519
或~/.ssh/id_rsa
),直接回车使用默认路径。 -
设置密钥密码(可选)
输入一个密码(passphrase)增强安全性(可留空直接回车跳过)。 -
生成成功
终端显示:Your identification has been saved in /Users/you/.ssh/id_ed25519 Your public key has been saved in /Users/you/.ssh/id_ed25519.pub
方法 2:生成 GPG 密钥对
若需 GPG 密钥(用于加密/签名),使用 gpg
命令:
# 安装 GPG(如未安装)
brew install gnupg# 生成 GPG 密钥
gpg --full-generate-key
按提示选择:
- 密钥类型:
RSA and RSA
(默认)。 - 密钥长度:
4096
。 - 设置有效期(建议
0
= 永不过期)。 - 输入姓名、邮箱。
- 设置保护密码(可选)。
密钥位置与管理
- SSH 密钥
- 私钥:
~/.ssh/id_ed25519
或~/.ssh/id_rsa
- 公钥:
~/.ssh/id_ed25519.pub
或~/.ssh/id_rsa.pub
- 私钥:
- GPG 密钥
查看公钥:gpg --armor --export your_email@example.com
查看私钥:gpg --list-secret-keys
常用操作
-
复制 SSH 公钥
pbcopy < ~/.ssh/id_ed25519.pub # 公钥内容存入剪贴板
粘贴到 GitHub/GitLab 等服务的 SSH Keys 设置中。
-
启动 ssh-agent(避免重复输入密码)
eval "$(ssh-agent -s)" ssh-add --apple-use-keychain ~/.ssh/id_ed25519 # 存储密码到钥匙串
-
验证 SSH 连接
ssh -T git@github.com # 测试 GitHub
安全提示
- 🔒 私钥永不分享!仅公钥(
.pub
文件)可公开。 - 使用密码保护密钥(即使泄露也多一层防御)。
- 定期备份
~/.ssh/
目录。
完成后即可将公钥用于 SSH 登录、Git 操作或加密通信。