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