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, 1997 Free Software Foundation, Inc.
4   This file is part of the GNU C Library.
5
6   The GNU C Library is free software; you can redistribute it and/or
7   modify it under the terms of the GNU Library General Public License as
8   published by the Free Software Foundation; either version 2 of the
9   License, or (at your option) any later version.
10
11   The GNU C Library is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   Library General Public License for more details.
15
16   You should have received a copy of the GNU Library General Public
17   License along with the GNU C Library; see the file COPYING.LIB.  If not,
18   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19   Boston, MA 02111-1307, USA.  */
20
21/* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.  */
22
23#include "config.h"
24
25#include <sys/types.h>
26
27#include <stdlib.h>
28#include <string.h>
29#ifdef HAVE_LIMITS_H
30# include <limits.h>
31#endif
32
33#include "ne_md5.h"
34#include "ne_string.h" /* for NE_ASC2HEX */
35
36#define md5_process_block ne_md5_process_block
37#define md5_process_bytes ne_md5_process_bytes
38#define md5_finish_ctx ne_md5_finish_ctx
39#define md5_read_ctx ne_md5_read_ctx
40#define md5_stream ne_md5_stream
41#define md5_ctx ne_md5_ctx
42
43#ifdef WORDS_BIGENDIAN
44# define SWAP(n)							\
45    (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
46#else
47# define SWAP(n) (n)
48#endif
49
50#if SIZEOF_INT == 4
51typedef unsigned int md5_uint32;
52#elif SIZEOF_LONG == 4
53typedef unsigned long md5_uint32;
54#else
55# error "Cannot determine unsigned 32-bit data type."
56#endif
57
58/* Structure to save state of computation between the single steps.  */
59struct md5_ctx
60{
61  md5_uint32 A;
62  md5_uint32 B;
63  md5_uint32 C;
64  md5_uint32 D;
65
66  md5_uint32 total[2];
67  md5_uint32 buflen;
68  char buffer[128];
69};
70
71/* This array contains the bytes used to pad the buffer to the next
72   64-byte boundary.  (RFC 1321, 3.1: Step 1)  */
73static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ...  */ };
74
75
76/* Initialize structure containing state of computation.
77   (RFC 1321, 3.3: Step 3)  */
78static void
79md5_init_ctx (struct md5_ctx *ctx)
80{
81  ctx->A = 0x67452301;
82  ctx->B = 0xefcdab89;
83  ctx->C = 0x98badcfe;
84  ctx->D = 0x10325476;
85
86  ctx->total[0] = ctx->total[1] = 0;
87  ctx->buflen = 0;
88}
89
90struct ne_md5_ctx *
91ne_md5_create_ctx(void)
92{
93  struct md5_ctx *ctx = ne_malloc(sizeof *ctx);
94  md5_init_ctx(ctx);
95  return ctx;
96}
97
98extern void
99ne_md5_reset_ctx(struct ne_md5_ctx *ctx)
100{
101  md5_init_ctx(ctx);
102}
103
104struct ne_md5_ctx *
105ne_md5_dup_ctx(struct ne_md5_ctx *ctx)
106{
107  return memcpy(ne_malloc(sizeof *ctx), ctx, sizeof *ctx);
108}
109
110void
111ne_md5_destroy_ctx(struct ne_md5_ctx *ctx)
112{
113  ne_free(ctx);
114}
115
116/* Put result from CTX in first 16 bytes following RESBUF.  The result
117   must be in little endian byte order.
118
119   IMPORTANT: On some systems it is required that RESBUF is correctly
120   aligned for a 32 bits value.  */
121void *
122md5_read_ctx (const struct md5_ctx *ctx, void *resbuf)
123{
124  ((md5_uint32 *) resbuf)[0] = SWAP (ctx->A);
125  ((md5_uint32 *) resbuf)[1] = SWAP (ctx->B);
126  ((md5_uint32 *) resbuf)[2] = SWAP (ctx->C);
127  ((md5_uint32 *) resbuf)[3] = SWAP (ctx->D);
128
129  return resbuf;
130}
131
132/* Process the remaining bytes in the internal buffer and the usual
133   prolog according to the standard and write the result to RESBUF.
134
135   IMPORTANT: On some systems it is required that RESBUF is correctly
136   aligned for a 32 bits value.  */
137void *
138md5_finish_ctx (struct md5_ctx *ctx, void *resbuf)
139{
140  /* Take yet unprocessed bytes into account.  */
141  md5_uint32 bytes = ctx->buflen;
142  size_t pad;
143
144  /* Now count remaining bytes.  */
145  ctx->total[0] += bytes;
146  if (ctx->total[0] < bytes)
147    ++ctx->total[1];
148
149  pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
150  memcpy (&ctx->buffer[bytes], fillbuf, pad);
151
152  /* Put the 64-bit file length in *bits* at the end of the buffer.  */
153  *(md5_uint32 *) &ctx->buffer[bytes + pad] = SWAP (ctx->total[0] << 3);
154  *(md5_uint32 *) &ctx->buffer[bytes + pad + 4] = SWAP ((ctx->total[1] << 3) |
155							(ctx->total[0] >> 29));
156
157  /* Process last bytes.  */
158  md5_process_block (ctx->buffer, bytes + pad + 8, ctx);
159
160  return md5_read_ctx (ctx, resbuf);
161}
162
163/* Compute MD5 message digest for bytes read from STREAM.  The
164   resulting message digest number will be written into the 16 bytes
165   beginning at RESBLOCK.  */
166int
167md5_stream (FILE *stream, void *resblock)
168{
169  /* Important: BLOCKSIZE must be a multiple of 64.  */
170#define BLOCKSIZE 4096
171  struct md5_ctx ctx;
172  char buffer[BLOCKSIZE + 72];
173  size_t sum;
174
175  /* Initialize the computation context.  */
176  md5_init_ctx (&ctx);
177
178  /* Iterate over full file contents.  */
179  while (1)
180    {
181      /* We read the file in blocks of BLOCKSIZE bytes.  One call of the
182	 computation function processes the whole buffer so that with the
183	 next round of the loop another block can be read.  */
184      size_t n;
185      sum = 0;
186
187      /* Read block.  Take care for partial reads.  */
188      do
189	{
190	  n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
191
192	  sum += n;
193	}
194      while (sum < BLOCKSIZE && n != 0);
195      if (n == 0 && ferror (stream))
196        return 1;
197
198      /* If end of file is reached, end the loop.  */
199      if (n == 0)
200	break;
201
202      /* Process buffer with BLOCKSIZE bytes.  Note that
203			BLOCKSIZE % 64 == 0
204       */
205      md5_process_block (buffer, BLOCKSIZE, &ctx);
206    }
207
208  /* Add the last bytes if necessary.  */
209  if (sum > 0)
210    md5_process_bytes (buffer, sum, &ctx);
211
212  /* Construct result in desired memory.  */
213  md5_finish_ctx (&ctx, resblock);
214  return 0;
215}
216
217void
218md5_process_bytes (const void *buffer, size_t len, struct md5_ctx *ctx)
219{
220  /* When we already have some bits in our internal buffer concatenate
221     both inputs first.  */
222  if (ctx->buflen != 0)
223    {
224      size_t left_over = ctx->buflen;
225      size_t add = 128 - left_over > len ? len : 128 - left_over;
226
227      memcpy (&ctx->buffer[left_over], buffer, add);
228      ctx->buflen += add;
229
230      if (left_over + add > 64)
231	{
232	  md5_process_block (ctx->buffer, (left_over + add) & ~63, ctx);
233	  /* The regions in the following copy operation cannot overlap.  */
234	  memcpy (ctx->buffer, &ctx->buffer[(left_over + add) & ~63],
235		  (left_over + add) & 63);
236	  ctx->buflen = (left_over + add) & 63;
237	}
238
239      buffer = (const char *) buffer + add;
240      len -= add;
241    }
242
243  /* Process available complete blocks.  */
244  if (len > 64)
245    {
246      md5_process_block (buffer, len & ~63, ctx);
247      buffer = (const char *) buffer + (len & ~63);
248      len &= 63;
249    }
250
251  /* Move remaining bytes in internal buffer.  */
252  if (len > 0)
253    {
254      memcpy (ctx->buffer, buffer, len);
255      ctx->buflen = len;
256    }
257}
258
259
260/* These are the four functions used in the four steps of the MD5 algorithm
261   and defined in the RFC 1321.  The first function is a little bit optimized
262   (as found in Colin Plumbs public domain implementation).  */
263/* #define FF(b, c, d) ((b & c) | (~b & d)) */
264#define FF(b, c, d) (d ^ (b & (c ^ d)))
265#define FG(b, c, d) FF (d, b, c)
266#define FH(b, c, d) (b ^ c ^ d)
267#define FI(b, c, d) (c ^ (b | ~d))
268
269/* Process LEN bytes of BUFFER, accumulating context into CTX.
270   It is assumed that LEN % 64 == 0.  */
271
272void
273md5_process_block (const void *buffer, size_t len, struct md5_ctx *ctx)
274{
275  md5_uint32 correct_words[16];
276  const unsigned char *words = buffer;
277  const unsigned char *endp = words + len;
278  md5_uint32 A = ctx->A;
279  md5_uint32 B = ctx->B;
280  md5_uint32 C = ctx->C;
281  md5_uint32 D = ctx->D;
282
283  /* First increment the byte count.  RFC 1321 specifies the possible
284     length of the file up to 2^64 bits.  Here we only compute the
285     number of bytes.  Do a double word increment.  */
286  ctx->total[0] += len;
287  if (ctx->total[0] < len)
288    ++ctx->total[1];
289
290  /* Process all bytes in the buffer with 64 bytes in each round of
291     the loop.  */
292  while (words < endp)
293    {
294      md5_uint32 *cwp = correct_words;
295      md5_uint32 A_save = A;
296      md5_uint32 B_save = B;
297      md5_uint32 C_save = C;
298      md5_uint32 D_save = D;
299
300      /* First round: using the given function, the context and a constant
301	 the next context is computed.  Because the algorithms processing
302	 unit is a 32-bit word and it is determined to work on words in
303	 little endian byte order we perhaps have to change the byte order
304	 before the computation.  To reduce the work for the next steps
305	 we store the swapped words in the array CORRECT_WORDS.  */
306
307#define OP(a, b, c, d, s, T)						\
308      do								\
309        {								\
310	  md5_uint32 WORD_ = (md5_uint32)words[0] | ((md5_uint32)words[1] << 8) \
311	       | ((md5_uint32)words[2] << 16) | ((md5_uint32)words[3] << 24); \
312	  a += FF (b, c, d) + (*cwp++ = WORD_) + T;		\
313	  words += 4;							\
314	  CYCLIC (a, s);						\
315	  a += b;							\
316        }								\
317      while (0)
318
319      /* It is unfortunate that C does not provide an operator for
320	 cyclic rotation.  Hope the C compiler is smart enough.  */
321#define CYCLIC(w, s) (w = (w << s) | (w >> (32 - s)))
322
323      /* Before we start, one word to the strange constants.
324	 They are defined in RFC 1321 as
325
326	 T[i] = (int) (4294967296.0 * fabs (sin (i))), i=1..64
327       */
328
329      /* Round 1.  */
330      OP (A, B, C, D,  7, 0xd76aa478);
331      OP (D, A, B, C, 12, 0xe8c7b756);
332      OP (C, D, A, B, 17, 0x242070db);
333      OP (B, C, D, A, 22, 0xc1bdceee);
334      OP (A, B, C, D,  7, 0xf57c0faf);
335      OP (D, A, B, C, 12, 0x4787c62a);
336      OP (C, D, A, B, 17, 0xa8304613);
337      OP (B, C, D, A, 22, 0xfd469501);
338      OP (A, B, C, D,  7, 0x698098d8);
339      OP (D, A, B, C, 12, 0x8b44f7af);
340      OP (C, D, A, B, 17, 0xffff5bb1);
341      OP (B, C, D, A, 22, 0x895cd7be);
342      OP (A, B, C, D,  7, 0x6b901122);
343      OP (D, A, B, C, 12, 0xfd987193);
344      OP (C, D, A, B, 17, 0xa679438e);
345      OP (B, C, D, A, 22, 0x49b40821);
346
347      /* For the second to fourth round we have the possibly swapped words
348	 in CORRECT_WORDS.  Redefine the macro to take an additional first
349	 argument specifying the function to use.  */
350#undef OP
351#define OP(f, a, b, c, d, k, s, T)					\
352      do 								\
353	{								\
354	  a += f (b, c, d) + correct_words[k] + T;			\
355	  CYCLIC (a, s);						\
356	  a += b;							\
357	}								\
358      while (0)
359
360      /* Round 2.  */
361      OP (FG, A, B, C, D,  1,  5, 0xf61e2562);
362      OP (FG, D, A, B, C,  6,  9, 0xc040b340);
363      OP (FG, C, D, A, B, 11, 14, 0x265e5a51);
364      OP (FG, B, C, D, A,  0, 20, 0xe9b6c7aa);
365      OP (FG, A, B, C, D,  5,  5, 0xd62f105d);
366      OP (FG, D, A, B, C, 10,  9, 0x02441453);
367      OP (FG, C, D, A, B, 15, 14, 0xd8a1e681);
368      OP (FG, B, C, D, A,  4, 20, 0xe7d3fbc8);
369      OP (FG, A, B, C, D,  9,  5, 0x21e1cde6);
370      OP (FG, D, A, B, C, 14,  9, 0xc33707d6);
371      OP (FG, C, D, A, B,  3, 14, 0xf4d50d87);
372      OP (FG, B, C, D, A,  8, 20, 0x455a14ed);
373      OP (FG, A, B, C, D, 13,  5, 0xa9e3e905);
374      OP (FG, D, A, B, C,  2,  9, 0xfcefa3f8);
375      OP (FG, C, D, A, B,  7, 14, 0x676f02d9);
376      OP (FG, B, C, D, A, 12, 20, 0x8d2a4c8a);
377
378      /* Round 3.  */
379      OP (FH, A, B, C, D,  5,  4, 0xfffa3942);
380      OP (FH, D, A, B, C,  8, 11, 0x8771f681);
381      OP (FH, C, D, A, B, 11, 16, 0x6d9d6122);
382      OP (FH, B, C, D, A, 14, 23, 0xfde5380c);
383      OP (FH, A, B, C, D,  1,  4, 0xa4beea44);
384      OP (FH, D, A, B, C,  4, 11, 0x4bdecfa9);
385      OP (FH, C, D, A, B,  7, 16, 0xf6bb4b60);
386      OP (FH, B, C, D, A, 10, 23, 0xbebfbc70);
387      OP (FH, A, B, C, D, 13,  4, 0x289b7ec6);
388      OP (FH, D, A, B, C,  0, 11, 0xeaa127fa);
389      OP (FH, C, D, A, B,  3, 16, 0xd4ef3085);
390      OP (FH, B, C, D, A,  6, 23, 0x04881d05);
391      OP (FH, A, B, C, D,  9,  4, 0xd9d4d039);
392      OP (FH, D, A, B, C, 12, 11, 0xe6db99e5);
393      OP (FH, C, D, A, B, 15, 16, 0x1fa27cf8);
394      OP (FH, B, C, D, A,  2, 23, 0xc4ac5665);
395
396      /* Round 4.  */
397      OP (FI, A, B, C, D,  0,  6, 0xf4292244);
398      OP (FI, D, A, B, C,  7, 10, 0x432aff97);
399      OP (FI, C, D, A, B, 14, 15, 0xab9423a7);
400      OP (FI, B, C, D, A,  5, 21, 0xfc93a039);
401      OP (FI, A, B, C, D, 12,  6, 0x655b59c3);
402      OP (FI, D, A, B, C,  3, 10, 0x8f0ccc92);
403      OP (FI, C, D, A, B, 10, 15, 0xffeff47d);
404      OP (FI, B, C, D, A,  1, 21, 0x85845dd1);
405      OP (FI, A, B, C, D,  8,  6, 0x6fa87e4f);
406      OP (FI, D, A, B, C, 15, 10, 0xfe2ce6e0);
407      OP (FI, C, D, A, B,  6, 15, 0xa3014314);
408      OP (FI, B, C, D, A, 13, 21, 0x4e0811a1);
409      OP (FI, A, B, C, D,  4,  6, 0xf7537e82);
410      OP (FI, D, A, B, C, 11, 10, 0xbd3af235);
411      OP (FI, C, D, A, B,  2, 15, 0x2ad7d2bb);
412      OP (FI, B, C, D, A,  9, 21, 0xeb86d391);
413
414      /* Add the starting values of the context.  */
415      A += A_save;
416      B += B_save;
417      C += C_save;
418      D += D_save;
419    }
420
421  /* Put checksum in context given as argument.  */
422  ctx->A = A;
423  ctx->B = B;
424  ctx->C = C;
425  ctx->D = D;
426}
427
428/* Writes the ASCII representation of the MD5 digest into the
429 * given buffer, which must be at least 33 characters long. */
430void ne_md5_to_ascii(const unsigned char md5_buf[16], char *buffer)
431{
432    int count;
433    for (count = 0; count<16; count++) {
434	buffer[count*2] = NE_HEX2ASC(md5_buf[count] >> 4);
435	buffer[count*2+1] = NE_HEX2ASC(md5_buf[count] & 0x0f);
436    }
437    buffer[32] = '\0';
438}
439
440/* Reads the ASCII representation of an MD5 digest. The buffer must
441 * be at least 32 characters long. */
442void ne_ascii_to_md5(const char *buffer, unsigned char md5_buf[16])
443{
444    int count;
445    for (count = 0; count<16; count++) {
446	md5_buf[count] = ((NE_ASC2HEX(buffer[count*2])) << 4) |
447	    NE_ASC2HEX(buffer[count*2+1]);
448    }
449}
450
451char *ne_md5_finish_ascii(struct ne_md5_ctx *ctx, char buffer[33])
452{
453    md5_uint32 result[4];
454
455    ne_md5_finish_ctx(ctx, (void *)result);
456    ne_md5_to_ascii((void *)result, buffer);
457
458    return buffer;
459}
460
461