Featured image of post Gpg4win / Kleopatra / GnuPG 对 git commit 签名

Gpg4win / Kleopatra / GnuPG 对 git commit 签名

配置git使用正确的ssh公钥; 配置git签名; 指定git签名公钥; git指定gpg客户端

前置步骤

  1. 安装Gpg4win;
  2. 生成或导入公私钥;
  3. 将SSH公钥与GPG公钥导入Github或Gitee;

此教程在Windows上描述,可同理应用于其他系统。

配置git使用正确的SSH公钥

存在多个ssh-key的环境下,git默认选择的公钥可能出现不对应,出现认证失败,即类似以下错误:

1
2
3
4
5
6
7
(base) PS D:\Code> git clone git@github.com:xxxx/xxxx.git
Cloning into 'xxxx'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

通过ssh-config配置Host方式,实现连接时选择正确公钥,即类似以下配置:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# ~/.ssh/config

Host github.com
    HostName github.com
    User git
    IdentityFile "C:\Users\Altman\.ssh\id_ed25519_github"
    IdentitiesOnly yes

Host gitee.com
    HostName gitee.com
    User git
    IdentityFile "C:\Users\Altman\.ssh\id_ed25519_gitee"
    IdentitiesOnly yes

配置git签名

如果你只想当前仓库签名:

1
git config --local commit.gpgsign true

如果要求所有仓库commit时均签名:

1
git config --global commit.gpgsign true

关闭签名:

1
git config commit.gpgsign false

指定git签名公钥

1
2
3
4
# 生成密钥
gpg --full-gen-key --expert
# 查看生成的密钥
gpg -K --keyid-format=short  #short输出8位 --keyid-format=long 则输出16位

输出信息大致如下,其中keyid是fingerprint的最后16位,使用最后8位也可以在本地识别到该key:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[keyboxd]
---------
pub   ed25519/F914ABD1 2023-10-24 [SC]
      12A52CF11A4D1C215AEAE73FF914A212xxxxxxxx
uid                 [  full  ] exp.com <exp@exp.com>
sub   cv25519/8447B18 2023-10-24 [E]
pub   ed25519/8C2AE92F 2023-11-14 [SC] [expires: 2026-11-13]
      F73017070D9B6A58CEAE55AD8C2AAD16xxxxxxxx
uid                 [ultimate] expp <exp@expp.com>
sub   cv25519/3030E9D4 2023-11-14 [E] [expires: 2026-11-13]

选择想要使用的签名公钥:

1
git config --global user.signingkey F914ABD1

git指定gpg客户端

上述步骤完成后,直接使用-S提交可能出现 “No secret key"错误,即以下错误:

1
2
3
4
5
(base) PS D:\Code\xxxx> git commit -a -S -m "PGP Test"
gpg: skipped "112510D8": No secret key
gpg: signing failed: No secret key
error: gpg failed to sign the data
fatal: failed to write commit object

原因在于OS/Git Bash自身可能具有gpg工具,但我们的公私钥并不存储于该工具内。 因此需要设置Git的gpg程序为我们安装的Gpg4win程序路径,即:

1
git config --global gpg.program "<安装目录>/GnuPG/bin/gpg.exe"

完成后,即可通过git commit -S完成签名提交。

本文参考众多信息,感谢大家的贡献!

Licensed under CC BY-NC-SA 4.0
最后更新于 Sep 20, 2024 15:34 CST
使用 Hugo 构建
主题 StackJimmy 设计