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