
Github 的 Commits 记录中的绿色 “Verified” 挺好看的,整一个。
使用 GPG Key 对 commit 签名即可在 Commits 记录中显示绿色 “Verified”。本文以 Github 为例,Gitee 平台的操作也是类似的。
环境
git version 2.35.1.windows.2
gpg (GnuPG) 2.2.29-unknown
windows 的 git 自带了 gpg, 无需单独下载安装。其他平台可能需要手动下载安装。
生成 GPG Key
输入指令。
1gpg --full-generate-key选择 key 类型,根据 Github 文档推荐选择默认,直接 enter。
Please select what kind of key you want: (1) RSA and RSA (default) (2) DSA and Elgamal (3) DSA (sign only) (4) RSA (sign only) (14) Existing key from card Your selection?选择 RSA 长度,根据 Github 文档推荐选择
4096。RSA keys may be between 1024 and 4096 bits long. What keysize do you want? (3072) 4096选择有效期,我这里选择一年
输入名字和邮箱,注意邮箱必须使用 Github 绑定的邮箱,否则在 Github 中会提示验证失败。如果开启了 Github 的 “Keep my email addresses private” 功能,则必须使用 Github 提供
<id>-<username>@users.noreply.github.com地址。信息无误则输入
O确认。1Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o输入安全口令。
建议设置密码,以保护 GPG Key
完成生成。
记录 16 位的 key id,例如我这里是
71C5EA31976DCC31。We need to generate a lot of random bytes. It is a good idea to perform some other action (type on the keyboard, move the mouse, utilize the disks) during the prime generation; this gives the random number generator a better chance to gain enough entropy. gpg: key '71C5EA31976DCC31' marked as ultimately trusted gpg: revocation certificate stored as '/c/Users/lixx/.gnupg/openpgp-revocs.d/681E61312333B6D9CC0A219771C5EA31976DCC31.rev' public and secret key created and signed. pub rsa4096 2022-02-10 [SC] [expires: 2023-02-10] 681E61312333B6D9CC0A219771C5EA31976DCC31 uid lixx.org <lixx@test.org> sub rsa4096 2022-02-10 [E] [expires: 2023-02-10]
输出 GPG 公钥
使用 gpg --armor --export <key-id> 输出公钥,我的 key-id 为 71C5EA31976DCC31
| |
然后得到公钥
-----BEGIN PGP PUBLIC KEY BLOCK-----
.
.
.
-----END PGP PUBLIC KEY BLOCK-----
添加公钥到 Github
将上面得到的公钥添加到 Github 账户设置的 GPG keys 中。 Gitee 同理。
设置 Git
使用命令行进行设置
在 Git 中设置要使用哪一个 GPG Key 的 id,我这里是
71C5EA31976DCC311git config --global user.signingkey 71C5EA31976DCC31设置 Git 用户名和邮箱。邮箱必须和 GPG Key 填写的邮箱以及 Github 绑定的邮箱相同,三者一致才能通过验证。
设置 Git 默认对 commit 进行 GPG 签名。(如果你需要)
1git config --global commit.gpgsign true设置 Git 默认对 tag 进行 GPG 签名。(如果你需要)
1git config --global tag.gpgsign true
直接设置 gitconfig
除了使用 git config 命令,也可以直接编辑 gitconfig,更为直观快捷。
- 全局
gitconfig:~/.gitconfig - 项目
gitconfig:./.git/config
[user]
name = lixx
email = lixx@test.org
signingkey = 681E61312333B6D9CC0A219771C5EA31976DCC31
[commit]
gpgsign = true
[tag]
gpgsign = true
提交 Commit
- 若没有开启默认对 commit 签名, 则需要使用
-S参数对单个 commit 进行签名。
| |
- 若已开启默认对 commit 签名,直接 commit 即可。
| |
然后需要输入生成 GPG Key 时设置的安全口令(如果有设置)。
git push 推送到 Github 后,即可在网页 Commits History 中看到绿色的 Verified。
额外
常用指令
查看已存在的私钥
gpg --list-secret-keys --keyid-format=long查看已存在的公钥
gpg --list-keys --keyid-format=long删除私钥
gpg --delete-secret-keys <id>删除公钥
gpg --delete-keys <id>输出公钥(ascii 格式)
gpg --armor --export <id>
提示
文中提到的
key id既可以使用 16 位的短 id,也可以使用 40 位的长 id。建议设置口令和有效期,降低 GPG 密钥丢失的危害。
~/.gnupg/文件夹需妥善保管。命令行操作生成 GPG key 还是有一点繁琐的,建议使用 GPG GUI 更为方便,例如 “Kleopatra”。