2003-12-16 Simon Josefsson <jas@extundo.com>
[elisp/flim.git] / sha1-el.el
1 ;;; sha1-el.el --- SHA1 Secure Hash Algorithm in Emacs-Lisp.
2
3 ;; Copyright (C) 1999, 2001, 2003  Free Software Foundation, Inc.
4
5 ;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
6 ;; Keywords: SHA1, FIPS 180-1
7
8 ;; This file is part of FLIM (Faithful Library about Internet Message).
9
10 ;; This program is free software; you can redistribute it and/or
11 ;; modify it under the terms of the GNU General Public License as
12 ;; published by the Free Software Foundation; either version 2, or
13 ;; (at your option) any later version.
14
15 ;; This program 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 this program; see the file COPYING.  If not, write to
22 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This program is implemented from the definition of SHA-1 in FIPS PUB
28 ;; 180-1 (Federal Information Processing Standards Publication 180-1),
29 ;; "Announcing the Standard for SECURE HASH STANDARD".
30 ;; <URL:http://www.itl.nist.gov/div897/pubs/fip180-1.htm>
31 ;; (EXCEPTION; two optimizations taken from GnuPG/cipher/sha1.c)
32 ;;
33 ;; Test cases from FIPS PUB 180-1.
34 ;;
35 ;; (sha1 "abc")
36 ;; => a9993e364706816aba3e25717850c26c9cd0d89d
37 ;;
38 ;; (sha1 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
39 ;; => 84983e441c3bd26ebaae4aa1f95129e5e54670f1
40 ;;
41 ;; (sha1 (make-string 1000000 ?a))
42 ;; => 34aa973cd4c4daa4f61eeb2bdbad27316534016f
43 ;;
44 ;; BUGS:
45 ;;  * It is assumed that length of input string is less than 2^29 bytes.
46 ;;  * It is caller's responsibility to make string (or region) unibyte.
47 ;;
48 ;; TODO:
49 ;;  * Rewrite from scratch!
50 ;;    This version is much faster than Keiichi Suzuki's another sha1.el,
51 ;;    but it is too dirty.
52
53 ;;; Code:
54
55 (require 'hex-util)
56
57 (autoload 'executable-find "executable")
58
59 ;;;
60 ;;; external SHA1 function.
61 ;;;
62
63 (defgroup sha1 nil
64   "Elisp interface for SHA1 hash computation."
65   :group 'extensions)
66
67 (defcustom sha1-maximum-internal-length 500
68   "*Maximum length of message to use lisp version of SHA1 function.
69 If message is longer than this, `sha1-program' is used instead.
70
71 If this variable is set to 0, use extarnal program only.
72 If this variable is set to nil, use internal function only."
73   :type 'integer
74   :group 'sha1)
75
76 (defcustom sha1-program '("sha1sum")
77   "*Name of program to compute SHA1.
78 It must be a string \(program name\) or list of strings \(name and its args\)."
79   :type '(repeat string)
80   :group 'sha1)
81
82 (defcustom sha1-use-external (condition-case ()
83                                  (executable-find (car sha1-program))
84                                (error))
85   "*Use external SHA1 program.
86 If this variable is set to nil, use internal function only."
87   :type 'boolean
88   :group 'sha1)
89
90 (defun sha1-string-external (string)
91   ;; `with-temp-buffer' is new in v20, so we do not use it.
92   (save-excursion
93     (let (buffer)
94       (unwind-protect
95           (let (prog args)
96             (if (consp sha1-program)
97                 (setq prog (car sha1-program)
98                       args (cdr sha1-program))
99               (setq prog sha1-program
100                     args nil))
101             (setq buffer (set-buffer
102                           (generate-new-buffer " *sha1 external*")))
103             (insert string)
104             (apply (function call-process-region)
105                    (point-min)(point-max)
106                    prog t t nil args)
107             ;; SHA1 is 40 bytes long in hexadecimal form.
108             (buffer-substring (point-min)(+ (point-min) 40)))
109         (and buffer
110              (buffer-name buffer)
111              (kill-buffer buffer))))))
112
113 (defun sha1-region-external (beg end)
114   (sha1-string-external (buffer-substring-no-properties beg end)))
115
116 ;;;
117 ;;; internal SHA1 function.
118 ;;;
119
120 (eval-when-compile
121   ;; optional second arg of string-to-number is new in v20.
122   (defconst sha1-K0-high 23170)         ; (string-to-number "5A82" 16)
123   (defconst sha1-K0-low  31129)         ; (string-to-number "7999" 16)
124   (defconst sha1-K1-high 28377)         ; (string-to-number "6ED9" 16)
125   (defconst sha1-K1-low  60321)         ; (string-to-number "EBA1" 16)
126   (defconst sha1-K2-high 36635)         ; (string-to-number "8F1B" 16)
127   (defconst sha1-K2-low  48348)         ; (string-to-number "BCDC" 16)
128   (defconst sha1-K3-high 51810)         ; (string-to-number "CA62" 16)
129   (defconst sha1-K3-low  49622)         ; (string-to-number "C1D6" 16)
130
131 ;;; original definition of sha1-F0.
132 ;;; (defmacro sha1-F0 (B C D)
133 ;;;   (` (logior (logand (, B) (, C))
134 ;;;          (logand (lognot (, B)) (, D)))))
135 ;;; a little optimization from GnuPG/cipher/sha1.c.
136   (defmacro sha1-F0 (B C D)
137     (` (logxor (, D) (logand (, B) (logxor (, C) (, D))))))
138   (defmacro sha1-F1 (B C D)
139     (` (logxor (, B) (, C) (, D))))
140 ;;; original definition of sha1-F2.
141 ;;; (defmacro sha1-F2 (B C D)
142 ;;;   (` (logior (logand (, B) (, C))
143 ;;;          (logand (, B) (, D))
144 ;;;          (logand (, C) (, D)))))
145 ;;; a little optimization from GnuPG/cipher/sha1.c.
146   (defmacro sha1-F2 (B C D)
147     (` (logior (logand (, B) (, C))
148                (logand (, D) (logior (, B) (, C))))))
149   (defmacro sha1-F3 (B C D)
150     (` (logxor (, B) (, C) (, D))))
151
152   (defmacro sha1-S1  (W-high W-low)
153     (` (let ((W-high (, W-high))
154              (W-low  (, W-low)))
155          (setq S1W-high (+ (% (* W-high 2) 65536)
156                            (/ W-low (, (/ 65536 2)))))
157          (setq S1W-low (+ (/ W-high (, (/ 65536 2)))
158                           (% (* W-low 2) 65536))))))
159   (defmacro sha1-S5  (A-high A-low)
160     (` (progn
161          (setq S5A-high (+ (% (* (, A-high) 32) 65536)
162                            (/ (, A-low) (, (/ 65536 32)))))
163          (setq S5A-low  (+ (/ (, A-high) (, (/ 65536 32)))
164                            (% (* (, A-low) 32) 65536))))))
165   (defmacro sha1-S30 (B-high B-low)
166     (` (progn
167          (setq S30B-high (+ (/ (, B-high) 4)
168                             (* (% (, B-low) 4) (, (/ 65536 4)))))
169          (setq S30B-low  (+ (/ (, B-low) 4)
170                             (* (% (, B-high) 4) (, (/ 65536 4))))))))
171
172   (defmacro sha1-OP (round)
173     (` (progn
174          (sha1-S5 sha1-A-high sha1-A-low)
175          (sha1-S30 sha1-B-high sha1-B-low)
176          (setq sha1-A-low (+ ((, (intern (format "sha1-F%d" round)))
177                               sha1-B-low sha1-C-low sha1-D-low)
178                              sha1-E-low
179                              (, (symbol-value
180                                  (intern (format "sha1-K%d-low" round))))
181                              (aref block-low idx)
182                              (progn
183                                (setq sha1-E-low sha1-D-low)
184                                (setq sha1-D-low sha1-C-low)
185                                (setq sha1-C-low S30B-low)
186                                (setq sha1-B-low sha1-A-low)
187                                S5A-low)))
188          (setq carry (/ sha1-A-low 65536))
189          (setq sha1-A-low (% sha1-A-low 65536))
190          (setq sha1-A-high (% (+ ((, (intern (format "sha1-F%d" round)))
191                                   sha1-B-high sha1-C-high sha1-D-high)
192                                  sha1-E-high
193                                  (, (symbol-value
194                                      (intern (format "sha1-K%d-high" round))))
195                                  (aref block-high idx)
196                                  (progn
197                                    (setq sha1-E-high sha1-D-high)
198                                    (setq sha1-D-high sha1-C-high)
199                                    (setq sha1-C-high S30B-high)
200                                    (setq sha1-B-high sha1-A-high)
201                                    S5A-high)
202                                  carry)
203                               65536)))))
204
205   (defmacro sha1-add-to-H (H X)
206     (` (progn
207          (setq (, (intern (format "sha1-%s-low" H)))
208                (+ (, (intern (format "sha1-%s-low" H)))
209                   (, (intern (format "sha1-%s-low" X)))))
210          (setq carry (/ (, (intern (format "sha1-%s-low" H))) 65536))
211          (setq (, (intern (format "sha1-%s-low" H)))
212                (% (, (intern (format "sha1-%s-low" H))) 65536))
213          (setq (, (intern (format "sha1-%s-high" H)))
214                (% (+ (, (intern (format "sha1-%s-high" H)))
215                      (, (intern (format "sha1-%s-high" X)))
216                      carry)
217                   65536)))))
218   )
219
220 ;;; buffers (H0 H1 H2 H3 H4).
221 (defvar sha1-H0-high)
222 (defvar sha1-H0-low)
223 (defvar sha1-H1-high)
224 (defvar sha1-H1-low)
225 (defvar sha1-H2-high)
226 (defvar sha1-H2-low)
227 (defvar sha1-H3-high)
228 (defvar sha1-H3-low)
229 (defvar sha1-H4-high)
230 (defvar sha1-H4-low)
231
232 (defun sha1-block (block-high block-low)
233   (let (;; step (c) --- initialize buffers (A B C D E).
234         (sha1-A-high sha1-H0-high) (sha1-A-low sha1-H0-low)
235         (sha1-B-high sha1-H1-high) (sha1-B-low sha1-H1-low)
236         (sha1-C-high sha1-H2-high) (sha1-C-low sha1-H2-low)
237         (sha1-D-high sha1-H3-high) (sha1-D-low sha1-H3-low)
238         (sha1-E-high sha1-H4-high) (sha1-E-low sha1-H4-low)
239         (idx 16))
240     ;; step (b).
241     (let (;; temporary variables used in sha1-S1 macro.
242           S1W-high S1W-low)
243       (while (< idx 80)
244         (sha1-S1 (logxor (aref block-high (- idx 3))
245                          (aref block-high (- idx 8))
246                          (aref block-high (- idx 14))
247                          (aref block-high (- idx 16)))
248                  (logxor (aref block-low  (- idx 3))
249                          (aref block-low  (- idx 8))
250                          (aref block-low  (- idx 14))
251                          (aref block-low  (- idx 16))))
252         (aset block-high idx S1W-high)
253         (aset block-low  idx S1W-low)
254         (setq idx (1+ idx))))
255     ;; step (d).
256     (setq idx 0)
257     (let (;; temporary variables used in sha1-OP macro.
258           S5A-high S5A-low S30B-high S30B-low carry)
259       (while (< idx 20) (sha1-OP 0) (setq idx (1+ idx)))
260       (while (< idx 40) (sha1-OP 1) (setq idx (1+ idx)))
261       (while (< idx 60) (sha1-OP 2) (setq idx (1+ idx)))
262       (while (< idx 80) (sha1-OP 3) (setq idx (1+ idx))))
263     ;; step (e).
264     (let (;; temporary variables used in sha1-add-to-H macro.
265           carry)
266       (sha1-add-to-H H0 A)
267       (sha1-add-to-H H1 B)
268       (sha1-add-to-H H2 C)
269       (sha1-add-to-H H3 D)
270       (sha1-add-to-H H4 E))))
271
272 (defun sha1-binary (string)
273   "Return the SHA1 of STRING in binary form."
274   (let (;; prepare buffers for a block. byte-length of block is 64.
275         ;; input block is split into two vectors.
276         ;;
277         ;; input block: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ...
278         ;; block-high:  +-0-+       +-1-+       +-2-+       +-3-+
279         ;; block-low:         +-0-+       +-1-+       +-2-+       +-3-+
280         ;;
281         ;; length of each vector is 80, and elements of each vector are
282         ;; 16bit integers.  elements 0x10-0x4F of each vector are
283         ;; assigned later in `sha1-block'.
284         (block-high (eval-when-compile (make-vector 80 nil)))
285         (block-low  (eval-when-compile (make-vector 80 nil))))
286     (unwind-protect
287         (let* (;; byte-length of input string.
288                (len (length string))
289                (lim (* (/ len 64) 64))
290                (rem (% len 4))
291                (idx 0)(pos 0))
292           ;; initialize buffers (H0 H1 H2 H3 H4).
293           (setq sha1-H0-high 26437      ; (string-to-number "6745" 16)
294                 sha1-H0-low  8961       ; (string-to-number "2301" 16)
295                 sha1-H1-high 61389      ; (string-to-number "EFCD" 16)
296                 sha1-H1-low  43913      ; (string-to-number "AB89" 16)
297                 sha1-H2-high 39098      ; (string-to-number "98BA" 16)
298                 sha1-H2-low  56574      ; (string-to-number "DCFE" 16)
299                 sha1-H3-high 4146       ; (string-to-number "1032" 16)
300                 sha1-H3-low  21622      ; (string-to-number "5476" 16)
301                 sha1-H4-high 50130      ; (string-to-number "C3D2" 16)
302                 sha1-H4-low  57840)     ; (string-to-number "E1F0" 16)
303           ;; loop for each 64 bytes block.
304           (while (< pos lim)
305             ;; step (a).
306             (setq idx 0)
307             (while (< idx 16)
308               (aset block-high idx (+ (* (aref string pos) 256)
309                                       (aref string (1+ pos))))
310               (setq pos (+ pos 2))
311               (aset block-low  idx (+ (* (aref string pos) 256)
312                                       (aref string (1+ pos))))
313               (setq pos (+ pos 2))
314               (setq idx (1+ idx)))
315             (sha1-block block-high block-low))
316           ;; last block.
317           (if (prog1
318                   (< (- len lim) 56)
319                 (setq lim (- len rem))
320                 (setq idx 0)
321                 (while (< pos lim)
322                   (aset block-high idx (+ (* (aref string pos) 256)
323                                           (aref string (1+ pos))))
324                   (setq pos (+ pos 2))
325                   (aset block-low  idx (+ (* (aref string pos) 256)
326                                           (aref string (1+ pos))))
327                   (setq pos (+ pos 2))
328                   (setq idx (1+ idx)))
329                 ;; this is the last (at most) 32bit word.
330                 (cond
331                  ((= rem 3)
332                   (aset block-high idx (+ (* (aref string pos) 256)
333                                           (aref string (1+ pos))))
334                   (setq pos (+ pos 2))
335                   (aset block-low  idx (+ (* (aref string pos) 256)
336                                           128)))
337                  ((= rem 2)
338                   (aset block-high idx (+ (* (aref string pos) 256)
339                                           (aref string (1+ pos))))
340                   (aset block-low  idx 32768))
341                  ((= rem 1)
342                   (aset block-high idx (+ (* (aref string pos) 256)
343                                           128))
344                   (aset block-low  idx 0))
345                  (t ;; (= rem 0)
346                   (aset block-high idx 32768)
347                   (aset block-low  idx 0)))
348                 (setq idx (1+ idx))
349                 (while (< idx 16)
350                   (aset block-high idx 0)
351                   (aset block-low  idx 0)
352                   (setq idx (1+ idx))))
353               ;; last block has enough room to write the length of string.
354               (progn
355                 ;; write bit length of string to last 4 bytes of the block.
356                 (aset block-low  15 (* (% len 8192) 8))
357                 (setq len (/ len 8192))
358                 (aset block-high 15 (% len 65536))
359                 ;; XXX: It is not practical to compute SHA1 of
360                 ;;      such a huge message on emacs.
361                 ;; (setq len (/ len 65536))     ; for 64bit emacs.
362                 ;; (aset block-low  14 (% len 65536))
363                 ;; (aset block-high 14 (/ len 65536))
364                 (sha1-block block-high block-low))
365             ;; need one more block.
366             (sha1-block block-high block-low)
367             (fillarray block-high 0)
368             (fillarray block-low  0)
369             ;; write bit length of string to last 4 bytes of the block.
370             (aset block-low  15 (* (% len 8192) 8))
371             (setq len (/ len 8192))
372             (aset block-high 15 (% len 65536))
373             ;; XXX: It is not practical to compute SHA1 of
374             ;;      such a huge message on emacs.
375             ;; (setq len (/ len 65536))         ; for 64bit emacs.
376             ;; (aset block-low  14 (% len 65536))
377             ;; (aset block-high 14 (/ len 65536))
378             (sha1-block block-high block-low))
379           ;; make output string (in binary form).
380           (let ((result (make-string 20 0)))
381             (aset result  0 (/ sha1-H0-high 256))
382             (aset result  1 (% sha1-H0-high 256))
383             (aset result  2 (/ sha1-H0-low  256))
384             (aset result  3 (% sha1-H0-low  256))
385             (aset result  4 (/ sha1-H1-high 256))
386             (aset result  5 (% sha1-H1-high 256))
387             (aset result  6 (/ sha1-H1-low  256))
388             (aset result  7 (% sha1-H1-low  256))
389             (aset result  8 (/ sha1-H2-high 256))
390             (aset result  9 (% sha1-H2-high 256))
391             (aset result 10 (/ sha1-H2-low  256))
392             (aset result 11 (% sha1-H2-low  256))
393             (aset result 12 (/ sha1-H3-high 256))
394             (aset result 13 (% sha1-H3-high 256))
395             (aset result 14 (/ sha1-H3-low  256))
396             (aset result 15 (% sha1-H3-low  256))
397             (aset result 16 (/ sha1-H4-high 256))
398             (aset result 17 (% sha1-H4-high 256))
399             (aset result 18 (/ sha1-H4-low  256))
400             (aset result 19 (% sha1-H4-low  256))
401             result))
402       ;; do not leave a copy of input string.
403       (fillarray block-high nil)
404       (fillarray block-low  nil))))
405
406 (defun sha1-string-internal (string)
407   (encode-hex-string (sha1-binary string)))
408
409 (defun sha1-region-internal (beg end)
410   (sha1-string-internal (buffer-substring-no-properties beg end)))
411
412 ;;;
413 ;;; application interface.
414 ;;;
415
416 (defun sha1-region (beg end)
417   (if (and sha1-use-external
418            sha1-maximum-internal-length
419            (> (abs (- end beg)) sha1-maximum-internal-length))
420       (sha1-region-external beg end)
421     (sha1-region-internal beg end)))
422
423 (defun sha1-string (string)
424   (if (and sha1-use-external
425            sha1-maximum-internal-length
426            (> (length string) sha1-maximum-internal-length))
427       (sha1-string-external string)
428     (sha1-string-internal string)))
429
430 ;;;###autoload
431 (defun sha1 (object &optional beg end)
432   "Return the SHA1 (Secure Hash Algorithm) of an object.
433 OBJECT is either a string or a buffer.
434 Optional arguments BEG and END denote buffer positions for computing the
435 hash of a portion of OBJECT."
436   (if (stringp object)
437       (sha1-string object)
438     (save-excursion
439       (set-buffer object)
440       (sha1-region (or beg (point-min)) (or end (point-max))))))
441
442 (provide 'sha1-el)
443
444 ;;; sha1-el.el ends here