发布于 2026-01-06 6 阅读
0

how2:如何在 macOS 上使用 GPG 而无需 GPGTools DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

如何在 macOS 上使用 GPG(无需 GPGTools)

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

我不喜欢 GPGTools。我想在 macOS 上使用 GPG。每个教程里都有一些过时的部分。以下是我的做法。


GPGTools 安装了很多我不需要的东西。我只想在 GitHub 上签名我的提交,并将我的 GPG 密钥保存到 macOS 钥匙串中。

要实现这一点,主要有两个依赖项:gnupg 包含用于生成密钥和签名的 GPG 工具,以及用于执行代理操作的代理;pinentry-mac 是 GPGTools 的一部分,它会提示您输入密钥密码并将其存储在操作系统钥匙串中。

GPG 设置

首先,请安装Homebrew

之后,安装依赖项:

brew install gnupg pinentry-mac
Enter fullscreen mode Exit fullscreen mode

注意安装命令的输出结果,它会告诉你pinentry-mac程序的安装位置:

==> Caveats
==> pinentry-mac
You can now set this as your pinentry program like

~/.gnupg/gpg-agent.conf
    pinentry-program /some/path/here
Enter fullscreen mode Exit fullscreen mode

您需要配置 gpg-agent 以使用 pinentry-mac,方法是创建一个名为 ~/.gnupg/gpg-agent.conf 的文件,并指向正确的 pinentry-mac 程序:

# Connects gpg-agent to the OSX keychain via the brew-installed
# pinentry program from GPGtools. This is the OSX 'magic sauce',
# allowing the gpg key's passphrase to be stored in the login
# keychain, enabling automatic key signing.
pinentry-program /usr/local/bin/pinentry-mac
Enter fullscreen mode Exit fullscreen mode

对于搭载 Apple Silicon 芯片的 Mac 电脑,Homebrew 使用的是不同的路径:

pinentry-program /opt/homebrew/bin/pinentry-mac
Enter fullscreen mode Exit fullscreen mode

接下来,我们来生成你的第一个密钥。我建议使用 RSA 算法,密钥长度为 4096 位,并且不要设置密钥过期时间。记住要选择一个强密码

gpg --full-generate-key
Enter fullscreen mode Exit fullscreen mode

然后,对一条测试消息进行签名,以便 pinentry-mac 可以将您的密码存储在钥匙串中:

echo "test" | gpg --clearsign
Enter fullscreen mode Exit fullscreen mode

这将弹出一个对话框,提示您输入密码。请记得勾选“保存到钥匙串”。

正在连接到 GitHub

首先,复制您的私钥并添加到 GitHub:

gpg --export --armor your@email.here | pbcopy
Enter fullscreen mode Exit fullscreen mode

然后将其粘贴到GitHub 的设置 > SSH 和 GPG 密钥 > 新的 GPG 密钥中。

其次,配置你的 Git 环境以使用签名提交。我已经全局配置好了。首先获取你的公钥:

$ gpg --list-secret-keys
(...)
sec   rsa2048 2019-01-15 [SC]
      YOUR_GPG_KEY_APPEARS_HERE
uid           [ultimate] Your Name <your@email.here>
ssb   rsa2048 2019-01-15 [E]
Enter fullscreen mode Exit fullscreen mode

然后配置 Git:

git config --global commit.gpgsign true
git config --global user.signingkey YOUR_GPG_KEY
Enter fullscreen mode Exit fullscreen mode

最后,使用 -S 参数提交一些内容,以确保它是签名的:

git commit -S -m "Testing GPG signature"
Enter fullscreen mode Exit fullscreen mode

故障排除

如果方法无效,您可以尝试以下方法:

# Kill gpg-agent
killall gpg-agent

# Run gpg-agent in daemon mode
gpg-agent --daemon
Enter fullscreen mode Exit fullscreen mode

封面照片由Micah Williams拍摄,来自Unsplash

文章来源:https://dev.to/wes/how2-using-gpg-on-macos-without-gpgtools-428f