EasyPG修改GPG加密文件时能否跳过密码二次确认?
问题
通过Emacs/EasyPG访问GPG加密的保密文件时流程正常,但修改后保存需要两次输入密码(额外一次确认)。想确认EasyPG是否支持「新密码与原密码一致时跳过确认」的功能,或者如何用Elisp实现该需求。
环境信息
- GNU Emacs 29.1
- MacOS Ventura 13.4.1
- GnuPG 2.4.3
ps命令输出:gpg-agent --homedir /Users/.../.gnupg --use-standard-socket --daemon
当前配置
EasyPG自定义配置
'(epg-gpg-program "/opt/homebrew/opt/gnupg@2.2/bin/gpg") '(epg-pinentry-mode 'loopback)
.gnupg/gpg.conf
auto-key-retrieve no-emit-version
.gnupg/gpg-agent.conf
default-cache-ttl 600 max-cache-ttl 7200
解决方案
EasyPG本身没有内置「密码一致时跳过确认」的功能,但可以通过自定义Elisp代码拦截保存流程,复用原密码来避免重复输入。
核心思路
保存加密文件时,EasyPG默认会提示输入新密码和确认密码。我们可以通过修改epg-write-file-encrypt-to函数的行为,在检测到新密码与原密码一致时自动跳过确认步骤。
实现代码
将以下代码添加到你的Emacs配置文件(如init.el)中:
(defun my-epg-skip-password-confirmation (orig-fun &rest args) "Wrap `epg-write-file-encrypt-to' to skip password confirmation if same as original." (let* ((file (car args)) (context (epg-make-context epg-gpg-program)) (cipher-info (epg-decrypt-file context file)) (original-passphrase (when cipher-info (epg-context-passphrase context)))) (if original-passphrase (let ((new-passphrase (read-passwd "Enter passphrase: ")) confirm-passphrase) (if (string= new-passphrase original-passphrase) (apply orig-fun file (cadr args) :passphrase new-passphrase) (progn (setq confirm-passphrase (read-passwd "Confirm passphrase: ")) (if (string= new-passphrase confirm-passphrase) (apply orig-fun file (cadr args) :passphrase new-passphrase) (error "Passphrases do not match"))))) (apply orig-fun args)))) (advice-add 'epg-write-file-encrypt-to :around #'my-epg-skip-password-confirmation)
代码说明
- 用
advice-add包裹epg-write-file-encrypt-to(EasyPG保存加密文件的核心函数),拦截原有逻辑。 - 先获取原文件的解密密码(依赖gpg-agent缓存,缓存有效期内无需重复输入原密码)。
- 提示输入新密码,若与原密码一致,直接用该密码完成保存,跳过确认步骤。
- 若新密码与原密码不同,仍会提示确认密码,保留原有校验逻辑。
额外优化
当前gpg-agent.conf的缓存设置(10分钟默认缓存、2小时最大缓存)已经比较合理,在缓存有效期内修改文件时,无需重新输入原密码,直接复用缓存密码完成保存。
内容的提问来源于stack exchange,提问作者René Steetskamp
相关产品推荐
相关产品推荐

