From e608477da2ff300bbc7796bd3c1a42394d1f1148 Mon Sep 17 00:00:00 2001 From: Lars Ingebrigtsen Date: Wed, 30 Sep 2020 03:47:47 +0200 Subject: [PATCH] Give better error feedback on wrong password in .gpg files * lisp/epa-file.el (epa-file--find-file-not-found-function): Do a user-error when there's a wrong password (bug#43704). (epa--wrong-password-p): New function. (epa-file-insert-file-contents): Use it, and stash the error away for later signalling. * lisp/emacs-lisp/subr-x.el (if-let): Autoload. --- lisp/emacs-lisp/subr-x.el | 1 + lisp/epa-file.el | 21 ++++++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lisp/emacs-lisp/subr-x.el b/lisp/emacs-lisp/subr-x.el index 9f96ac50d1c..e6abb39ddc6 100644 --- a/lisp/emacs-lisp/subr-x.el +++ b/lisp/emacs-lisp/subr-x.el @@ -156,6 +156,7 @@ are non-nil, then the result is non-nil." ,@(or body `(,res)))) `(let* () ,@(or body '(t)))))) +;;;###autoload (defmacro if-let (spec then &rest else) "Bind variables according to SPEC and evaluate THEN or ELSE. Evaluate each binding in turn, as in `let*', stopping if a diff --git a/lisp/epa-file.el b/lisp/epa-file.el index bb027b9abfb..7fd41784746 100644 --- a/lisp/epa-file.el +++ b/lisp/epa-file.el @@ -26,6 +26,7 @@ (require 'epa) (require 'epa-hook) +(eval-when-compile (require 'subr-x)) ;;; Options @@ -115,8 +116,17 @@ encryption is used." (let ((error epa-file-error)) (save-window-excursion (kill-buffer)) - (signal 'file-missing - (cons "Opening input file" (cdr error))))) + (if (nth 3 error) + (user-error "Wrong passphrase: %s" (nth 3 error)) + (signal 'file-missing + (cons "Opening input file" (cdr error)))))) + +(defun epa--wrong-password-p (context) + (let ((error-string (epg-context-error-output context))) + (and (string-match + "decryption failed: \\(Bad session key\\|No secret key\\)" + error-string) + (match-string 1 error-string)))) (defvar last-coding-system-used) (defun epa-file-insert-file-contents (file &optional visit beg end replace) @@ -159,7 +169,12 @@ encryption is used." (nth 3 error))) (let ((exists (file-exists-p local-file))) (when exists - (epa-display-error context) + (if-let ((wrong-password (epa--wrong-password-p context))) + ;; Don't display the *error* buffer if we just + ;; have a wrong password; let the later error + ;; handler notify the user. + (setq error (append error (list wrong-password))) + (epa-display-error context)) ;; When the .gpg file isn't an encrypted file (e.g., ;; it's a keyring.gpg file instead), then gpg will ;; say "Unexpected exit" as the error message. In -- 2.39.2