r3383: *** empty log message ***
[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 ;;;; $Id: md5.lisp,v 1.2 2002/11/11 11:17:56 kevin Exp $
9 ;;;;
10 ;;;; While the implementation should work on all conforming Common
11 ;;;; Lisp implementations, it has only been optimized for CMU CL,
12 ;;;; where it achieved comparable performance to the standard md5sum
13 ;;;; utility (within a factor of 1.5 or less on iA32 and UltraSparc
14 ;;;; hardware).
15 ;;;;
16 ;;;; Since the implementation makes heavy use of arithmetic on
17 ;;;; (unsigned-byte 32) numbers, acceptable performance is likely only
18 ;;;; on CL implementations that support unboxed arithmetic on such
19 ;;;; numbers in some form.  For other CL implementations a 16bit
20 ;;;; implementation of MD5 is probably more suitable.
21 ;;;;
22 ;;;; The code implements correct operation for files of unbounded size
23 ;;;; as is, at the cost of having to do a single generic integer
24 ;;;; addition for each call to update-md5-state.  If you call
25 ;;;; update-md5-state frequently with little data, this can pose a
26 ;;;; performance problem.  If you can live with a size restriction of
27 ;;;; 512 MB, then you can enable fast fixnum arithmetic by putting
28 ;;;; :md5-small-length onto *features* prior to compiling this file.
29 ;;;;
30 ;;;; Testing code can be compiled by including :md5-testing on
31 ;;;; *features* prior to compilation.  In that case evaluating
32 ;;;; (md5::test-rfc1321) will run all the test-cases present in
33 ;;;; Appendix A.5 of RFC 1321 and report on the results.
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 (eval-when (:compile-toplevel :load-toplevel :execute)
65 (deftype ub32 ()
66   "Corresponds to the 32bit quantity word of the MD5 Spec"
67   `(unsigned-byte 32)))
68
69 (defmacro assemble-ub32 (a b c d)
70   "Assemble an ub32 value from the given (unsigned-byte 8) values,
71 where a is the intended low-order byte and d the high-order byte."
72   `(the ub32 (logior (ash ,d 24) (ash ,c 16) (ash ,b 8) ,a)))
73
74 ;;; Section 3.4:  Auxilliary functions
75
76 (declaim (inline f g h i)
77          (ftype (function (ub32 ub32 ub32) ub32) f g h i))
78
79 (defun f (x y z)
80   (declare (type ub32 x y z)
81            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
82   #+cmu
83   (kernel:32bit-logical-or (kernel:32bit-logical-and x y)
84                            (kernel:32bit-logical-andc1 x z))
85   #-cmu
86   (logior (logand x y) (logandc1 x z)))
87
88 (defun g (x y z)
89   (declare (type ub32 x y z)
90            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
91   #+cmu
92   (kernel:32bit-logical-or (kernel:32bit-logical-and x z)
93                            (kernel:32bit-logical-andc2 y z))
94   #-cmu
95   (logior (logand x z) (logandc2 y z)))
96
97 (defun h (x y z)
98   (declare (type ub32 x y z)
99            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
100   #+cmu
101   (kernel:32bit-logical-xor x (kernel:32bit-logical-xor y z))
102   #-cmu
103   (logxor x y z))
104
105 (defun i (x y z)
106   (declare (type ub32 x y z)
107            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
108   #+cmu
109   (kernel:32bit-logical-xor y (kernel:32bit-logical-orc2 x z))
110   #-cmu
111   (logxor y (logorc2 x z)))
112
113 (declaim (inline mod32+)
114          (ftype (function (ub32 ub32) ub32) mod32+))
115 (defun mod32+ (a b)
116   (declare (type ub32 a b) (optimize (speed 3) (safety 0) (space 0) (debug 0)))
117   (ldb (byte 32 0) (+ a b)))
118
119 #+cmu
120 (define-compiler-macro mod32+ (a b)
121   `(ext:truly-the ub32 (+ ,a ,b)))
122
123 (declaim (inline rol32)
124          (ftype (function (ub32 (unsigned-byte 5)) ub32) rol32))
125 (defun rol32 (a s)
126   (declare (type ub32 a) (type (unsigned-byte 5) s)
127            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
128   #+cmu
129   (kernel:32bit-logical-or #+little-endian (kernel:shift-towards-end a s)
130                            #+big-endian (kernel:shift-towards-start a s)
131                            (ash a (- s 32)))
132   #-cmu
133   (logior (ldb (byte 32 0) (ash a s)) (ash a (- s 32))))
134
135 ;;; Section 3.4:  Table T
136
137 (eval-when (:compile-toplevel :load-toplevel :execute)
138   (defparameter *t* (make-array 64 :element-type 'ub32
139                                 :initial-contents
140                                 (loop for i from 1 to 64
141                                       collect
142                                       (truncate
143                                        (* 4294967296
144                                           (abs (sin (float i 0.0d0)))))))))
145
146 ;;; Section 3.4:  Helper Macro for single round definitions
147
148 (defmacro with-md5-round ((op block) &rest clauses)
149   (loop for (a b c d k s i) in clauses
150         collect
151         `(setq ,a (mod32+ ,b (rol32 (mod32+ (mod32+ ,a (,op ,b ,c ,d))
152                                             (mod32+ (aref ,block ,k)
153                                                     ,(aref *t* (1- i))))
154                                     ,s)))
155         into result
156         finally
157         (return `(progn ,@result))))
158
159 ;;; Section 3.3:  (Initial) MD5 Working Set
160
161 (deftype md5-regs ()
162   "The working state of the MD5 algorithm, which contains the 4 32-bit
163 registers A, B, C and D."
164   `(simple-array (unsigned-byte 32) (4)))
165
166 (defmacro md5-regs-a (regs)
167   `(aref ,regs 0))
168
169 (defmacro md5-regs-b (regs)
170   `(aref ,regs 1))
171
172 (defmacro md5-regs-c (regs)
173   `(aref ,regs 2))
174
175 (defmacro md5-regs-d (regs)
176   `(aref ,regs 3))
177
178 (defconstant +md5-magic-a+ (assemble-ub32 #x01 #x23 #x45 #x67)
179   "Initial value of Register A of the MD5 working state.")
180 (defconstant +md5-magic-b+ (assemble-ub32 #x89 #xab #xcd #xef)
181   "Initial value of Register B of the MD5 working state.")
182 (defconstant +md5-magic-c+ (assemble-ub32 #xfe #xdc #xba #x98)
183   "Initial value of Register C of the MD5 working state.")
184 (defconstant +md5-magic-d+ (assemble-ub32 #x76 #x54 #x32 #x10)
185   "Initial value of Register D of the MD5 working state.")
186
187 (declaim (inline initial-md5-regs))
188 (defun initial-md5-regs ()
189   "Create the initial working state of an MD5 run."
190   (declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
191   (let ((regs (make-array 4 :element-type '(unsigned-byte 32))))
192     (declare (type md5-regs regs))
193     (setf (md5-regs-a regs) +md5-magic-a+
194           (md5-regs-b regs) +md5-magic-b+
195           (md5-regs-c regs) +md5-magic-c+
196           (md5-regs-d regs) +md5-magic-d+)
197     regs))
198
199 ;;; Section 3.4:  Operation on 16-Word Blocks
200
201 (defun update-md5-block (regs block)
202   "This is the core part of the MD5 algorithm.  It takes a complete 16
203 word block of input, and updates the working state in A, B, C, and D
204 accordingly."
205   (declare (type md5-regs regs)
206            (type (simple-array ub32 (16)) block)
207            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
208   (let ((a (md5-regs-a regs)) (b (md5-regs-b regs))
209         (c (md5-regs-c regs)) (d (md5-regs-d regs)))
210     (declare (type ub32 a b c d))
211     ;; Round 1
212     (with-md5-round (f block)
213       (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)
214       (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)
215       (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)
216       (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))
217     ;; Round 2
218     (with-md5-round (g block)
219       (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)
220       (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)
221       (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)
222       (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))
223     ;; Round 3
224     (with-md5-round (h block)
225       (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)
226       (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)
227       (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)
228       (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))
229     ;; Round 4
230     (with-md5-round (i block)
231       (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)
232       (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)
233       (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)
234       (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))
235     ;; Update and return
236     (setf (md5-regs-a regs) (mod32+ (md5-regs-a regs) a)
237           (md5-regs-b regs) (mod32+ (md5-regs-b regs) b)
238           (md5-regs-c regs) (mod32+ (md5-regs-c regs) c)
239           (md5-regs-d regs) (mod32+ (md5-regs-d regs) d))
240     regs))
241
242 ;;; Section 3.4:  Converting 8bit-vectors into 16-Word Blocks
243
244 (declaim (inline fill-block fill-block-ub8 fill-block-char))
245 (defun fill-block (block buffer offset)
246   "Convert a complete 64 byte input vector segment into the given 16
247 word MD5 block.  This currently works on (unsigned-byte 8) and
248 character simple-arrays, via the functions `fill-block-ub8' and
249 `fill-block-char' respectively."
250   (declare (type (integer 0 #.(- most-positive-fixnum 64)) offset)
251            (type (simple-array ub32 (16)) block)
252            (type (simple-array * (*)) buffer)
253            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
254   (etypecase buffer
255     ((simple-array (unsigned-byte 8) (*))
256      (fill-block-ub8 block buffer offset))
257     (simple-string
258      (fill-block-char block buffer offset))))
259
260 (defun fill-block-ub8 (block buffer offset)
261   "Convert a complete 64 (unsigned-byte 8) input vector segment
262 starting from offset into the given 16 word MD5 block."
263   (declare (type (integer 0 #.(- most-positive-fixnum 64)) offset)
264            (type (simple-array ub32 (16)) block)
265            (type (simple-array (unsigned-byte 8) (*)) buffer)
266            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
267   #+(and :cmu :little-endian)
268   (kernel:bit-bash-copy
269    buffer (+ (* vm:vector-data-offset vm:word-bits) (* offset vm:byte-bits))
270    block (* vm:vector-data-offset vm:word-bits)
271    (* 64 vm:byte-bits))
272   #-(and :cmu :little-endian)
273   (loop for i of-type (integer 0 16) from 0
274         for j of-type (integer 0 #.most-positive-fixnum)
275         from offset to (+ offset 63) by 4
276         do
277         (setf (aref block i)
278               (assemble-ub32 (aref buffer j)
279                              (aref buffer (+ j 1))
280                              (aref buffer (+ j 2))
281                              (aref buffer (+ j 3))))))
282
283 (defun fill-block-char (block buffer offset)
284   "Convert a complete 64 character input string segment starting from
285 offset into the given 16 word MD5 block."
286   (declare (type (integer 0 #.(- most-positive-fixnum 64)) offset)
287            (type (simple-array ub32 (16)) block)
288            (type simple-string buffer)
289            (optimize (speed 3) (safety 0) (space 0) (debug 0)))
290   #+(and :cmu :little-endian)
291   (kernel:bit-bash-copy
292    buffer (+ (* vm:vector-data-offset vm:word-bits) (* offset vm:byte-bits))
293    block (* vm:vector-data-offset vm:word-bits)
294    (* 64 vm:byte-bits))
295   #-(and :cmu :little-endian)
296   (loop for i of-type (integer 0 16) from 0
297         for j of-type (integer 0 #.most-positive-fixnum)
298         from offset to (+ offset 63) by 4
299         do
300         (setf (aref block i)
301               (assemble-ub32 (char-code (schar buffer j))
302                              (char-code (schar buffer (+ j 1)))
303                              (char-code (schar buffer (+ j 2)))
304                              (char-code (schar buffer (+ j 3)))))))
305
306 ;;; Section 3.5:  Message Digest Output
307
308 (declaim (inline md5regs-digest))
309 (defun md5regs-digest (regs)
310   "Create the final 16 byte message-digest from the MD5 working state
311 in regs.  Returns a (simple-array (unsigned-byte 8) (16))."
312   (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
313            (type md5-regs regs))
314   (let ((result (make-array 16 :element-type '(unsigned-byte 8))))
315     (declare (type (simple-array (unsigned-byte 8) (16)) result))
316     (macrolet ((frob (reg offset)
317                  (let ((var (gensym)))
318                    `(let ((,var ,reg))
319                       (declare (type ub32 ,var))
320                       (setf
321                        (aref result ,offset) (ldb (byte 8 0) ,var)
322                        (aref result ,(+ offset 1)) (ldb (byte 8 8) ,var)
323                        (aref result ,(+ offset 2)) (ldb (byte 8 16) ,var)
324                        (aref result ,(+ offset 3)) (ldb (byte 8 24) ,var))))))
325       (frob (md5-regs-a regs) 0)
326       (frob (md5-regs-b regs) 4)
327       (frob (md5-regs-c regs) 8)
328       (frob (md5-regs-d regs) 12))
329     result))
330
331 ;;; Mid-Level Drivers
332
333 (defstruct (md5-state
334              (:constructor make-md5-state ())
335              (:copier))
336   (regs (initial-md5-regs) :type md5-regs :read-only t)
337   (amount 0 :type
338           #-md5-small-length (integer 0 *)
339           #+md5-small-length (unsigned-byte 29))
340   (block (make-array 16 :element-type '(unsigned-byte 32)) :read-only t
341          :type (simple-array (unsigned-byte 32) (16)))
342   (buffer (make-array 64 :element-type '(unsigned-byte 8)) :read-only t
343          :type (simple-array (unsigned-byte 8) (64)))
344   (buffer-index 0 :type (integer 0 63))
345   (finalized-p nil))
346
347 (declaim (inline copy-to-buffer))
348 (defun copy-to-buffer (from from-offset count buffer buffer-offset)
349   "Copy a partial segment from input vector from starting at
350 from-offset and copying count elements into the 64 byte buffer
351 starting at buffer-offset."
352   (declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
353            (type (unsigned-byte 29) from-offset)
354            (type (integer 0 63) count buffer-offset)
355            (type (simple-array * (*)) from)
356            (type (simple-array (unsigned-byte 8) (64)) buffer))
357   #+cmu
358   (kernel:bit-bash-copy
359    from (+ (* vm:vector-data-offset vm:word-bits) (* from-offset vm:byte-bits))
360    buffer (+ (* vm:vector-data-offset vm:word-bits)
361              (* buffer-offset vm:byte-bits))
362    (* count vm:byte-bits))
363   #-cmu
364   (etypecase from
365     (simple-string
366      (loop for buffer-index of-type (integer 0 64) from buffer-offset
367            for from-index of-type fixnum from from-offset
368            below (+ from-offset count)
369            do
370            (setf (aref buffer buffer-index)
371                  (char-code (schar (the simple-string from) from-index)))))
372     ((simple-array (unsigned-byte 8) (*))
373      (loop for buffer-index of-type (integer 0 64) from buffer-offset
374            for from-index of-type fixnum from from-offset
375            below (+ from-offset count)
376            do
377            (setf (aref buffer buffer-index)
378                  (aref (the (simple-array (unsigned-byte 8) (*)) from)
379                        from-index))))))
380
381 (defun update-md5-state (state sequence &key (start 0) (end (length sequence)))
382   "Update the given md5-state from sequence, which is either a
383 simple-string or a simple-array with element-type (unsigned-byte 8),
384 bounded by start and end, which must be numeric bounding-indices."
385   (declare (type md5-state state)
386            (type (simple-array * (*)) sequence)
387            (type fixnum start end)
388            (optimize (speed 3) #+cmu (safety 0) (space 0) (debug 0))
389            #+cmu
390            (ext:optimize-interface (safety 1) (debug 1)))
391   (let ((regs (md5-state-regs state))
392         (block (md5-state-block state))
393         (buffer (md5-state-buffer state))
394         (buffer-index (md5-state-buffer-index state))
395         (length (- end start)))
396     (declare (type md5-regs regs) (type fixnum length)
397              (type (integer 0 63) buffer-index)
398              (type (simple-array (unsigned-byte 32) (16)) block)
399              (type (simple-array (unsigned-byte 8) (64)) buffer))
400     ;; Handle old rest
401     (unless (zerop buffer-index)
402       (let ((amount (min (- 64 buffer-index) length)))
403         (declare (type (integer 0 63) amount))
404         (copy-to-buffer sequence start amount buffer buffer-index)
405         (setq start (the fixnum (+ start amount)))
406         (when (>= start end)
407           (setf (md5-state-buffer-index state) (+ buffer-index amount))
408           (return-from update-md5-state state)))
409       (fill-block-ub8 block buffer 0)
410       (update-md5-block regs block))
411     ;; Handle main-part and new-rest
412     (etypecase sequence
413       ((simple-array (unsigned-byte 8) (*))
414        (locally
415            (declare (type (simple-array (unsigned-byte 8) (*)) sequence))
416          (loop for offset of-type (unsigned-byte 29) from start below end by 64
417                until (< (- end offset) 64)
418                do
419                (fill-block-ub8 block sequence offset)
420                (update-md5-block regs block)
421                finally
422                (let ((amount (- end offset)))
423                  (unless (zerop amount)
424                    (copy-to-buffer sequence offset amount buffer 0))
425                  (setf (md5-state-buffer-index state) amount)))))
426       (simple-string
427        (locally
428            (declare (type simple-string sequence))
429          (loop for offset of-type (unsigned-byte 29) from start below end by 64
430                until (< (- end offset) 64)
431                do
432                (fill-block-char block sequence offset)
433                (update-md5-block regs block)
434                finally
435                (let ((amount (- end offset)))
436                  (unless (zerop amount)
437                    (copy-to-buffer sequence offset amount buffer 0))
438                  (setf (md5-state-buffer-index state) amount))))))
439     (setf (md5-state-amount state)
440           #-md5-small-length (+ (md5-state-amount state) length)
441           #+md5-small-length (the (unsigned-byte 29)
442                                (+ (md5-state-amount state) length)))
443     state))
444
445 (defun finalize-md5-state (state)
446   "If the given md5-state has not already been finalized, finalize it,
447 by processing any remaining input in its buffer, with suitable padding
448 and appended bit-length, as specified by the MD5 standard.
449
450 The resulting MD5 message-digest is returned as an array of sixteen
451 (unsigned-byte 8) values.  Calling `update-md5-state' after a call to
452 `finalize-md5-state' results in unspecified behaviour."
453   (declare (type md5-state state)
454            (optimize (speed 3) #+cmu (safety 0) (space 0) (debug 0))
455            #+cmu
456            (ext:optimize-interface (safety 1) (debug 1)))
457   (or (md5-state-finalized-p state)
458       (let ((regs (md5-state-regs state))
459             (block (md5-state-block state))
460             (buffer (md5-state-buffer state))
461             (buffer-index (md5-state-buffer-index state))
462             (total-length (* 8 (md5-state-amount state))))
463         (declare (type md5-regs regs)
464                  (type (integer 0 63) buffer-index)
465                  (type (simple-array ub32 (16)) block)
466                  (type (simple-array (unsigned-byte 8) (*)) buffer))
467         (setf (aref buffer buffer-index) #x80)
468         (loop for index of-type (integer 0 64)
469               from (1+ buffer-index) below 64
470               do (setf (aref buffer index) #x00))
471         (fill-block-ub8 block buffer 0)
472         (when (< buffer-index 56)
473           (setf (aref block 14) (ldb (byte 32 0) total-length))
474           #-md5-small-length
475           (setf (aref block 15) (ldb (byte 32 32) total-length)))
476         (update-md5-block regs block)
477         (when (< 56 buffer-index 64)
478           (loop for index of-type (integer 0 16) from 0 below 16
479                 do (setf (aref block index) #x00000000))
480           (setf (aref block 14) (ldb (byte 32 0) total-length))
481           #-md5-small-length
482           (setf (aref block 15) (ldb (byte 32 32) total-length))
483           (update-md5-block regs block))
484         (setf (md5-state-finalized-p state)
485               (md5regs-digest regs)))))
486
487 ;;; High-Level Drivers
488
489 (defun md5sum-sequence (sequence &key (start 0) end)
490   "Calculate the MD5 message-digest of data in sequence.  On CMU CL
491 this works for all sequences whose element-type is supported by the
492 underlying MD5 routines, on other implementations it only works for 1d
493 simple-arrays with such element types."
494   (declare (optimize (speed 3) (space 0) (debug 0))
495            (type vector sequence) (type fixnum start))
496   (let ((state (make-md5-state)))
497     (declare (type md5-state state))
498     #+cmu
499     (lisp::with-array-data ((data sequence) (real-start start) (real-end end))
500       (update-md5-state state data :start real-start :end real-end))
501     #-cmu
502     (let ((real-end (or end (length sequence))))
503       (declare (type fixnum real-end))
504       (update-md5-state state sequence :start start :end real-end))
505     (finalize-md5-state state)))
506
507 (eval-when (:compile-toplevel :load-toplevel :execute)
508 (defconstant +buffer-size+ (* 128 1024)
509   "Size of internal buffer to use for md5sum-stream and md5sum-file
510 operations.  This should be a multiple of 64, the MD5 block size."))
511
512 (deftype buffer-index () `(integer 0 ,+buffer-size+))
513
514 (defun md5sum-stream (stream)
515   "Calculate an MD5 message-digest of the contents of stream.  Its
516 element-type has to be either (unsigned-byte 8) or character."
517   (declare (optimize (speed 3) (space 0) (debug 0)))
518   (let ((state (make-md5-state)))
519     (declare (type md5-state state))
520     (cond
521       ((equal (stream-element-type stream) '(unsigned-byte 8))
522        (let ((buffer (make-array +buffer-size+
523                                  :element-type '(unsigned-byte 8))))
524          (declare (type (simple-array (unsigned-byte 8) (#.+buffer-size+))
525                         buffer))
526          (loop for bytes of-type buffer-index = (read-sequence buffer stream)
527                do (update-md5-state state buffer :end bytes)
528                until (< bytes +buffer-size+)
529                finally
530                (return (finalize-md5-state state)))))
531       ((equal (stream-element-type stream) 'character)
532        (let ((buffer (make-string +buffer-size+)))
533          (declare (type (simple-string #.+buffer-size+) buffer))
534          (loop for bytes of-type buffer-index = (read-sequence buffer stream)
535                do (update-md5-state state buffer :end bytes)
536                until (< bytes +buffer-size+)
537                finally
538                (return (finalize-md5-state state)))))
539       (t
540        (error "Unsupported stream element-type ~S for stream ~S."
541               (stream-element-type stream) stream)))))
542
543 (defun md5sum-file (pathname)
544   "Calculate the MD5 message-digest of the file specified by pathname."
545   (declare (optimize (speed 3) (space 0) (debug 0)))
546   (with-open-file (stream pathname :element-type '(unsigned-byte 8))
547     (md5sum-stream stream)))
548
549 #+md5-testing
550 (defconstant +rfc1321-testsuite+
551   '(("" . "d41d8cd98f00b204e9800998ecf8427e")
552     ("a" ."0cc175b9c0f1b6a831c399e269772661")
553     ("abc" . "900150983cd24fb0d6963f7d28e17f72")
554     ("message digest" . "f96b697d7cb7938d525a2f31aaf161d0")
555     ("abcdefghijklmnopqrstuvwxyz" . "c3fcd3d76192e4007dfb496cca67e13b")
556     ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" .
557      "d174ab98d277d9f5a5611c2c9f419d9f")
558     ("12345678901234567890123456789012345678901234567890123456789012345678901234567890" .
559      "57edf4a22be3c955ac49da2e2107b67a"))
560   "AList of test input strings and stringified message-digests
561 according to the test suite in Appendix A.5 of RFC 1321")
562
563 #+md5-testing
564 (defun test-rfc1321 ()
565   (loop for count from 1
566         for (source . md5-string) in +rfc1321-testsuite+
567         for md5-digest = (md5sum-sequence source)
568         for md5-result-string = (format nil "~(~{~2,'0X~}~)"
569                                         (map 'list #'identity md5-digest))
570         do
571         (format
572          *trace-output*
573          "~2&Test-Case ~D:~%  Input: ~S~%  Required: ~A~%  Returned: ~A~%"
574          count source md5-string md5-result-string)
575         when (string= md5-string md5-result-string)
576         do (format *trace-output* "  OK~%")
577         else
578         count 1 into failed
579         and do (format *trace-output* "  FAILED~%")
580         finally
581         (format *trace-output*
582                 "~2&~[All ~D test cases succeeded~:;~:*~D of ~D test cases failed~].~%"
583                 failed (1- count))
584         (return (zerop failed))))
585
586 #+cmu
587 (eval-when (:compile-toplevel :execute)
588   (setq *features* *old-features*))
589
590 #+cmu
591 (eval-when (:compile-toplevel)
592   (setq ext:*inline-expansion-limit* *old-expansion-limit*))