--- title: VSCode WSL 中使用 GPG 对 Git 记录进行签名 comments: true toc: true permalink: posts/wsl2-gpg/ date: 2021-02-28 11:02:00 categories: GPG tags: - VSCode - WSL - GPG --- 最近配置了一下 git 的 GPG,但是在使用 VSCode WSL 进行 git commit 的时候就提示: ```txt Git: gpg failed to sign the data ``` 详细输出如下: ```txt > git -c user.useConfigOnly=true commit --quiet --allow-empty-message --file - error: gpg failed to sign the data fatal: failed to write commit object ``` ## 原因 原因是你没有 「输入」 你设置的 gpg key 的密码,因为使用 VSCode WSL 的时候,没有一个图形界面让你输密码,所以 gpg 无法 sign 你的 commit。 在 Windows 图形界面下,gpg 会弹出一个 Pinentry 的 dialog 框让你输密码。而我们在使用 VSCode WSL 时,WSL 并没有使用到图形界面(XServer)。 ## 解决方法 解决方法很简单: gpg 会缓存我们第一次输入的密码,一段时间内我们多次对数据签名不需要重复输入密码,所以我们可以写一个 shell 函数,每次手动输入好了 gpg 的密码后,再使用 vsc 提交 commit。 如下两个函数: ```sh gpg-login() { export GPG_TTY=$TTY # 对 "test" 这个字符串进行 gpg 签名,这时候需要输密码。 # 然后密码就会被缓存,下次就不用输密码了。 # 重定向输出到 null,就不会显示到终端中。 echo "test" | gpg --clearsign > /dev/null 2>&1 } gpg-logout() { echo RELOADAGENT | gpg-connect-agent } ``` 在终端中输入 `gpg-login`,就会出现输密码的框,输入完密码之后该密码会被缓存,之后在 VSCode 进行 commit 的时候不用输密码了。 输入 `gpg-logout` 就可以清除你 `gpg` 密码的缓存。 虽然不是解决办法,但使用起来也还算方便,也能忍。 关于我 Shell 的一些其他配置,可见:[ubuntu_wsl/zshrc](https://github.com/bytemain/dotfiles/blob/master/ubuntu_wsl/zshrc)。 ## 配置 gpg 缓存时间 编辑这个文件 `~/.gnupg/gpg-agent.conf`: 添加如下内容,就可以将密码缓存 1 小时。 ```conf default-cache-ttl 3600 max-cache-ttl 3600 ``` 单位是秒。 ## 参考链接 - [vscode with ubuntu + wsl 2 never prompts for gpg passphrase even after configuration just “failed to write commit data”](https://stackoverflow.com/questions/61939216/vscode-with-ubuntu-wsl-2-never-prompts-for-gpg-passphrase-even-after-configura) - [How can I clear my cached gpg password?](https://askubuntu.com/questions/349238/how-can-i-clear-my-cached-gpg-password)