remove old cvs keyword
[md5.git] / md5.lisp
1 ;;;; This file implements The MD5 Message-Digest Algorithm, as defined in
2 ;;;; RFC 1321 by R. Rivest, published April 1992.
3 ;;;;
4 ;;;; It was written by Pierre R. Mai, with copious input from the
5 ;;;; cmucl-help mailing-list hosted at cons.org, in November 2001 and
6 ;;;; has been placed into the public domain.
7 ;;;;
8 ;;;; While the implementation should work on all conforming Common
9 ;;;; Lisp implementations, it has only been optimized for CMU CL,
10 ;;;; where it achieved comparable performance to the standard md5sum
11 ;;;; utility (within a factor of 1.5 or less on iA32 and UltraSparc
12 ;;;; hardware).
13 ;;;;
14 ;;;; Since the implementation makes heavy use of arithmetic on
15 ;;;; (unsigned-byte 32) numbers, acceptable performance is likely only
16 ;;;; on CL implementations that support unboxed arithmetic on such
17 ;;;; numbers in some form.  For other CL implementations a 16bit
18 ;;;; implementation of MD5 is probably more suitable.
19 ;;;;
20 ;;;; The code implements correct operation for files of unbounded size
21 ;;;; as is, at the cost of having to do a single generic integer
22 ;;;; addition for each call to update-md5-state.  If you call
23 ;;;; update-md5-state frequently with little data, this can pose a
24 ;;;; performance problem.  If you can live with a size restriction of
25 ;;;; 512 MB, then you can enable fast fixnum arithmetic by putting
26 ;;;; :md5-small-length onto *features* prior to compiling this file.
27 ;;;;
28 ;;;; Testing code can be compiled by including :md5-testing on
29 ;;;; *features* prior to compilation.  In that case evaluating
30 ;;;; (md5::test-rfc1321) will run all the test-cases present in
31 ;;;; Appendix A.5 of RFC 1321 and report on the results.
32 ;;;; Evaluating (md5::test-other) will run further test-cases
33 ;;;; gathered by the author to cover regressions, etc.
34 ;;;;
35 ;;;; This software is "as is", and has no warranty of any kind.  The
36 ;;;; authors assume no responsibility for the consequences of any use
37 ;;;; of this software.
38
39 (defpackage #:md5 (:use #:cl)
40   (:export
41    ;; Low-Level types and functions
42    #:md5-regs #:initial-md5-regs #:md5regs-digest
43    #:update-md5-block #:fill-block #:fill-block-ub8 #:fill-block-char
44    ;; Mid-Level types and functions
45    #:md5-state #:md5-state-p #:make-md5-state
46    #:update-md5-state #:finalize-md5-state
47    ;; High-Level functions on sequences, streams and files
48    #:md5sum-sequence #:md5sum-stream #:md5sum-file))
49
50 (in-package #:md5)
51
52 #+cmu
53 (eval-when (:compile-toplevel)
54   (defparameter *old-expansion-limit* ext:*inline-expansion-limit*)
55   (setq ext:*inline-expansion-limit* (max ext:*inline-expansion-limit* 1000)))
56
57 #+cmu
58 (eval-when (:compile-toplevel :execute)
59   (defparameter *old-features* *features*)
60   (pushnew (c:backend-byte-order c:*target-backend*) *features*))
61
62 ;;; Section 2:  Basic Datatypes
63
64 #-lispworks
65 (eval-when (:compile-toplevel :load-toplevel :execute)
66   (deftype ub32 ()
67     "Corresponds to the 32bit quantity word of the MD5 Spec"
68     `(unsigned-byte 32)))
69
70 #+lispworks
71 (deftype ub32 ()
72     "Corresponds to the 32bit quantity word of the MD5 Spec"
73     `(unsigned-byte 32))
74
75 (eval-when (:compile-toplevel :load-toplevel :execute)
76   (defmacro assemble-ub32 (a b c d)
77     "Assemble an ub32 value from the given (unsigned-byte 8) values,
78 where a is the intended low-order byte and d the high-order byte."
79     `(the ub32 (logior (ash ,d 24) (ash ,c 16) (ash ,b 8) ,a))))
80
81 ;;; Section 3.4:  Auxilliary functions
82
83 (declaim (inline f g h i)
84          (ftype (function (ub32 ub32 ub32) ub32) f g h i))
85
86 (defun f (x y z)
87   (declare (type ub32 x y z)
88            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
89   #+cmu
90   (kernel:32bit-logical-or (kernel:32bit-logical-and x y)
91                            (kernel:32bit-logical-andc1 x z))
92   #-cmu
93   (logior (logand x y) (logandc1 x z)))
94
95 (defun g (x y z)
96   (declare (type ub32 x y z)
97            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
98   #+cmu
99   (kernel:32bit-logical-or (kernel:32bit-logical-and x z)
100                            (kernel:32bit-logical-andc2 y z))
101   #-cmu
102   (logior (logand x z) (logandc2 y z)))
103
104 (defun h (x y z)
105   (declare (type ub32 x y z)
106            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
107   #+cmu
108   (kernel:32bit-logical-xor x (kernel:32bit-logical-xor y z))
109   #-cmu
110   (logxor x y z))
111
112 (defun i (x y z)
113   (declare (type ub32 x y z)
114            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
115   #+cmu
116   (kernel:32bit-logical-xor y (kernel:32bit-logical-orc2 x z))
117   #-cmu
118   (ldb (byte 32 0) (logxor y (logorc2 x z))))
119
120 (declaim (inline mod32+)
121          (ftype (function (ub32 ub32) ub32) mod32+))
122 (defun mod32+ (a b)
123   (declare (type ub32 a b) (optimize (speed 3) (safety 0) (space 0) (debug 0)))
124   (ldb (byte 32 0) (+ a b)))
125
126 #+cmu
127 (define-compiler-macro mod32+ (a b)
128   `(ext:truly-the ub32 (+ ,a ,b)))
129
130 (declaim (inline rol32)
131          (ftype (function (ub32 (unsigned-byte 5)) ub32) rol32))
132 (defun rol32 (a s)
133   (declare (type ub32 a) (type (unsigned-byte 5) s)
134            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
135   #+cmu
136   (kernel:32bit-logical-or #+little-endian (kernel:shift-towards-end a s)
137                            #+big-endian (kernel:shift-towards-start a s)
138                            (ash a (- s 32)))
139   #-cmu
140   (logior (ldb (byte 32 0) (ash a s)) (ash a (- s 32))))
141
142 ;;; Section 3.4:  Table T
143
144 (eval-when (:compile-toplevel :load-toplevel :execute)
145   (defparameter *t* (make-array 64 :element-type 'ub32
146                                 :initial-contents
147                                 (loop for i from 1 to 64
148                                       collect
149                                       (truncate
150                                        (* 4294967296
151                                           (abs (sin (float i 0.0d0)))))))))
152
153 ;;; Section 3.4:  Helper Macro for single round definitions
154
155 (defmacro with-md5-round ((op block) &rest clauses)
156   (loop for (a b c d k s i) in clauses
157         collect
158         `(setq ,a (mod32+ ,b (rol32 (mod32+ (mod32+ ,a (,op ,b ,c ,d))
159                                             (mod32+ (aref ,block ,k)
160                                                     ,(aref *t* (1- i))))
161                                     ,s)))
162         into result
163         finally
164         (return `(progn ,@result))))
165
166 ;;; Section 3.3:  (Initial) MD5 Working Set
167
168 (deftype md5-regs ()
169   "The working state of the MD5 algorithm, which contains the 4 32-bit
170 registers A, B, C and D."
171   `(simple-array (unsigned-byte 32) (4)))
172
173 (defmacro md5-regs-a (regs)
174   `(aref ,regs 0))
175
176 (defmacro md5-regs-b (regs)
177   `(aref ,regs 1))
178
179 (defmacro md5-regs-c (regs)
180   `(aref ,regs 2))
181
182 (defmacro md5-regs-d (regs)
183   `(aref ,regs 3))
184
185 (defconstant +md5-magic-a+ (assemble-ub32 #x01 #x23 #x45 #x67)
186   "Initial value of Register A of the MD5 working state.")
187 (defconstant +md5-magic-b+ (assemble-ub32 #x89 #xab #xcd #xef)
188   "Initial value of Register B of the MD5 working state.")
189 (defconstant +md5-magic-c+ (assemble-ub32 #xfe #xdc #xba #x98)
190   "Initial value of Register C of the MD5 working state.")
191 (defconstant +md5-magic-d+ (assemble-ub32 #x76 #x54 #x32 #x10)
192   "Initial value of Register D of the MD5 working state.")
193
194 (declaim (inline initial-md5-regs))
195 (defun initial-md5-regs ()
196   "Create the initial working state of an MD5 run."
197   (declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
198   (let ((regs (make-array 4 :element-type '(unsigned-byte 32))))
199     (declare (type md5-regs regs))
200     (setf (md5-regs-a regs) +md5-magic-a+
201           (md5-regs-b regs) +md5-magic-b+
202           (md5-regs-c regs) +md5-magic-c+
203           (md5-regs-d regs) +md5-magic-d+)
204     regs))
205
206 ;;; Section 3.4:  Operation on 16-Word Blocks
207
208 (defun update-md5-block (regs block)
209   "This is the core part of the MD5 algorithm.  It takes a complete 16
210 word block of input, and updates the working state in A, B, C, and D
211 accordingly."
212   (declare (type md5-regs regs)
213            (type (simple-array ub32 (16)) block)
214            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
215   (let ((A (md5-regs-a regs)) (B (md5-regs-b regs))
216         (C (md5-regs-c regs)) (D (md5-regs-d regs)))
217     (declare (type ub32 A B C D))
218     ;; Round 1
219     (with-md5-round (f block)
220       (A B C D  0  7  1)(D A B C  1 12  2)(C D A B  2 17  3)(B C D A  3 22  4)
221       (A B C D  4  7  5)(D A B C  5 12  6)(C D A B  6 17  7)(B C D A  7 22  8)
222       (A B C D  8  7  9)(D A B C  9 12 10)(C D A B 10 17 11)(B C D A 11 22 12)
223       (A B C D 12  7 13)(D A B C 13 12 14)(C D A B 14 17 15)(B C D A 15 22 16))
224     ;; Round 2
225     (with-md5-round (g block)
226       (A B C D  1  5 17)(D A B C  6  9 18)(C D A B 11 14 19)(B C D A  0 20 20)
227       (A B C D  5  5 21)(D A B C 10  9 22)(C D A B 15 14 23)(B C D A  4 20 24)
228       (A B C D  9  5 25)(D A B C 14  9 26)(C D A B  3 14 27)(B C D A  8 20 28)
229       (A B C D 13  5 29)(D A B C  2  9 30)(C D A B  7 14 31)(B C D A 12 20 32))
230     ;; Round 3
231     (with-md5-round (h block)
232       (A B C D  5  4 33)(D A B C  8 11 34)(C D A B 11 16 35)(B C D A 14 23 36)
233       (A B C D  1  4 37)(D A B C  4 11 38)(C D A B  7 16 39)(B C D A 10 23 40)
234       (A B C D 13  4 41)(D A B C  0 11 42)(C D A B  3 16 43)(B C D A  6 23 44)
235       (A B C D  9  4 45)(D A B C 12 11 46)(C D A B 15 16 47)(B C D A  2 23 48))
236     ;; Round 4
237     (with-md5-round (i block)
238       (A B C D  0  6 49)(D A B C  7 10 50)(C D A B 14 15 51)(B C D A  5 21 52)
239       (A B C D 12  6 53)(D A B C  3 10 54)(C D A B 10 15 55)(B C D A  1 21 56)
240       (A B C D  8  6 57)(D A B C 15 10 58)(C D A B  6 15 59)(B C D A 13 21 60)
241       (A B C D  4  6 61)(D A B C 11 10 62)(C D A B  2 15 63)(B C D A  9 21 64))
242     ;; Update and return
243     (setf (md5-regs-a regs) (mod32+ (md5-regs-a regs) A)
244           (md5-regs-b regs) (mod32+ (md5-regs-b regs) B)
245           (md5-regs-c regs) (mod32+ (md5-regs-c regs) C)
246           (md5-regs-d regs) (mod32+ (md5-regs-d regs) D))
247     regs))
248
249 ;;; Section 3.4:  Converting 8bit-vectors into 16-Word Blocks
250
251 (declaim (inline fill-block fill-block-ub8 fill-block-char))
252
253 (defun fill-block-ub8 (block buffer offset)
254   "Convert a complete 64 (unsigned-byte 8) input vector segment
255 starting from offset into the given 16 word MD5 block."
256   (declare (type (integer 0 #.(- most-positive-fixnum 64)) offset)
257            (type (simple-array ub32 (16)) block)
258            (type (simple-array (unsigned-byte 8) (*)) buffer)
259            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
260   #+(and :cmu :little-endian)
261   (kernel:bit-bash-copy
262    buffer (+ (* vm:vector-data-offset vm:word-bits) (* offset vm:byte-bits))
263    block (* vm:vector-data-offset vm:word-bits)
264    (* 64 vm:byte-bits))
265   #-(and :cmu :little-endian)
266   (loop for i of-type (integer 0 16) from 0
267         for j of-type (integer 0 #.most-positive-fixnum)
268         from offset to (+ offset 63) by 4
269         do
270         (setf (aref block i)
271               (assemble-ub32 (aref buffer j)
272                              (aref buffer (+ j 1))
273                              (aref buffer (+ j 2))
274                              (aref buffer (+ j 3))))))
275
276 (defun fill-block-char (block buffer offset)
277   "Convert a complete 64 character input string segment starting from
278 offset into the given 16 word MD5 block."
279   (declare (type (integer 0 #.(- most-positive-fixnum 64)) offset)
280            (type (simple-array ub32 (16)) block)
281            (type simple-string buffer)
282            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
283   #+(and :cmu :little-endian)
284   (kernel:bit-bash-copy
285    buffer (+ (* vm:vector-data-offset vm:word-bits) (* offset vm:byte-bits))
286    block (* vm:vector-data-offset vm:word-bits)
287    (* 64 vm:byte-bits))
288   #-(and :cmu :little-endian)
289   (loop for i of-type (integer 0 16) from 0
290         for j of-type (integer 0 #.most-positive-fixnum)
291         from offset to (+ offset 63) by 4
292         do
293         (setf (aref block i)
294               (assemble-ub32 (char-code (schar buffer j))
295                              (char-code (schar buffer (+ j 1)))
296                              (char-code (schar buffer (+ j 2)))
297                              (char-code (schar buffer (+ j 3)))))))
298
299 (defun fill-block (block buffer offset)
300   "Convert a complete 64 byte input vector segment into the given 16
301 word MD5 block.  This currently works on (unsigned-byte 8) and
302 character simple-arrays, via the functions `fill-block-ub8' and
303 `fill-block-char' respectively."
304   (declare (type (integer 0 #.(- most-positive-fixnum 64)) offset)
305            (type (simple-array ub32 (16)) block)
306            (type (simple-array * (*)) buffer)
307            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
308   (etypecase buffer
309     ((simple-array (unsigned-byte 8) (*))
310      (fill-block-ub8 block buffer offset))
311     (simple-string
312      (fill-block-char block buffer offset))))
313
314 ;;; Section 3.5:  Message Digest Output
315
316 (declaim (inline md5regs-digest))
317 (defun md5regs-digest (regs)
318   "Create the final 16 byte message-digest from the MD5 working state
319 in regs.  Returns a (simple-array (unsigned-byte 8) (16))."
320   (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
321            (type md5-regs regs))
322   (let ((result (make-array 16 :element-type '(unsigned-byte 8))))
323     (declare (type (simple-array (unsigned-byte 8) (16)) result))
324     (macrolet ((frob (reg offset)
325                  (let ((var (gensym)))
326                    `(let ((,var ,reg))
327                       (declare (type ub32 ,var))
328                       (setf
329                        (aref result ,offset) (ldb (byte 8 0) ,var)
330                        (aref result ,(+ offset 1)) (ldb (byte 8 8) ,var)
331                        (aref result ,(+ offset 2)) (ldb (byte 8 16) ,var)
332                        (aref result ,(+ offset 3)) (ldb (byte 8 24) ,var))))))
333       (frob (md5-regs-a regs) 0)
334       (frob (md5-regs-b regs) 4)
335       (frob (md5-regs-c regs) 8)
336       (frob (md5-regs-d regs) 12))
337     result))
338
339 ;;; Mid-Level Drivers
340
341 (defstruct (md5-state
342              (:constructor make-md5-state ())
343              (:copier))
344   (regs (initial-md5-regs) :type md5-regs :read-only t)
345   (amount 0 :type
346           #-md5-small-length (integer 0 *)
347           #+md5-small-length (unsigned-byte 29))
348   (block (make-array 16 :element-type '(unsigned-byte 32)) :read-only t
349          :type (simple-array (unsigned-byte 32) (16)))
350   (buffer (make-array 64 :element-type '(unsigned-byte 8)) :read-only t
351          :type (simple-array (unsigned-byte 8) (64)))
352   (buffer-index 0 :type (integer 0 63))
353   (finalized-p nil))
354
355 (declaim (inline copy-to-buffer))
356 (defun copy-to-buffer (from from-offset count buffer buffer-offset)
357   "Copy a partial segment from input vector from starting at
358 from-offset and copying count elements into the 64 byte buffer
359 starting at buffer-offset."
360   (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
361            (type (unsigned-byte 29) from-offset)
362            (type (integer 0 63) count buffer-offset)
363            (type (simple-array * (*)) from)
364            (type (simple-array (unsigned-byte 8) (64)) buffer))
365   #+cmu
366   (kernel:bit-bash-copy
367    from (+ (* vm:vector-data-offset vm:word-bits) (* from-offset vm:byte-bits))
368    buffer (+ (* vm:vector-data-offset vm:word-bits)
369              (* buffer-offset vm:byte-bits))
370    (* count vm:byte-bits))
371   #-cmu
372   (etypecase from
373     (simple-string
374      (loop for buffer-index of-type (integer 0 64) from buffer-offset
375            for from-index of-type fixnum from from-offset
376            below (+ from-offset count)
377            do
378            (setf (aref buffer buffer-index)
379                  (char-code (schar (the simple-string from) from-index)))))
380     ((simple-array (unsigned-byte 8) (*))
381      (loop for buffer-index of-type (integer 0 64) from buffer-offset
382            for from-index of-type fixnum from from-offset
383            below (+ from-offset count)
384            do
385            (setf (aref buffer buffer-index)
386                  (aref (the (simple-array (unsigned-byte 8) (*)) from)
387                        from-index))))))
388
389 (defun update-md5-state (state sequence &key (start 0) (end (length sequence)))
390   "Update the given md5-state from sequence, which is either a
391 simple-string or a simple-array with element-type (unsigned-byte 8),
392 bounded by start and end, which must be numeric bounding-indices."
393   (declare (type md5-state state)
394            (type (simple-array * (*)) sequence)
395            (type fixnum start end)
396            (optimize (speed 3) #+cmu (safety 0) (space 0) (debug 0))
397            #+cmu
398            (ext:optimize-interface (safety 1) (debug 1)))
399   (let ((regs (md5-state-regs state))
400         (block (md5-state-block state))
401         (buffer (md5-state-buffer state)))
402     (declare (type md5-regs regs)
403              (type (simple-array (unsigned-byte 32) (16)) block)
404              (type (simple-array (unsigned-byte 8) (64)) buffer))
405     ;; Handle old rest
406     (unless (zerop (md5-state-buffer-index state))
407       (let* ((buffer-index (md5-state-buffer-index state))
408              (remainder (- 64 buffer-index))
409              (length (- end start))
410              (amount (min remainder length)))
411         (declare (type (integer 0 63) buffer-index remainder amount)
412                  (type fixnum length))
413         (copy-to-buffer sequence start amount buffer buffer-index)
414         (setf (md5-state-amount state)
415               #-md5-small-length (+ (md5-state-amount state) amount)
416               #+md5-small-length (the (unsigned-byte 29)
417                                       (+ (md5-state-amount state) amount)))
418         (setq start (the fixnum (+ start amount)))
419         (if (< length remainder)
420             (setf (md5-state-buffer-index state)
421                   (the (integer 0 63) (+ buffer-index amount)))
422           (progn
423             (fill-block-ub8 block buffer 0)
424             (update-md5-block regs block)
425             (setf (md5-state-buffer-index state) 0)))))
426     ;; Leave when nothing to do
427     (when (>= start end)
428       (return-from update-md5-state state))
429     ;; Handle main-part and new-rest
430     (etypecase sequence
431       ((simple-array (unsigned-byte 8) (*))
432        (locally
433            (declare (type (simple-array (unsigned-byte 8) (*)) sequence))
434          (loop for offset of-type (unsigned-byte 29) from start below end by 64
435                until (< (- end offset) 64)
436                do
437                (fill-block-ub8 block sequence offset)
438                (update-md5-block regs block)
439                finally
440                (let ((amount (- end offset)))
441                  (unless (zerop amount)
442                    (copy-to-buffer sequence offset amount buffer 0))
443                  (setf (md5-state-buffer-index state) amount)))))
444       (simple-string
445        (locally
446            (declare (type simple-string sequence))
447          (loop for offset of-type (unsigned-byte 29) from start below end by 64
448                until (< (- end offset) 64)
449                do
450                (fill-block-char block sequence offset)
451                (update-md5-block regs block)
452                finally
453                (let ((amount (- end offset)))
454                  (unless (zerop amount)
455                    (copy-to-buffer sequence offset amount buffer 0))
456                  (setf (md5-state-buffer-index state) amount))))))
457     (setf (md5-state-amount state)
458           #-md5-small-length (+ (md5-state-amount state)
459                                 (the fixnum (- end start)))
460           #+md5-small-length (the (unsigned-byte 29)
461                                (+ (md5-state-amount state)
462                                   (the fixnum (- end start)))))
463     state))
464
465 (defun finalize-md5-state (state)
466   "If the given md5-state has not already been finalized, finalize it,
467 by processing any remaining input in its buffer, with suitable padding
468 and appended bit-length, as specified by the MD5 standard.
469
470 The resulting MD5 message-digest is returned as an array of sixteen
471 (unsigned-byte 8) values.  Calling `update-md5-state' after a call to
472 `finalize-md5-state' results in unspecified behaviour."
473   (declare (type md5-state state)
474            (optimize (speed 3) #+cmu (safety 0) (space 0) (debug 0))
475            #+cmu
476            (ext:optimize-interface (safety 1) (debug 1)))
477   (or (md5-state-finalized-p state)
478       (let ((regs (md5-state-regs state))
479             (block (md5-state-block state))
480             (buffer (md5-state-buffer state))
481             (buffer-index (md5-state-buffer-index state))
482             (total-length (* 8 (md5-state-amount state))))
483         (declare (type md5-regs regs)
484                  (type (integer 0 63) buffer-index)
485                  (type (simple-array ub32 (16)) block)
486                  (type (simple-array (unsigned-byte 8) (*)) buffer))
487         ;; Add mandatory bit 1 padding
488         (setf (aref buffer buffer-index) #x80)
489         ;; Fill with 0 bit padding
490         (loop for index of-type (integer 0 64)
491               from (1+ buffer-index) below 64
492               do (setf (aref buffer index) #x00))
493         (fill-block-ub8 block buffer 0)
494         ;; Flush block first if length wouldn't fit
495         (when (>= buffer-index 56)
496           (update-md5-block regs block)
497           ;; Create new fully 0 padded block
498           (loop for index of-type (integer 0 16) from 0 below 16
499                 do (setf (aref block index) #x00000000)))
500         ;; Add 64bit message bit length
501         (setf (aref block 14) (ldb (byte 32 0) total-length))
502         #-md5-small-length
503         (setf (aref block 15) (ldb (byte 32 32) total-length))
504         ;; Flush last block
505         (update-md5-block regs block)
506         ;; Done, remember digest for later calls
507         (setf (md5-state-finalized-p state)
508               (md5regs-digest regs)))))
509
510 ;;; High-Level Drivers
511
512 (defun md5sum-sequence (sequence &key (start 0) end)
513   "Calculate the MD5 message-digest of data in sequence.  On CMU CL
514 this works for all sequences whose element-type is supported by the
515 underlying MD5 routines, on other implementations it only works for 1d
516 simple-arrays with such element types."
517   (declare (optimize (speed 3) (space 0) (debug 0))
518            (type vector sequence) (type fixnum start))
519   (let ((state (make-md5-state)))
520     (declare (type md5-state state))
521     #+cmu
522     (lisp::with-array-data ((data sequence) (real-start start) (real-end end))
523       (update-md5-state state data :start real-start :end real-end))
524     #-cmu
525     (let ((real-end (or end (length sequence))))
526       (declare (type fixnum real-end))
527       (update-md5-state state sequence :start start :end real-end))
528     (finalize-md5-state state)))
529
530 (eval-when (:compile-toplevel :load-toplevel :execute)
531   (defconstant +buffer-size+ (* 128 1024)
532     "Size of internal buffer to use for md5sum-stream and md5sum-file
533 operations.  This should be a multiple of 64, the MD5 block size."))
534
535 (deftype buffer-index () `(integer 0 ,+buffer-size+))
536
537 (defun md5sum-stream (stream)
538   "Calculate an MD5 message-digest of the contents of stream.  Its
539 element-type has to be either (unsigned-byte 8) or character."
540   (declare (optimize (speed 3) (space 0) (debug 0)))
541   (let ((state (make-md5-state)))
542     (declare (type md5-state state))
543     (cond
544       ((equal (stream-element-type stream) '(unsigned-byte 8))
545        (let ((buffer (make-array +buffer-size+
546                                  :element-type '(unsigned-byte 8))))
547          (declare (type (simple-array (unsigned-byte 8) (#.+buffer-size+))
548                         buffer))
549          (loop for bytes of-type buffer-index = (read-sequence buffer stream)
550                do (update-md5-state state buffer :end bytes)
551                until (< bytes +buffer-size+)
552                finally
553                (return (finalize-md5-state state)))))
554       ((equal (stream-element-type stream) 'character)
555        (let ((buffer (make-string +buffer-size+)))
556          (declare (type (simple-string #.+buffer-size+) buffer))
557          (loop for bytes of-type buffer-index = (read-sequence buffer stream)
558                do (update-md5-state state buffer :end bytes)
559                until (< bytes +buffer-size+)
560                finally
561                (return (finalize-md5-state state)))))
562       (t
563        (error "Unsupported stream element-type ~S for stream ~S."
564               (stream-element-type stream) stream)))))
565
566 (defun md5sum-file (pathname)
567   "Calculate the MD5 message-digest of the file specified by pathname."
568   (declare (optimize (speed 3) (space 0) (debug 0)))
569   (with-open-file (stream pathname :element-type '(unsigned-byte 8))
570     (md5sum-stream stream)))
571
572 #+md5-testing
573 (defconstant +rfc1321-testsuite+
574   '(("" . "d41d8cd98f00b204e9800998ecf8427e")
575     ("a" ."0cc175b9c0f1b6a831c399e269772661")
576     ("abc" . "900150983cd24fb0d6963f7d28e17f72")
577     ("message digest" . "f96b697d7cb7938d525a2f31aaf161d0")
578     ("abcdefghijklmnopqrstuvwxyz" . "c3fcd3d76192e4007dfb496cca67e13b")
579     ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" .
580      "d174ab98d277d9f5a5611c2c9f419d9f")
581     ("12345678901234567890123456789012345678901234567890123456789012345678901234567890" .
582      "57edf4a22be3c955ac49da2e2107b67a"))
583   "AList of test input strings and stringified message-digests
584 according to the test suite in Appendix A.5 of RFC 1321")
585
586 #+md5-testing
587 (defconstant +other-testsuite+
588   '(;; From padding bug report by Edi Weitz
589     ("1631901HERR BUCHHEISTERCITROEN NORD1043360796beckenbauer" .
590      "d734945e5930bb28859ccd13c830358b")
591     ;; Test padding for strings from 0 to 69*8 bits in size.
592     ("" . "d41d8cd98f00b204e9800998ecf8427e")
593     ("a" . "0cc175b9c0f1b6a831c399e269772661")
594     ("aa" . "4124bc0a9335c27f086f24ba207a4912")
595     ("aaa" . "47bce5c74f589f4867dbd57e9ca9f808")
596     ("aaaa" . "74b87337454200d4d33f80c4663dc5e5")
597     ("aaaaa" . "594f803b380a41396ed63dca39503542")
598     ("aaaaaa" . "0b4e7a0e5fe84ad35fb5f95b9ceeac79")
599     ("aaaaaaa" . "5d793fc5b00a2348c3fb9ab59e5ca98a")
600     ("aaaaaaaa" . "3dbe00a167653a1aaee01d93e77e730e")
601     ("aaaaaaaaa" . "552e6a97297c53e592208cf97fbb3b60")
602     ("aaaaaaaaaa" . "e09c80c42fda55f9d992e59ca6b3307d")
603     ("aaaaaaaaaaa" . "d57f21e6a273781dbf8b7657940f3b03")
604     ("aaaaaaaaaaaa" . "45e4812014d83dde5666ebdf5a8ed1ed")
605     ("aaaaaaaaaaaaa" . "c162de19c4c3731ca3428769d0cd593d")
606     ("aaaaaaaaaaaaaa" . "451599a5f9afa91a0f2097040a796f3d")
607     ("aaaaaaaaaaaaaaa" . "12f9cf6998d52dbe773b06f848bb3608")
608     ("aaaaaaaaaaaaaaaa" . "23ca472302f49b3ea5592b146a312da0")
609     ("aaaaaaaaaaaaaaaaa" . "88e42e96cc71151b6e1938a1699b0a27")
610     ("aaaaaaaaaaaaaaaaaa" . "2c60c24e7087e18e45055a33f9a5be91")
611     ("aaaaaaaaaaaaaaaaaaa" . "639d76897485360b3147e66e0a8a3d6c")
612     ("aaaaaaaaaaaaaaaaaaaa" . "22d42eb002cefa81e9ad604ea57bc01d")
613     ("aaaaaaaaaaaaaaaaaaaaa" . "bd049f221af82804c5a2826809337c9b")
614     ("aaaaaaaaaaaaaaaaaaaaaa" . "ff49cfac3968dbce26ebe7d4823e58bd")
615     ("aaaaaaaaaaaaaaaaaaaaaaa" . "d95dbfee231e34cccb8c04444412ed7d")
616     ("aaaaaaaaaaaaaaaaaaaaaaaa" . "40edae4bad0e5bf6d6c2dc5615a86afb")
617     ("aaaaaaaaaaaaaaaaaaaaaaaaa" . "a5a8bfa3962f49330227955e24a2e67c")
618     ("aaaaaaaaaaaaaaaaaaaaaaaaaa" . "ae791f19bdf77357ff10bb6b0e97e121")
619     ("aaaaaaaaaaaaaaaaaaaaaaaaaaa" . "aaab9c59a88bf0bdfcb170546c5459d6")
620     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaa" . "b0f0545856af1a340acdedce23c54b97")
621     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa" . "f7ce3d7d44f3342107d884bfa90c966a")
622     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" . "59e794d45697b360e18ba972bada0123")
623     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" . "3b0845db57c200be6052466f87b2198a")
624     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" . "5eca9bd3eb07c006cd43ae48dfde7fd3")
625     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" . "b4f13cb081e412f44e99742cb128a1a5")
626     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" . "4c660346451b8cf91ef50f4634458d41")
627     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
628      "11db24dc3f6c2145701db08625dd6d76")
629     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
630      "80dad3aad8584778352c68ab06250327")
631     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
632      "1227fe415e79db47285cb2689c93963f")
633     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
634      "8e084f489f1bdf08c39f98ff6447ce6d")
635     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
636      "08b2f2b0864bac1ba1585043362cbec9")
637     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
638      "4697843037d962f62a5a429e611e0f5f")
639     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
640      "10c4da18575c092b486f8ab96c01c02f")
641     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
642      "af205d729450b663f48b11d839a1c8df")
643     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
644      "0d3f91798fac6ee279ec2485b25f1124")
645     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
646      "4c3c7c067634daec9716a80ea886d123")
647     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
648      "d1e358e6e3b707282cdd06e919f7e08c")
649     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
650      "8c6ded4f0af86e0a7e301f8a716c4363")
651     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
652      "4c2d8bcb02d982d7cb77f649c0a2dea8")
653     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
654      "bdb662f765cd310f2a547cab1cfecef6")
655     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
656      "08ff5f7301d30200ab89169f6afdb7af")
657     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
658      "6eb6a030bcce166534b95bc2ab45d9cf")
659     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
660      "1bb77918e5695c944be02c16ae29b25e")
661     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
662      "b6fe77c19f0f0f4946c761d62585bfea")
663     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
664      "e9e7e260dce84ffa6e0e7eb5fd9d37fc")
665     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
666      "eced9e0b81ef2bba605cbc5e2e76a1d0")
667     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
668      "ef1772b6dff9a122358552954ad0df65")
669     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
670      "3b0c8ac703f828b04c6c197006d17218")
671     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
672      "652b906d60af96844ebd21b674f35e93")
673     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
674      "dc2f2f2462a0d72358b2f99389458606")
675     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
676      "762fc2665994b217c52c3c2eb7d9f406")
677     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
678      "cc7ed669cf88f201c3297c6a91e1d18d")
679     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
680      "cced11f7bbbffea2f718903216643648")
681     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
682      "24612f0ce2c9d2cf2b022ef1e027a54f")
683     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
684      "b06521f39153d618550606be297466d5")
685     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
686      "014842d480b571495a4a0363793f7367")
687     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
688      "c743a45e0d2e6a95cb859adae0248435")
689     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
690      "def5d97e01e1219fb2fc8da6c4d6ba2f")
691     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
692      "92cb737f8687ccb93022fdb411a77cca")
693     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
694      "a0d1395c7fb36247bfe2d49376d9d133")
695     ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
696      "ab75504250558b788f99d1ebd219abf2"))
697   "AList of test input strings and stringified message-digests
698 according to my additional test suite")
699
700 #+md5-testing
701 (defun test-with-testsuite (testsuite)
702   (loop for count from 1
703         for (source . md5-string) in testsuite
704         for md5-digest = (md5sum-sequence source)
705         for md5-result-string = (format nil "~(~{~2,'0X~}~)"
706                                         (map 'list #'identity md5-digest))
707         do
708         (format
709          *trace-output*
710          "~2&Test-Case ~D:~%  Input: ~S~%  Required: ~A~%  Returned: ~A~%"
711          count source md5-string md5-result-string)
712         when (string= md5-string md5-result-string)
713         do (format *trace-output* "  OK~%")
714         else
715         count 1 into failed
716         and do (format *trace-output* "  FAILED~%")
717         finally
718         (format *trace-output*
719                 "~2&~[All ~D test cases succeeded~:;~:*~D of ~D test cases failed~].~%"
720                 failed (1- count))
721         (return (zerop failed))))
722
723 #+md5-testing
724 (defun test-rfc1321 ()
725   (test-with-testsuite +rfc1321-testsuite+))
726
727 #+md5-testing
728 (defun test-other ()
729   (test-with-testsuite +other-testsuite+))
730
731 #+cmu
732 (eval-when (:compile-toplevel :execute)
733   (setq *features* *old-features*))
734
735 #+cmu
736 (eval-when (:compile-toplevel)
737   (setq ext:*inline-expansion-limit* *old-expansion-limit*))