解决 GnuPG 报错 gpg: invalid keybox format pubring.kbx 密钥库损坏修复
排查 运行 gpg 签名或验签时,终端报错 gpg: [fatal] ~/.gnupg/pubring.kbx: invalid keybox format 或 read error,导致 Git GPG commit 签名中断,分析 Keybox 数据库损坏与从公钥重新重建。
问题现象
开发者在 Git 提交带签名 Commit 时,Git 命令直接失败报错:
$ git commit -S -m "feat: update security"
error: gpg failed to sign the data
fatal: failed to write commit object
[GPG Output]: gpg: fatal: /home/user/.gnupg/pubring.kbx: invalid keybox format
触发根因
- 磁盘非正常关机或多进程并发写入导致
~/.gnupg/pubring.kbx文件头部幻数(Magic Header)或记录偏移损坏; - GnuPG 现代 Keybox 二进制格式对文件完整性有严格校验,遇到损坏扇区直接致命退出;
- 进程无法读取公钥环数据导致数字签名流程中断。
解决步骤
备份并移除损坏的 pubring.kbx 文件
在终端执行安全隔离:
cd ~/.gnupg
mv pubring.kbx pubring.kbx.corrupted
利用已有的私钥库导出或从外部备份重新生成干净的 pubring.kbx
通过 gpg 重新初始化公钥映射:
# 重新导出私钥对应的公钥并导入:
gpg --export-secret-keys | gpg --import
测试 GPG 签名功能恢复
运行:echo "test" | gpg -s 确认签名顺畅无报错。
验证确认
重新执行 git commit -S:
GPG 进程秒级完成数字签名,GitHub 绿色 Verified 徽标正常点亮,提交顺利入库。


