ssh-keygen作用概览
ssh-keygen 是 OpenSSH 套件里的钥匙工匠,负责生成、管理、转换 SSH 密钥。它支持 RSA、ECDSA、ED25519 等类型,可用于登录、Git、公钥分发、证书签发等场景。
1.ssh-keygen常用参数及说明
1.1.基本生成
ssh-keygen -t ed25519 -C "user@host"
-t指定类型:rsa、ecdsa、ed25519-C注释,便于识别- Ed25519 是未来趋势,更快、更安全、密钥更小。
1.2.指定文件路径
ssh-keygen -f ~/.ssh/mykey
-f指定 key 文件前缀。
这在多 key、自动化、CI/CD 中非常重要。
1.3.自定义长度(仅限 RSA)
ssh-keygen -t rsa -b 4096
-b指定位数- RSA 4096 已经是大多数安全基线的最低要求。
1.4.强制覆盖
ssh-keygen -f ~/.ssh/id_rsa -N "" -t rsa -b 4096 -q -y
这里的重点是:
-N设置密码短语(空为无密码)-q静默模式
1.5.从私钥提取公钥
ssh-keygen -y -f ~/.ssh/id_rsa > id_rsa.pub
-y:从私钥导出公钥,CI/CD 或丢失公钥文件时补救用。

1.6.查看公钥指纹
ssh-keygen -lf ~/.ssh/id_ed25519.pub
-l查看指纹-f指定文件
用于验证公钥是否被替换、是否在跳板机中间人攻击。
1.7.更改私钥密码
ssh-keygen -p -f ~/.ssh/id_rsa
-p修改密钥密码短语
日常安全要求:密钥泄露后立即换 passphrase 或 rotate key。
1.8.格式转换
ssh-keygen -m PEM -f ~/.ssh/id_rsa
-m指定输出格式:RFC4716 / PEM / PKCS8
兼容老系统、网络设备(如 F5、Cisco)时有用。
2.多环境密钥管理
2.1.目录结构
~/.ssh/
id_ed25519_work
id_ed25519_home
id_ed25519_git
2.2.使用命令
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_work -C "work"
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_git -C "git"
2.3.结合config
Host gitlab-git
HostName gitlab.com
IdentityFile ~/.ssh/id_ed25519_git
Host gitlab-work
HostName gitlab.com
IdentityFile ~/.ssh/id_ed25519_work