1 /* md5.c - Functions to compute MD5 message digest of files or memory blocks
2 according to the definition of MD5 in RFC 1321 from April 1992.
3 Copyright (C) 1995, 1996 Free Software Foundation, Inc.
4 NOTE: The canonical source of this file is maintained with the GNU C
5 Library. Bugs can be reported to bug-glibc@prep.ai.mit.edu.
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software Foundation,
19 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
21 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995. */
23 /* XEmacs frontend written by Ben Wing, Jareth Hein and Hrvoje Niksic. */
29 #include <sys/types.h>
36 #if defined HAVE_LIMITS_H || _LIBC
40 /* The following contortions are an attempt to use the C preprocessor
41 to determine an unsigned integral type that is 32 bits wide. An
42 alternative approach is to use autoconf's AC_CHECK_SIZEOF macro, but
43 doing that would require that the configure script compile and *run*
44 the resulting executable. Locally running cross-compiled executables
45 is usually not possible. */
48 # include <sys/types.h>
49 typedef u_int32_t md5_uint32;
51 # if defined __STDC__ && __STDC__
52 # define UINT_MAX_32_BITS 4294967295U
54 # define UINT_MAX_32_BITS 0xFFFFFFFF
57 /* If UINT_MAX isn't defined, assume it's a 32-bit type.
58 This should be valid for all systems GNU cares about because
59 that doesn't include 16-bit systems, and only modern systems
60 (that certainly have <limits.h>) have 64+-bit integral types. */
63 # define UINT_MAX UINT_MAX_32_BITS
66 # if UINT_MAX == UINT_MAX_32_BITS
67 typedef unsigned int md5_uint32;
69 # if USHRT_MAX == UINT_MAX_32_BITS
70 typedef unsigned short md5_uint32;
72 # if ULONG_MAX == UINT_MAX_32_BITS
73 typedef unsigned long md5_uint32;
75 /* The following line is intended to evoke an error.
76 Using #error is not portable enough. */
77 "Cannot determine unsigned 32-bit data type."
87 # include "file-coding.h"
90 /* Structure to save state of computation between the single steps. */
103 #ifdef WORDS_BIGENDIAN
105 (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
111 /* This array contains the bytes used to pad the buffer to the next
112 64-byte boundary. (RFC 1321, 3.1: Step 1) */
113 static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ };
116 static void md5_process_block (CONST void *, size_t, struct md5_ctx *);
119 /* Initialize structure containing state of computation.
120 (RFC 1321, 3.3: Step 3) */
122 md5_init_ctx (struct md5_ctx *ctx)
129 ctx->total[0] = ctx->total[1] = 0;
133 /* Put result from CTX in first 16 bytes following RESBUF. The result
134 must be in little endian byte order.
136 IMPORTANT: On some systems it is required that RESBUF is correctly
137 aligned for a 32 bits value. */
139 md5_read_ctx (CONST struct md5_ctx *ctx, void *resbuf)
141 ((md5_uint32 *) resbuf)[0] = SWAP (ctx->A);
142 ((md5_uint32 *) resbuf)[1] = SWAP (ctx->B);
143 ((md5_uint32 *) resbuf)[2] = SWAP (ctx->C);
144 ((md5_uint32 *) resbuf)[3] = SWAP (ctx->D);
149 /* Process the remaining bytes in the internal buffer and the usual
150 prolog according to the standard and write the result to RESBUF.
152 IMPORTANT: On some systems it is required that RESBUF is correctly
153 aligned for a 32 bits value. */
155 md5_finish_ctx (struct md5_ctx *ctx, void *resbuf)
157 /* Take yet unprocessed bytes into account. */
158 md5_uint32 bytes = ctx->buflen;
161 /* Now count remaining bytes. */
162 ctx->total[0] += bytes;
163 if (ctx->total[0] < bytes)
166 pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
167 memcpy (&ctx->buffer[bytes], fillbuf, pad);
169 /* Put the 64-bit file length in *bits* at the end of the buffer. */
170 *(md5_uint32 *) &ctx->buffer[bytes + pad] = SWAP (ctx->total[0] << 3);
171 *(md5_uint32 *) &ctx->buffer[bytes + pad + 4] = SWAP ((ctx->total[1] << 3) |
172 (ctx->total[0] >> 29));
174 /* Process last bytes. */
175 md5_process_block (ctx->buffer, bytes + pad + 8, ctx);
177 return md5_read_ctx (ctx, resbuf);
180 #ifndef emacs /* unused in Emacs */
181 /* Compute MD5 message digest for bytes read from STREAM. The
182 resulting message digest number will be written into the 16 bytes
183 beginning at RESBLOCK. */
185 md5_stream (FILE *stream, void *resblock)
187 /* Important: BLOCKSIZE must be a multiple of 64. */
188 #define BLOCKSIZE 4096
190 char buffer[BLOCKSIZE + 72];
193 /* Initialize the computation context. */
196 /* Iterate over full file contents. */
199 /* We read the file in blocks of BLOCKSIZE bytes. One call of the
200 computation function processes the whole buffer so that with the
201 next round of the loop another block can be read. */
205 /* Read block. Take care for partial reads. */
208 n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
212 while (sum < BLOCKSIZE && n != 0);
213 if (n == 0 && ferror (stream))
216 /* If end of file is reached, end the loop. */
220 /* Process buffer with BLOCKSIZE bytes. Note that
223 md5_process_block (buffer, BLOCKSIZE, &ctx);
226 /* Add the last bytes if necessary. */
228 md5_process_bytes (buffer, sum, &ctx);
230 /* Construct result in desired memory. */
231 md5_finish_ctx (&ctx, resblock);
235 /* Compute MD5 message digest for LEN bytes beginning at BUFFER. The
236 result is always in little endian byte order, so that a byte-wise
237 output yields to the wanted ASCII representation of the message
240 md5_buffer (const char *buffer, size_t len, void *resblock)
244 /* Initialize the computation context. */
247 /* Process whole buffer but last len % 64 bytes. */
248 md5_process_bytes (buffer, len, &ctx);
250 /* Put result in desired memory area. */
251 return md5_finish_ctx (&ctx, resblock);
253 #endif /* not emacs */
257 md5_process_bytes (CONST void *buffer, size_t len, struct md5_ctx *ctx)
259 /* When we already have some bits in our internal buffer concatenate
260 both inputs first. */
261 if (ctx->buflen != 0)
263 size_t left_over = ctx->buflen;
264 size_t add = 128 - left_over > len ? len : 128 - left_over;
266 memcpy (&ctx->buffer[left_over], buffer, add);
269 if (left_over + add > 64)
271 md5_process_block (ctx->buffer, (left_over + add) & ~63, ctx);
272 /* The regions in the following copy operation cannot overlap. */
273 memcpy (ctx->buffer, &ctx->buffer[(left_over + add) & ~63],
274 (left_over + add) & 63);
275 ctx->buflen = (left_over + add) & 63;
278 buffer = (const char *) buffer + add;
282 /* Process available complete blocks. */
285 md5_process_block (buffer, len & ~63, ctx);
286 buffer = (const char *) buffer + (len & ~63);
290 /* Move remaining bytes in internal buffer. */
293 memcpy (ctx->buffer, buffer, len);
299 /* These are the four functions used in the four steps of the MD5 algorithm
300 and defined in the RFC 1321. The first function is a little bit optimized
301 (as found in Colin Plumbs public domain implementation). */
302 /* #define FF(b, c, d) ((b & c) | (~b & d)) */
303 #define FF(b, c, d) (d ^ (b & (c ^ d)))
304 #define FG(b, c, d) FF (d, b, c)
305 #define FH(b, c, d) (b ^ c ^ d)
306 #define FI(b, c, d) (c ^ (b | ~d))
308 /* Process LEN bytes of BUFFER, accumulating context into CTX.
309 It is assumed that LEN % 64 == 0. */
312 md5_process_block (CONST void *buffer, size_t len, struct md5_ctx *ctx)
314 md5_uint32 correct_words[16];
315 const md5_uint32 *words = (const md5_uint32 *) buffer;
316 size_t nwords = len / sizeof (md5_uint32);
317 const md5_uint32 *endp = words + nwords;
318 md5_uint32 A = ctx->A;
319 md5_uint32 B = ctx->B;
320 md5_uint32 C = ctx->C;
321 md5_uint32 D = ctx->D;
323 /* First increment the byte count. RFC 1321 specifies the possible
324 length of the file up to 2^64 bits. Here we only compute the
325 number of bytes. Do a double word increment. */
326 ctx->total[0] += len;
327 if (ctx->total[0] < len)
330 /* Process all bytes in the buffer with 64 bytes in each round of
334 md5_uint32 *cwp = correct_words;
335 md5_uint32 A_save = A;
336 md5_uint32 B_save = B;
337 md5_uint32 C_save = C;
338 md5_uint32 D_save = D;
340 /* First round: using the given function, the context and a constant
341 the next context is computed. Because the algorithms processing
342 unit is a 32-bit word and it is determined to work on words in
343 little endian byte order we perhaps have to change the byte order
344 before the computation. To reduce the work for the next steps
345 we store the swapped words in the array CORRECT_WORDS. */
347 #define OP(a, b, c, d, s, T) \
350 a += FF (b, c, d) + (*cwp++ = SWAP (*words)) + T; \
357 /* It is unfortunate that C does not provide an operator for
358 cyclic rotation. Hope the C compiler is smart enough. */
359 #define CYCLIC(w, s) (w = (w << s) | (w >> (32 - s)))
361 /* Before we start, one word to the strange constants.
362 They are defined in RFC 1321 as
364 T[i] = (int) (4294967296.0 * fabs (sin (i))), i=1..64
368 OP (A, B, C, D, 7, 0xd76aa478);
369 OP (D, A, B, C, 12, 0xe8c7b756);
370 OP (C, D, A, B, 17, 0x242070db);
371 OP (B, C, D, A, 22, 0xc1bdceee);
372 OP (A, B, C, D, 7, 0xf57c0faf);
373 OP (D, A, B, C, 12, 0x4787c62a);
374 OP (C, D, A, B, 17, 0xa8304613);
375 OP (B, C, D, A, 22, 0xfd469501);
376 OP (A, B, C, D, 7, 0x698098d8);
377 OP (D, A, B, C, 12, 0x8b44f7af);
378 OP (C, D, A, B, 17, 0xffff5bb1);
379 OP (B, C, D, A, 22, 0x895cd7be);
380 OP (A, B, C, D, 7, 0x6b901122);
381 OP (D, A, B, C, 12, 0xfd987193);
382 OP (C, D, A, B, 17, 0xa679438e);
383 OP (B, C, D, A, 22, 0x49b40821);
385 /* For the second to fourth round we have the possibly swapped words
386 in CORRECT_WORDS. Redefine the macro to take an additional first
387 argument specifying the function to use. */
389 #define OP(f, a, b, c, d, k, s, T) \
392 a += f (b, c, d) + correct_words[k] + T; \
399 OP (FG, A, B, C, D, 1, 5, 0xf61e2562);
400 OP (FG, D, A, B, C, 6, 9, 0xc040b340);
401 OP (FG, C, D, A, B, 11, 14, 0x265e5a51);
402 OP (FG, B, C, D, A, 0, 20, 0xe9b6c7aa);
403 OP (FG, A, B, C, D, 5, 5, 0xd62f105d);
404 OP (FG, D, A, B, C, 10, 9, 0x02441453);
405 OP (FG, C, D, A, B, 15, 14, 0xd8a1e681);
406 OP (FG, B, C, D, A, 4, 20, 0xe7d3fbc8);
407 OP (FG, A, B, C, D, 9, 5, 0x21e1cde6);
408 OP (FG, D, A, B, C, 14, 9, 0xc33707d6);
409 OP (FG, C, D, A, B, 3, 14, 0xf4d50d87);
410 OP (FG, B, C, D, A, 8, 20, 0x455a14ed);
411 OP (FG, A, B, C, D, 13, 5, 0xa9e3e905);
412 OP (FG, D, A, B, C, 2, 9, 0xfcefa3f8);
413 OP (FG, C, D, A, B, 7, 14, 0x676f02d9);
414 OP (FG, B, C, D, A, 12, 20, 0x8d2a4c8a);
417 OP (FH, A, B, C, D, 5, 4, 0xfffa3942);
418 OP (FH, D, A, B, C, 8, 11, 0x8771f681);
419 OP (FH, C, D, A, B, 11, 16, 0x6d9d6122);
420 OP (FH, B, C, D, A, 14, 23, 0xfde5380c);
421 OP (FH, A, B, C, D, 1, 4, 0xa4beea44);
422 OP (FH, D, A, B, C, 4, 11, 0x4bdecfa9);
423 OP (FH, C, D, A, B, 7, 16, 0xf6bb4b60);
424 OP (FH, B, C, D, A, 10, 23, 0xbebfbc70);
425 OP (FH, A, B, C, D, 13, 4, 0x289b7ec6);
426 OP (FH, D, A, B, C, 0, 11, 0xeaa127fa);
427 OP (FH, C, D, A, B, 3, 16, 0xd4ef3085);
428 OP (FH, B, C, D, A, 6, 23, 0x04881d05);
429 OP (FH, A, B, C, D, 9, 4, 0xd9d4d039);
430 OP (FH, D, A, B, C, 12, 11, 0xe6db99e5);
431 OP (FH, C, D, A, B, 15, 16, 0x1fa27cf8);
432 OP (FH, B, C, D, A, 2, 23, 0xc4ac5665);
435 OP (FI, A, B, C, D, 0, 6, 0xf4292244);
436 OP (FI, D, A, B, C, 7, 10, 0x432aff97);
437 OP (FI, C, D, A, B, 14, 15, 0xab9423a7);
438 OP (FI, B, C, D, A, 5, 21, 0xfc93a039);
439 OP (FI, A, B, C, D, 12, 6, 0x655b59c3);
440 OP (FI, D, A, B, C, 3, 10, 0x8f0ccc92);
441 OP (FI, C, D, A, B, 10, 15, 0xffeff47d);
442 OP (FI, B, C, D, A, 1, 21, 0x85845dd1);
443 OP (FI, A, B, C, D, 8, 6, 0x6fa87e4f);
444 OP (FI, D, A, B, C, 15, 10, 0xfe2ce6e0);
445 OP (FI, C, D, A, B, 6, 15, 0xa3014314);
446 OP (FI, B, C, D, A, 13, 21, 0x4e0811a1);
447 OP (FI, A, B, C, D, 4, 6, 0xf7537e82);
448 OP (FI, D, A, B, C, 11, 10, 0xbd3af235);
449 OP (FI, C, D, A, B, 2, 15, 0x2ad7d2bb);
450 OP (FI, B, C, D, A, 9, 21, 0xeb86d391);
452 /* Add the starting values of the context. */
459 /* Put checksum in context given as argument. */
469 /* Find out what format the buffer will be saved in, so we can make
470 the digest based on what it will look like on disk. */
472 md5_coding_system (Lisp_Object object, Lisp_Object coding, Lisp_Object istream,
475 Lisp_Object coding_system;
479 if (BUFFERP (object))
481 /* Use the file coding for this buffer by default. */
482 coding_system = XBUFFER (object)->buffer_file_coding_system;
486 /* Attempt to autodetect the coding of the string. This is
487 VERY hit-and-miss. */
488 enum eol_type eol = EOL_AUTODETECT;
489 coding_system = Fget_coding_system (Qundecided);
490 determine_real_coding_system (XLSTREAM (istream),
491 &coding_system, &eol);
493 if (NILP (coding_system))
494 coding_system = Fget_coding_system (Qbinary);
497 coding_system = Ffind_coding_system (coding_system);
498 if (NILP (coding_system))
499 coding_system = Fget_coding_system (Qbinary);
504 coding_system = Ffind_coding_system (coding);
505 if (NILP (coding_system))
508 /* Default to binary. */
509 coding_system = Fget_coding_system (Qbinary);
511 signal_simple_error ("No such coding system", coding);
514 return coding_system;
516 #endif /* FILE_CODING */
519 DEFUN ("md5", Fmd5, 1, 5, 0, /*
520 Return the MD5 message digest of OBJECT, a buffer or string.
522 Optional arguments START and END denote positions for computing the
523 digest of a portion of OBJECT.
525 The optional CODING argument specifies the coding system the text is to be
526 represented in while computing the digest. If unspecified, it defaults
527 to the current format of the data, or is guessed.
529 If NOERROR is non-nil, silently assume binary coding if the guesswork
530 fails. Normally, an error is signaled in such case.
532 CODING and NOERROR arguments are meaningful only in XEmacsen with
533 file-coding or Mule support. Otherwise, they are ignored.
535 (object, start, end, coding, noerror))
537 /* This function can GC */
538 /* Can this really GC? How? */
540 unsigned char digest[16];
541 unsigned char thehash[33];
544 Lisp_Object instream;
547 Lisp_Object raw_instream;
548 struct gcpro ngcpro1;
551 /* Set up the input stream. */
552 if (BUFFERP (object))
556 CHECK_LIVE_BUFFER (object);
557 b = XBUFFER (object);
558 /* Figure out where we need to get info from */
559 get_buffer_range_char (b, start, end, &begv, &endv, GB_ALLOW_NIL);
561 instream = make_lisp_buffer_input_stream (b, begv, endv, 0);
565 Bytecount bstart, bend;
566 CHECK_STRING (object);
567 get_string_range_byte (object, start, end, &bstart, &bend,
568 GB_HISTORICAL_STRING_BEHAVIOR);
569 instream = make_lisp_string_input_stream (object, bstart, bend);
574 /* Determine the coding and set up the conversion stream. */
575 coding = md5_coding_system (object, coding, instream, !NILP (noerror));
576 raw_instream = instream;
577 instream = make_encoding_input_stream (XLSTREAM (instream), coding);
578 NGCPRO1 (raw_instream);
581 /* Initialize MD5 context. */
584 /* Get the data while doing the conversion. */
587 Bufbyte tempbuf[1024]; /* some random amount */
588 int size_in_bytes = Lstream_read (XLSTREAM (instream),
589 tempbuf, sizeof (tempbuf));
593 /* Process the bytes. */
594 md5_process_bytes (tempbuf, size_in_bytes, &ctx);
596 Lstream_delete (XLSTREAM (instream));
598 Lstream_delete (XLSTREAM (raw_instream));
603 md5_finish_ctx (&ctx, digest);
604 for (i = 0; i < 16; i++)
605 sprintf ((char *) (thehash + (i * 2)), "%02x", digest[i]);
607 return make_string (thehash, 32);
619 Fprovide (intern ("md5"));