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 file is part of SXEmacs
9 SXEmacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 SXEmacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 /* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995. */
25 /* XEmacs frontend written by Ben Wing, Jareth Hein and Hrvoje Niksic. */
31 #include <sys/types.h>
36 /* The following contortions are an attempt to use the C preprocessor
37 to determine an unsigned integral type that is 32 bits wide. An
38 alternative approach is to use autoconf's AC_CHECK_SIZEOF macro, but
39 doing that would require that the configure script compile and *run*
40 the resulting executable. Locally running cross-compiled executables
41 is usually not possible. */
44 # include <sys/types.h>
45 typedef u_int32_t md5_uint32;
47 # if defined __STDC__ && __STDC__
48 # define UINT_MAX_32_BITS 4294967295U
50 # define UINT_MAX_32_BITS 0xFFFFFFFF
53 /* If UINT_MAX isn't defined, assume it's a 32-bit type.
54 This should be valid for all systems GNU cares about because
55 that doesn't include 16-bit systems, and only modern systems
56 (that certainly have <limits.h>) have 64+-bit integral types. */
59 # define UINT_MAX UINT_MAX_32_BITS
62 # if UINT_MAX == UINT_MAX_32_BITS
63 typedef unsigned int md5_uint32;
65 # if USHRT_MAX == UINT_MAX_32_BITS
66 typedef unsigned short md5_uint32;
68 # if ULONG_MAX == UINT_MAX_32_BITS
69 typedef unsigned long md5_uint32;
71 /* The following line is intended to evoke an error.
72 Using #error is not portable enough. */
73 "Cannot determine unsigned 32-bit data type."
82 # include "mule/file-coding.h"
84 /* Structure to save state of computation between the single steps. */
96 #ifdef WORDS_BIGENDIAN
98 (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
103 /* This array contains the bytes used to pad the buffer to the next
104 64-byte boundary. (RFC 1321, 3.1: Step 1) */
105 static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ };
107 static void md5_process_block(const void *, size_t, struct md5_ctx *);
109 /* Initialize structure containing state of computation.
110 (RFC 1321, 3.3: Step 3) */
111 static void md5_init_ctx(struct md5_ctx *ctx)
118 ctx->total[0] = ctx->total[1] = 0;
122 /* Put result from CTX in first 16 bytes following RESBUF. The result
123 must be in little endian byte order.
125 IMPORTANT: On some systems it is required that RESBUF is correctly
126 aligned for a 32 bits value. */
127 static void *md5_read_ctx(const struct md5_ctx *ctx, void *resbuf)
129 ((md5_uint32 *) resbuf)[0] = SWAP(ctx->A);
130 ((md5_uint32 *) resbuf)[1] = SWAP(ctx->B);
131 ((md5_uint32 *) resbuf)[2] = SWAP(ctx->C);
132 ((md5_uint32 *) resbuf)[3] = SWAP(ctx->D);
137 /* Process the remaining bytes in the internal buffer and the usual
138 prolog according to the standard and write the result to RESBUF.
140 IMPORTANT: On some systems it is required that RESBUF is correctly
141 aligned for a 32 bits value. */
142 static void *md5_finish_ctx(struct md5_ctx *ctx, void *resbuf)
144 /* Take yet unprocessed bytes into account. */
145 md5_uint32 bytes = ctx->buflen;
148 /* Now count remaining bytes. */
149 ctx->total[0] += bytes;
150 if (ctx->total[0] < bytes)
153 pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
154 memcpy(&ctx->buffer[bytes], fillbuf, pad);
156 /* Put the 64-bit file length in *bits* at the end of the buffer. */
157 *(md5_uint32 *) & ctx->buffer[bytes + pad] = SWAP(ctx->total[0] << 3);
158 *(md5_uint32 *) & ctx->buffer[bytes + pad + 4] =
159 SWAP((ctx->total[1] << 3) | (ctx->total[0] >> 29));
161 /* Process last bytes. */
162 md5_process_block(ctx->buffer, bytes + pad + 8, ctx);
164 return md5_read_ctx(ctx, resbuf);
167 #ifndef emacs /* unused in Emacs */
168 /* Compute MD5 message digest for bytes read from STREAM. The
169 resulting message digest number will be written into the 16 bytes
170 beginning at RESBLOCK. */
171 int md5_stream(FILE * stream, void *resblock)
173 /* Important: BLOCKSIZE must be a multiple of 64. */
174 #define BLOCKSIZE 4096
176 char buffer[BLOCKSIZE + 72];
179 /* Initialize the computation context. */
182 /* Iterate over full file contents. */
184 /* We read the file in blocks of BLOCKSIZE bytes. One call of the
185 computation function processes the whole buffer so that with the
186 next round of the loop another block can be read. */
190 /* Read block. Take care for partial reads. */
192 n = fread(buffer + sum, 1, BLOCKSIZE - sum, stream);
196 while (sum < BLOCKSIZE && n != 0);
197 if (n == 0 && ferror(stream))
200 /* If end of file is reached, end the loop. */
204 /* Process buffer with BLOCKSIZE bytes. Note that
207 md5_process_block(buffer, BLOCKSIZE, &ctx);
210 /* Add the last bytes if necessary. */
212 md5_process_bytes(buffer, sum, &ctx);
214 /* Construct result in desired memory. */
215 md5_finish_ctx(&ctx, resblock);
219 /* Compute MD5 message digest for LEN bytes beginning at BUFFER. The
220 result is always in little endian byte order, so that a byte-wise
221 output yields to the wanted ASCII representation of the message
223 void *md5_buffer(const char *buffer, size_t len, void *resblock)
227 /* Initialize the computation context. */
230 /* Process whole buffer but last len % 64 bytes. */
231 md5_process_bytes(buffer, len, &ctx);
233 /* Put result in desired memory area. */
234 return md5_finish_ctx(&ctx, resblock);
236 #endif /* not emacs */
239 md5_process_bytes(const void *buffer, size_t len, struct md5_ctx *ctx)
241 /* When we already have some bits in our internal buffer concatenate
242 both inputs first. */
243 if (ctx->buflen != 0) {
244 size_t left_over = ctx->buflen;
245 size_t add = 128 - left_over > len ? len : 128 - left_over;
247 memcpy(&ctx->buffer[left_over], buffer, add);
250 if (left_over + add > 64) {
251 md5_process_block(ctx->buffer, (left_over + add) & ~63,
253 /* The regions in the following copy operation cannot overlap. */
255 &ctx->buffer[(left_over + add) & ~63],
256 (left_over + add) & 63);
257 ctx->buflen = (left_over + add) & 63;
260 buffer = (const char *)buffer + add;
264 /* Process available complete blocks. */
266 md5_process_block(buffer, len & ~63, ctx);
267 buffer = (const char *)buffer + (len & ~63);
271 /* Move remaining bytes in internal buffer. */
273 memcpy(ctx->buffer, buffer, len);
278 /* These are the four functions used in the four steps of the MD5 algorithm
279 and defined in the RFC 1321. The first function is a little bit optimized
280 (as found in Colin Plumbs public domain implementation). */
281 /* #define FF(b, c, d) ((b & c) | (~b & d)) */
282 #define FF(b, c, d) (d ^ (b & (c ^ d)))
283 #define FG(b, c, d) FF (d, b, c)
284 #define FH(b, c, d) (b ^ c ^ d)
285 #define FI(b, c, d) (c ^ (b | ~d))
287 /* Process LEN bytes of BUFFER, accumulating context into CTX.
288 It is assumed that LEN % 64 == 0. */
291 md5_process_block(const void *buffer, size_t len, struct md5_ctx *ctx)
293 md5_uint32 correct_words[16];
294 const md5_uint32 *words = (const md5_uint32 *)buffer;
295 size_t nwords = len / sizeof(md5_uint32);
296 const md5_uint32 *endp = words + nwords;
297 md5_uint32 A = ctx->A;
298 md5_uint32 B = ctx->B;
299 md5_uint32 C = ctx->C;
300 md5_uint32 D = ctx->D;
302 /* First increment the byte count. RFC 1321 specifies the possible
303 length of the file up to 2^64 bits. Here we only compute the
304 number of bytes. Do a double word increment. */
305 ctx->total[0] += len;
306 if (ctx->total[0] < len)
309 /* Process all bytes in the buffer with 64 bytes in each round of
311 while (words < endp) {
312 md5_uint32 *cwp = correct_words;
313 md5_uint32 A_save = A;
314 md5_uint32 B_save = B;
315 md5_uint32 C_save = C;
316 md5_uint32 D_save = D;
318 /* First round: using the given function, the context and a constant
319 the next context is computed. Because the algorithms processing
320 unit is a 32-bit word and it is determined to work on words in
321 little endian byte order we perhaps have to change the byte order
322 before the computation. To reduce the work for the next steps
323 we store the swapped words in the array CORRECT_WORDS. */
325 #define OP(a, b, c, d, s, T) \
328 a += FF (b, c, d) + (*cwp++ = SWAP (*words)) + T; \
335 /* It is unfortunate that C does not provide an operator for
336 cyclic rotation. Hope the C compiler is smart enough. */
337 #define CYCLIC(w, s) (w = (w << s) | (w >> (32 - s)))
339 /* Before we start, one word to the strange constants.
340 They are defined in RFC 1321 as
342 T[i] = (int) (4294967296.0 * fabs (sin (i))), i=1..64
346 OP(A, B, C, D, 7, 0xd76aa478);
347 OP(D, A, B, C, 12, 0xe8c7b756);
348 OP(C, D, A, B, 17, 0x242070db);
349 OP(B, C, D, A, 22, 0xc1bdceee);
350 OP(A, B, C, D, 7, 0xf57c0faf);
351 OP(D, A, B, C, 12, 0x4787c62a);
352 OP(C, D, A, B, 17, 0xa8304613);
353 OP(B, C, D, A, 22, 0xfd469501);
354 OP(A, B, C, D, 7, 0x698098d8);
355 OP(D, A, B, C, 12, 0x8b44f7af);
356 OP(C, D, A, B, 17, 0xffff5bb1);
357 OP(B, C, D, A, 22, 0x895cd7be);
358 OP(A, B, C, D, 7, 0x6b901122);
359 OP(D, A, B, C, 12, 0xfd987193);
360 OP(C, D, A, B, 17, 0xa679438e);
361 OP(B, C, D, A, 22, 0x49b40821);
363 /* For the second to fourth round we have the possibly swapped words
364 in CORRECT_WORDS. Redefine the macro to take an additional first
365 argument specifying the function to use. */
367 #define OP(f, a, b, c, d, k, s, T) \
370 a += f (b, c, d) + correct_words[k] + T; \
377 OP(FG, A, B, C, D, 1, 5, 0xf61e2562);
378 OP(FG, D, A, B, C, 6, 9, 0xc040b340);
379 OP(FG, C, D, A, B, 11, 14, 0x265e5a51);
380 OP(FG, B, C, D, A, 0, 20, 0xe9b6c7aa);
381 OP(FG, A, B, C, D, 5, 5, 0xd62f105d);
382 OP(FG, D, A, B, C, 10, 9, 0x02441453);
383 OP(FG, C, D, A, B, 15, 14, 0xd8a1e681);
384 OP(FG, B, C, D, A, 4, 20, 0xe7d3fbc8);
385 OP(FG, A, B, C, D, 9, 5, 0x21e1cde6);
386 OP(FG, D, A, B, C, 14, 9, 0xc33707d6);
387 OP(FG, C, D, A, B, 3, 14, 0xf4d50d87);
388 OP(FG, B, C, D, A, 8, 20, 0x455a14ed);
389 OP(FG, A, B, C, D, 13, 5, 0xa9e3e905);
390 OP(FG, D, A, B, C, 2, 9, 0xfcefa3f8);
391 OP(FG, C, D, A, B, 7, 14, 0x676f02d9);
392 OP(FG, B, C, D, A, 12, 20, 0x8d2a4c8a);
395 OP(FH, A, B, C, D, 5, 4, 0xfffa3942);
396 OP(FH, D, A, B, C, 8, 11, 0x8771f681);
397 OP(FH, C, D, A, B, 11, 16, 0x6d9d6122);
398 OP(FH, B, C, D, A, 14, 23, 0xfde5380c);
399 OP(FH, A, B, C, D, 1, 4, 0xa4beea44);
400 OP(FH, D, A, B, C, 4, 11, 0x4bdecfa9);
401 OP(FH, C, D, A, B, 7, 16, 0xf6bb4b60);
402 OP(FH, B, C, D, A, 10, 23, 0xbebfbc70);
403 OP(FH, A, B, C, D, 13, 4, 0x289b7ec6);
404 OP(FH, D, A, B, C, 0, 11, 0xeaa127fa);
405 OP(FH, C, D, A, B, 3, 16, 0xd4ef3085);
406 OP(FH, B, C, D, A, 6, 23, 0x04881d05);
407 OP(FH, A, B, C, D, 9, 4, 0xd9d4d039);
408 OP(FH, D, A, B, C, 12, 11, 0xe6db99e5);
409 OP(FH, C, D, A, B, 15, 16, 0x1fa27cf8);
410 OP(FH, B, C, D, A, 2, 23, 0xc4ac5665);
413 OP(FI, A, B, C, D, 0, 6, 0xf4292244);
414 OP(FI, D, A, B, C, 7, 10, 0x432aff97);
415 OP(FI, C, D, A, B, 14, 15, 0xab9423a7);
416 OP(FI, B, C, D, A, 5, 21, 0xfc93a039);
417 OP(FI, A, B, C, D, 12, 6, 0x655b59c3);
418 OP(FI, D, A, B, C, 3, 10, 0x8f0ccc92);
419 OP(FI, C, D, A, B, 10, 15, 0xffeff47d);
420 OP(FI, B, C, D, A, 1, 21, 0x85845dd1);
421 OP(FI, A, B, C, D, 8, 6, 0x6fa87e4f);
422 OP(FI, D, A, B, C, 15, 10, 0xfe2ce6e0);
423 OP(FI, C, D, A, B, 6, 15, 0xa3014314);
424 OP(FI, B, C, D, A, 13, 21, 0x4e0811a1);
425 OP(FI, A, B, C, D, 4, 6, 0xf7537e82);
426 OP(FI, D, A, B, C, 11, 10, 0xbd3af235);
427 OP(FI, C, D, A, B, 2, 15, 0x2ad7d2bb);
428 OP(FI, B, C, D, A, 9, 21, 0xeb86d391);
430 /* Add the starting values of the context. */
437 /* Put checksum in context given as argument. */
446 /* Find out what format the buffer will be saved in, so we can make
447 the digest based on what it will look like on disk. */
449 md5_coding_system(Lisp_Object object, Lisp_Object coding, Lisp_Object istream,
452 Lisp_Object coding_system;
455 if (BUFFERP(object)) {
456 /* Use the file coding for this buffer by default. */
458 XBUFFER(object)->buffer_file_coding_system;
460 /* Attempt to autodetect the coding of the string. This is
461 VERY hit-and-miss. */
462 eol_type_t eol = EOL_AUTODETECT;
463 coding_system = Fget_coding_system(Qundecided);
464 determine_real_coding_system(XLSTREAM(istream),
465 &coding_system, &eol);
467 if (NILP(coding_system))
468 coding_system = Fget_coding_system(Qbinary);
470 coding_system = Ffind_coding_system(coding_system);
471 if (NILP(coding_system))
472 coding_system = Fget_coding_system(Qbinary);
475 coding_system = Ffind_coding_system(coding);
476 if (NILP(coding_system)) {
478 /* Default to binary. */
479 coding_system = Fget_coding_system(Qbinary);
481 signal_simple_error("No such coding system",
485 return coding_system;
487 #endif /* FILE_CODING */
489 DEFUN("md5", Fmd5, 1, 5, 0, /*
490 Return the MD5 message digest of OBJECT, a buffer or string.
492 Optional arguments START and END denote positions for computing the
493 digest of a portion of OBJECT.
495 The optional CODING argument specifies the coding system the text is to be
496 represented in while computing the digest. If unspecified, it defaults
497 to the current format of the data, or is guessed.
499 If NOERROR is non-nil, silently assume binary coding if the guesswork
500 fails. Normally, an error is signaled in such case.
502 CODING and NOERROR arguments are meaningful only in XEmacsen with
503 file-coding or Mule support. Otherwise, they are ignored.
505 (object, start, end, coding, noerror))
507 /* This function can GC */
508 /* Can this really GC? How? */
510 unsigned char digest[16];
511 unsigned char thehash[33];
514 Lisp_Object instream;
517 Lisp_Object raw_instream;
518 struct gcpro ngcpro1;
521 /* Set up the input stream. */
522 if (BUFFERP(object)) {
525 CHECK_LIVE_BUFFER(object);
527 /* Figure out where we need to get info from */
528 get_buffer_range_char(b, start, end, &begv, &endv,
531 instream = make_lisp_buffer_input_stream(b, begv, endv, 0);
533 Bytecount bstart, bend;
534 CHECK_STRING(object);
535 get_string_range_byte(object, start, end, &bstart, &bend,
536 GB_HISTORICAL_STRING_BEHAVIOR);
538 make_lisp_string_input_stream(object, bstart,
544 /* Determine the coding and set up the conversion stream. */
545 coding = md5_coding_system(object, coding, instream, !NILP(noerror));
546 raw_instream = instream;
547 instream = make_encoding_input_stream(XLSTREAM(instream), coding);
548 NGCPRO1(raw_instream);
551 /* Initialize MD5 context. */
554 /* Get the data while doing the conversion. */
556 Bufbyte tempbuf[1024]; /* some random amount */
557 Lstream_data_count size_in_bytes =
558 Lstream_read(XLSTREAM(instream), tempbuf, sizeof(tempbuf));
559 if (size_in_bytes<=0)
562 /* Process the bytes. */
563 md5_process_bytes(tempbuf, size_in_bytes, &ctx);
565 Lstream_delete(XLSTREAM(instream));
567 Lstream_delete(XLSTREAM(raw_instream));
572 md5_finish_ctx(&ctx, digest);
573 for (i = 0; i < 16; i++)
574 sprintf((char *)(thehash + (i * 2)), "%02x", digest[i]);
576 return make_string(thehash, 32);
579 void syms_of_md5(void)
584 void vars_of_md5(void)
586 Fprovide(intern("md5"));