Git 全套:GPG 签名、SSH 签名与多身份切换
Fedora 的 git 是 2.55.0,签名相关的能力全都在。这篇把「提交能被 GitHub/GitLab 标记 Verified」的两种姿势讲完。
GPG 签名提交
Section titled “GPG 签名提交”生成签名用密钥
Section titled “生成签名用密钥”gpg --batch --passphrase "" --quick-gen-key \实测这条命令在 Fedora 45 上直接可用(GnuPG 2.4.9),ed25519 比 RSA 快且签名短。1y 是有效期,到期前 --quick-set-expire 续。
拿到密钥指纹:
让 git 用它
Section titled “让 git 用它”git config --global user.name "Your Name"git config --global commit.gpgsign truegit config --global user.signingkey <指纹或邮箱>git commit -m "signed"git log --show-signature -1实测输出:
gpg: Signature made Thu 29 Oct 2026 02:59:26 AM UTCgpg: using EDDSA key 6F559EB9AF396AAE7799237AB812682FB6341EE3git log --format="%G?" -1 输出 G 表示有效签名。把公钥传到 GitHub(Settings → SSH and GPG keys)后,提交会显示 Verified 徽章。
SSH 签名(不想碰 GPG 的选这条)
Section titled “SSH 签名(不想碰 GPG 的选这条)”git 2.34 起支持用 SSH 密钥签名,密钥本来就是你的,不用再维护一套 GPG。
# 1. 专用的签名密钥(也可复用登录密钥)
# 2. 告诉 git 用 SSH 签名 + 哪把钥匙git config --global gpg.format sshgit config --global user.signingkey ~/.ssh/id_ed25519_sig.pub
# 3. 验证用白名单(不加这个,本地永远不显示 Good)git config --global gpg.ssh.allowedSignersFile ~/.ssh/allowed_signers实测行为差异
Section titled “实测行为差异”没配第 3 步时,git log --show-signature 报:
error: gpg.ssh.allowedSignersFile needs to be configured and exist for ssh signature verification且 %G? 输出 N。签名本身是成功的(GitHub 照样认),只是本地无法校验。配好白名单后:
Good "git" signature for [email protected] with ED25519 key SHA256:Pqut/KsBJcbpV00quDyPN6rtpmtssWsT8nq5s2UXS8Y%G? 变 G。
多身份切换:includeIf
Section titled “多身份切换:includeIf”公司仓库用工作邮箱、个人仓库用私人邮箱——写死 --global 必然出错。按目录切换:
# ~/.gitconfig 末尾追加[includeIf "gitdir:~/work/"] path = ~/.gitconfig-work[includeIf "gitdir:~/personal/"] path = ~/.gitconfig-personal~/.gitconfig-work:
[user] signingkey = <工作密钥指纹>验证是否生效:
cd ~/work/some-repogit config user.email # 输出公司邮箱改签名:amend 与 rebase
Section titled “改签名:amend 与 rebase”提交后想补签名(忘了开 commit.gpgsign):
git commit --amend --no-edit -S批量给最近 N 个未推送提交补签名:
git rebase --exec 'git commit --amend --no-edit -S' HEAD~5已推送的历史不要改写——签名改变的提交哈希会让协作者的拉取变成冲突。
| 现象 | 原因 |
|---|---|
gpg failed to sign the data | gpg-agent 没起或 pinentry 弹不出来;`echo test |
| GitHub 不认 GPG 签名 | 邮箱不匹配——签名邮箱必须是 GitHub 已验证邮箱 |
SSH 签名本地显示 N | 没配 gpg.ssh.allowedSignersFile(签名本身没问题) |
| CI 里签名失败 | 密钥有密码;CI 用无密码专用密钥或只验签 |
includeIf 不生效 | 路径大小写/末尾斜杠不匹配,git config --show-origin 查来源 |
| 换机器后签名失效 | 公钥没同步到平台,或 user.signingkey 指纹写死了旧密钥 |
- SSH 与密钥 — 登录密钥与 agent
- 终端与 shell — git 配置的运行环境
- 官方:git-sig tooling