Merge the t-gnus-6_17-quimby branch.
[elisp/gnus.git-] / lisp / encrypt.el
1 ;;; encrypt.el --- file encryption routines
2 ;; Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3
4 ;; Author: Teodor Zlatanov <tzz@lifelogs.com>
5 ;; Created: 2003/01/24
6 ;; Keywords: files
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
24
25 ;;; Commentary:
26
27 ;;; This module addresses data encryption.  Page breaks are used for
28 ;;; grouping declarations and documentation relating to each
29 ;;; particular aspect.
30
31 ;;; Code:
32
33 ;; autoload password
34 (eval-and-compile
35   (autoload 'password-read "password")
36   ;; The following section is needed since T-gnus won't load password.el
37   ;; by way of pgg.el at the compile time.
38   (autoload 'password-read-and-add "password")
39   (autoload 'password-cache-remove "password")
40   (defvar password-cache-expiry))
41
42 (defgroup encrypt '((password-cache custom-variable)
43                     (password-cache-expiry custom-variable))
44   "File encryption configuration."
45   :group 'applications)
46
47 (defcustom encrypt-file-alist nil
48   "List of file names or regexes matched with encryptions.
49 Format example:
50  '((\"beta\"
51     (gpg \"AES\"))
52    (\"/home/tzz/alpha\"
53     (encrypt-xor \"Semi-Secret\")))"
54
55   :type '(repeat
56           (list :tag "Encryption entry"
57            (radio :tag "What to encrypt"
58                   (file :tag "Filename")
59                   (regexp :tag "Regular expression match"))
60            (radio :tag "How to encrypt it"
61                   (list
62                    :tag "GPG Encryption"
63                    (const :tag "GPG Program" gpg)
64                    (radio :tag "Choose a cipher"
65                           (const :tag "3DES Encryption" "3DES")
66                           (const :tag "CAST5 Encryption" "CAST5")
67                           (const :tag "Blowfish Encryption" "BLOWFISH")
68                           (const :tag "AES Encryption" "AES")
69                           (const :tag "AES192 Encryption" "AES192")
70                           (const :tag "AES256 Encryption" "AES256")
71                           (const :tag "Twofish Encryption" "TWOFISH")
72                           (string :tag "Cipher Name")))
73                   (list
74                    :tag "Built-in simple XOR"
75                    (const :tag "XOR Encryption" encrypt-xor)
76                    (string :tag "XOR Cipher Value (seed value)")))))
77   :group 'encrypt)
78
79 ;; TODO: now, load gencrypt.el and if successful, modify the
80 ;; custom-type of encrypt-file-alist to add the gencrypt.el options
81
82 ;; (plist-get (symbol-plist 'encrypt-file-alist) 'custom-type)
83 ;; then use plist-put
84
85 (defcustom encrypt-gpg-path (executable-find "gpg")
86   "Path to the GPG program."
87   :type '(radio
88           (file :tag "Location of the GPG executable")
89           (const :tag "GPG is not installed" nil))
90   :group 'encrypt)
91
92 (defvar encrypt-temp-prefix "encrypt"
93   "Prefix for temporary filenames")
94
95 ;;;###autoload
96 (defun encrypt-find-model (filename)
97   "Given a filename, find a encrypt-file-alist entry"
98   (dolist (entry encrypt-file-alist)
99     (let ((match (nth 0 entry))
100           (model (nth 1 entry)))
101       (when (or (eq match filename)
102                 (string-match match filename))
103         (return model)))))
104
105 ;;;###autoload
106 (defun encrypt-insert-file-contents (file &optional model)
107   "Decrypt FILE into the current buffer."
108   (interactive "fFile to insert: ")
109   (let* ((model (or model (encrypt-find-model file)))
110          (method (nth 0 model))
111          (cipher (nth 1 model))
112          (password-key (format "encrypt-password-%s-%s %s"
113                                (symbol-name method) cipher file))
114          (passphrase
115           (password-read-and-add
116            (format "%s password for cipher %s? "
117                    (symbol-name method) cipher)
118            password-key))
119           (buffer-file-coding-system 'binary)
120          (coding-system-for-read 'binary)
121          outdata)
122
123     ;; note we only insert-file-contents if the method is known to be valid
124     (cond
125      ((eq method 'gpg)
126       (insert-file-contents file)
127       (setq outdata (encrypt-gpg-decode-buffer passphrase cipher)))
128      ((eq method 'encrypt-xor)
129       (insert-file-contents file)
130       (setq outdata (encrypt-xor-decode-buffer passphrase cipher))))
131
132     (if outdata
133         (progn
134           (message "%s was decrypted with %s (cipher %s)"
135                    file (symbol-name method) cipher)
136           (delete-region (point-min) (point-max))
137           (goto-char (point-min))
138           (insert outdata))
139       ;; the decryption failed, alas
140       (password-cache-remove password-key)
141       (gnus-error 5 "%s was NOT decrypted with %s (cipher %s)"
142                   file (symbol-name method) cipher))))
143
144 (defun encrypt-get-file-contents (file &optional model)
145   "Decrypt FILE and return the contents."
146   (interactive "fFile to decrypt: ")
147   (with-temp-buffer
148     (encrypt-insert-file-contents file model)
149     (buffer-string)))
150
151 (defun encrypt-put-file-contents (file data &optional model)
152   "Encrypt the DATA to FILE, then continue normally."
153   (with-temp-buffer
154     (insert data)
155     (encrypt-write-file-contents file model)))
156
157 (defun encrypt-write-file-contents (file &optional model)
158   "Encrypt the current buffer to FILE, then continue normally."
159   (interactive "fFile to write: ")
160   (let* ((model (or model (encrypt-find-model file)))
161          (method (nth 0 model))
162          (cipher (nth 1 model))
163          (password-key (format "encrypt-password-%s-%s %s"
164                                (symbol-name method) cipher file))
165          (passphrase
166           (password-read
167            (format "%s password for cipher %s? "
168                    (symbol-name method) cipher)
169            password-key))
170          outdata)
171
172     (cond
173      ((eq method 'gpg)
174       (setq outdata (encrypt-gpg-encode-buffer passphrase cipher)))
175      ((eq method 'encrypt-xor)
176       (setq outdata (encrypt-xor-encode-buffer passphrase cipher))))
177
178     (if outdata
179         (progn
180           (message "%s was encrypted with %s (cipher %s)"
181                    file (symbol-name method) cipher)
182           (delete-region (point-min) (point-max))
183           (goto-char (point-min))
184           (insert outdata)
185           ;; do not confirm overwrites
186           (write-file file nil))
187       ;; the decryption failed, alas
188       (password-cache-remove password-key)
189       (gnus-error 5 "%s was NOT encrypted with %s (cipher %s)"
190                   file (symbol-name method) cipher))))
191
192 (defun encrypt-xor-encode-buffer (passphrase cipher)
193   (encrypt-xor-process-buffer passphrase cipher t))
194
195 (defun encrypt-xor-decode-buffer (passphrase cipher)
196   (encrypt-xor-process-buffer passphrase cipher nil))
197
198 (defun encrypt-xor-process-buffer (passphrase
199                                         cipher
200                                         &optional encode)
201   "Given PASSPHRASE, xor-encode or decode the contents of the current buffer."
202   (let* ((bs (buffer-substring-no-properties (point-min) (point-max)))
203          ;; passphrase-sum is a simple additive checksum of the
204          ;; passphrase and the cipher
205         (passphrase-sum
206          (when (stringp passphrase)
207            (apply '+ (append cipher passphrase nil))))
208         new-list)
209
210     (with-temp-buffer
211       (if encode
212           (progn
213             (dolist (x (append bs nil))
214               (setq new-list (cons (logxor x passphrase-sum) new-list)))
215
216             (dolist (x new-list)
217               (insert (format "%d " x))))
218         (progn
219           (setq new-list (reverse (split-string bs)))
220           (dolist (x new-list)
221             (setq x (string-to-number x))
222             (insert (format "%c" (logxor x passphrase-sum))))))
223       (buffer-substring-no-properties (point-min) (point-max)))))
224
225 (defun encrypt-gpg-encode-buffer (passphrase cipher)
226   (encrypt-gpg-process-buffer passphrase cipher t))
227
228 (defun encrypt-gpg-decode-buffer (passphrase cipher)
229   (encrypt-gpg-process-buffer passphrase cipher nil))
230
231 (defun encrypt-gpg-process-buffer (passphrase 
232                                         cipher 
233                                         &optional encode)
234   "With PASSPHRASE, use GPG to encode or decode the current buffer."
235   (let* ((program encrypt-gpg-path)
236          (input (buffer-substring-no-properties (point-min) (point-max)))
237          (temp-maker (if (fboundp 'make-temp-file) 
238                          'make-temp-file 
239                        'make-temp-name))
240          (temp-file (funcall temp-maker encrypt-temp-prefix))
241          (default-enable-multibyte-characters nil)
242          (args `("--cipher-algo" ,cipher
243                  "--status-fd" "2"
244                  "--logger-fd" "2"
245                  "--passphrase-fd" "0"
246                  "--no-tty"))
247          exit-status exit-data)
248     
249     (when encode
250       (setq args
251             (append args
252                     '("--symmetric"
253                       "--armor"))))
254
255     (if program
256         (with-temp-buffer
257           (when passphrase
258             (insert passphrase "\n"))
259           (insert input)
260           (setq exit-status
261                 (apply #'call-process-region (point-min) (point-max) program
262                        t `(t ,temp-file) nil args))
263           (if (equal exit-status 0)
264               (setq exit-data
265                     (buffer-substring-no-properties (point-min) (point-max)))
266             (with-temp-buffer
267               (when (file-exists-p temp-file)
268                 (insert-file-contents temp-file))
269               (gnus-error 5 (format "%s exited abnormally: '%s' [%s]"
270                                     program exit-status (buffer-string)))))
271           (delete-file temp-file))
272       (gnus-error 5 "GPG is not installed."))
273     exit-data))
274
275 (provide 'encrypt)
276 ;;; encrypt.el ends here