e5da278d6cece3ce5b1d376ae8277428fc32e7ca
[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., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, 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
46 (defcustom encrypt-file-alist nil
47   "List of file names or regexes matched with encryptions.
48 Format example:
49  '((\"beta\"
50     (gpg \"AES\"))
51    (\"/home/tzz/alpha\"
52     (encrypt-xor \"Semi-Secret\")))"
53
54   :type '(repeat
55           (list :tag "Encryption entry"
56            (radio :tag "What to encrypt"
57                   (file :tag "Filename")
58                   (regexp :tag "Regular expression match"))
59            (radio :tag "How to encrypt it"
60                   (list
61                    :tag "GPG Encryption"
62                    (const :tag "GPG Program" gpg)
63                    (radio :tag "Choose a cipher"
64                           (const :tag "3DES Encryption" "3DES")
65                           (const :tag "CAST5 Encryption" "CAST5")
66                           (const :tag "Blowfish Encryption" "BLOWFISH")
67                           (const :tag "AES Encryption" "AES")
68                           (const :tag "AES192 Encryption" "AES192")
69                           (const :tag "AES256 Encryption" "AES256")
70                           (const :tag "Twofish Encryption" "TWOFISH")
71                           (string :tag "Cipher Name")))
72                   (list
73                    :tag "Built-in simple XOR"
74                    (const :tag "XOR Encryption" encrypt-xor)
75                    (string :tag "XOR Cipher Value (seed value)")))))
76   :group 'encrypt)
77
78 ;; TODO: now, load gencrypt.el and if successful, modify the
79 ;; custom-type of encrypt-file-alist to add the gencrypt.el options
80
81 ;; (plist-get (symbol-plist 'encrypt-file-alist) 'custom-type)
82 ;; then use plist-put
83
84 (defcustom encrypt-gpg-path (executable-find "gpg")
85   "Path to the GPG program."
86   :type '(radio
87           (file :tag "Location of the GPG executable")
88           (const :tag "GPG is not installed" nil))
89   :group 'encrypt)
90
91 (defvar encrypt-temp-prefix "encrypt"
92   "Prefix for temporary filenames")
93
94 ;;;###autoload
95 (defun encrypt-find-model (filename)
96   "Given a filename, find a encrypt-file-alist entry"
97   (dolist (entry encrypt-file-alist)
98     (let ((match (nth 0 entry))
99           (model (nth 1 entry)))
100       (when (or (eq match filename)
101                 (string-match match filename))
102         (return model)))))
103
104 ;;;###autoload
105 (defun encrypt-insert-file-contents (file &optional model)
106   "Decrypt FILE into the current buffer."
107   (interactive "fFile to insert: ")
108   (let* ((model (or model (encrypt-find-model file)))
109          (method (nth 0 model))
110          (cipher (nth 1 model))
111          (password-key (format "encrypt-password-%s-%s %s"
112                                (symbol-name method) cipher file))
113          (passphrase
114           (password-read-and-add
115            (format "%s password for cipher %s? "
116                    (symbol-name method) cipher)
117            password-key))
118           (buffer-file-coding-system 'binary)
119          (coding-system-for-read 'binary)
120          outdata)
121
122     ;; note we only insert-file-contents if the method is known to be valid
123     (cond
124      ((eq method 'gpg)
125       (insert-file-contents file)
126       (setq outdata (encrypt-gpg-decode-buffer passphrase cipher)))
127      ((eq method 'encrypt-xor)
128       (insert-file-contents file)
129       (setq outdata (encrypt-xor-decode-buffer passphrase cipher))))
130
131     (if outdata
132         (progn
133           (gnus-message 9 "%s was decrypted with %s (cipher %s)"
134                         file (symbol-name method) cipher)
135           (delete-region (point-min) (point-max))
136           (goto-char (point-min))
137           (insert outdata))
138       ;; the decryption failed, alas
139       (password-cache-remove password-key)
140       (gnus-error 5 "%s was NOT decrypted with %s (cipher %s)"
141                   file (symbol-name method) cipher))))
142
143 (defun encrypt-get-file-contents (file &optional model)
144   "Decrypt FILE and return the contents."
145   (interactive "fFile to decrypt: ")
146   (with-temp-buffer
147     (encrypt-insert-file-contents file model)
148     (buffer-string)))
149
150 (defun encrypt-put-file-contents (file data &optional model)
151   "Encrypt the DATA to FILE, then continue normally."
152   (with-temp-buffer
153     (insert data)
154     (encrypt-write-file-contents file model)))
155
156 (defun encrypt-write-file-contents (file &optional model)
157   "Encrypt the current buffer to FILE, then continue normally."
158   (interactive "fFile to write: ")
159   (let* ((model (or model (encrypt-find-model file)))
160          (method (nth 0 model))
161          (cipher (nth 1 model))
162          (password-key (format "encrypt-password-%s-%s %s"
163                                (symbol-name method) cipher file))
164          (passphrase
165           (password-read
166            (format "%s password for cipher %s? "
167                    (symbol-name method) cipher)
168            password-key))
169          outdata)
170
171     (cond
172      ((eq method 'gpg)
173       (setq outdata (encrypt-gpg-encode-buffer passphrase cipher)))
174      ((eq method 'encrypt-xor)
175       (setq outdata (encrypt-xor-encode-buffer passphrase cipher))))
176
177     (if outdata
178         (progn
179           (gnus-message 9 "%s was encrypted with %s (cipher %s)"
180                         file (symbol-name method) cipher)
181           (delete-region (point-min) (point-max))
182           (goto-char (point-min))
183           (insert outdata)
184           ;; do not confirm overwrites
185           (write-file file nil))
186       ;; the decryption failed, alas
187       (password-cache-remove password-key)
188       (gnus-error 5 "%s was NOT encrypted with %s (cipher %s)"
189                   file (symbol-name method) cipher))))
190
191 (defun encrypt-xor-encode-buffer (passphrase cipher)
192   (encrypt-xor-process-buffer passphrase cipher t))
193
194 (defun encrypt-xor-decode-buffer (passphrase cipher)
195   (encrypt-xor-process-buffer passphrase cipher nil))
196
197 (defun encrypt-xor-process-buffer (passphrase
198                                         cipher
199                                         &optional encode)
200   "Given PASSPHRASE, xor-encode or decode the contents of the current buffer."
201   (let* ((bs (buffer-substring-no-properties (point-min) (point-max)))
202          ;; passphrase-sum is a simple additive checksum of the
203          ;; passphrase and the cipher
204         (passphrase-sum
205          (when (stringp passphrase)
206            (apply '+ (append cipher passphrase nil))))
207         new-list)
208
209     (with-temp-buffer
210       (if encode
211           (progn
212             (dolist (x (append bs nil))
213               (setq new-list (cons (logxor x passphrase-sum) new-list)))
214
215             (dolist (x new-list)
216               (insert (format "%d " x))))
217         (progn
218           (setq new-list (reverse (split-string bs)))
219           (dolist (x new-list)
220             (setq x (string-to-int x))
221             (insert (format "%c" (logxor x passphrase-sum))))))
222       (buffer-substring-no-properties (point-min) (point-max)))))
223
224 (defun encrypt-gpg-encode-buffer (passphrase cipher)
225   (encrypt-gpg-process-buffer passphrase cipher t))
226
227 (defun encrypt-gpg-decode-buffer (passphrase cipher)
228   (encrypt-gpg-process-buffer passphrase cipher nil))
229
230 (defun encrypt-gpg-process-buffer (passphrase 
231                                         cipher 
232                                         &optional encode)
233   "With PASSPHRASE, use GPG to encode or decode the current buffer."
234   (let* ((program encrypt-gpg-path)
235          (input (buffer-substring-no-properties (point-min) (point-max)))
236          (temp-maker (if (fboundp 'make-temp-file) 
237                          'make-temp-file 
238                        'make-temp-name))
239          (temp-file (funcall temp-maker encrypt-temp-prefix))
240          (default-enable-multibyte-characters nil)
241          (args `("--cipher-algo" ,cipher
242                  "--status-fd" "2"
243                  "--logger-fd" "2"
244                  "--passphrase-fd" "0"
245                  "--no-tty"))
246          exit-status exit-data)
247     
248     (when encode
249       (setq args
250             (append args
251                     '("--symmetric"
252                       "--armor"))))
253
254     (if program
255         (with-temp-buffer
256           (when passphrase
257             (insert passphrase "\n"))
258           (insert input)
259           (setq exit-status
260                 (apply #'call-process-region (point-min) (point-max) program
261                        t `(t ,temp-file) nil args))
262           (if (equal exit-status 0)
263               (setq exit-data
264                     (buffer-substring-no-properties (point-min) (point-max)))
265             (with-temp-buffer
266               (when (file-exists-p temp-file)
267                 (insert-file-contents temp-file))
268               (gnus-error 5 (format "%s exited abnormally: '%s' [%s]"
269                                     program exit-status (buffer-string)))))
270           (delete-file temp-file))
271       (gnus-error 5 "GPG is not installed."))
272     exit-data))
273
274 (provide 'encrypt)
275 ;;; encrypt.el ends here