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