6807a830d32b92bfc86af5f83aff0eabb30d85db
[gnulib.git] / lib / md4.c
1 /* Functions to compute MD4 message digest of files or memory blocks.
2    according to the definition of MD4 in RFC 1320 from April 1992.
3    Copyright (C) 1995-1997, 1999-2003, 2005-2006, 2008-2011 Free Software
4    Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify it
7    under the terms of the GNU General Public License as published by the
8    Free Software Foundation; either version 2, or (at your option) any
9    later version.
10
11    This program 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
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 /* Adapted by Simon Josefsson from gnulib md5.? and Libgcrypt
21    cipher/md4.c . */
22
23 #include <config.h>
24
25 #include "md4.h"
26
27 #include <stdalign.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32
33 #if USE_UNLOCKED_IO
34 # include "unlocked-io.h"
35 #endif
36
37 #ifdef WORDS_BIGENDIAN
38 # define SWAP(n)                                                        \
39   (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
40 #else
41 # define SWAP(n) (n)
42 #endif
43
44 #define BLOCKSIZE 32768
45 #if BLOCKSIZE % 64 != 0
46 # error "invalid BLOCKSIZE"
47 #endif
48
49 /* This array contains the bytes used to pad the buffer to the next
50    64-byte boundary.  (RFC 1320, 3.1: Step 1)  */
51 static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ...  */  };
52
53
54 /* Initialize structure containing state of computation.
55    (RFC 1320, 3.3: Step 3)  */
56 void
57 md4_init_ctx (struct md4_ctx *ctx)
58 {
59   ctx->A = 0x67452301;
60   ctx->B = 0xefcdab89;
61   ctx->C = 0x98badcfe;
62   ctx->D = 0x10325476;
63
64   ctx->total[0] = ctx->total[1] = 0;
65   ctx->buflen = 0;
66 }
67
68 /* Copy the 4 byte value from v into the memory location pointed to by *cp,
69    If your architecture allows unaligned access this is equivalent to
70    * (uint32_t *) cp = v  */
71 static inline void
72 set_uint32 (char *cp, uint32_t v)
73 {
74   memcpy (cp, &v, sizeof v);
75 }
76
77 /* Put result from CTX in first 16 bytes following RESBUF.  The result
78    must be in little endian byte order.  */
79 void *
80 md4_read_ctx (const struct md4_ctx *ctx, void *resbuf)
81 {
82   char *r = resbuf;
83   set_uint32 (r + 0 * sizeof ctx->A, SWAP (ctx->A));
84   set_uint32 (r + 1 * sizeof ctx->B, SWAP (ctx->B));
85   set_uint32 (r + 2 * sizeof ctx->C, SWAP (ctx->C));
86   set_uint32 (r + 3 * sizeof ctx->D, SWAP (ctx->D));
87
88   return resbuf;
89 }
90
91 /* Process the remaining bytes in the internal buffer and the usual
92    prolog according to the standard and write the result to RESBUF.  */
93 void *
94 md4_finish_ctx (struct md4_ctx *ctx, void *resbuf)
95 {
96   /* Take yet unprocessed bytes into account.  */
97   uint32_t bytes = ctx->buflen;
98   size_t pad;
99
100   /* Now count remaining bytes.  */
101   ctx->total[0] += bytes;
102   if (ctx->total[0] < bytes)
103     ++ctx->total[1];
104
105   pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
106   memcpy (&((char*)ctx->buffer)[bytes], fillbuf, pad);
107
108   /* Put the 64-bit file length in *bits* at the end of the buffer.  */
109   ctx->buffer[(bytes + pad) / 4] = SWAP (ctx->total[0] << 3);
110   ctx->buffer[(bytes + pad) / 4 + 1] = SWAP ((ctx->total[1] << 3) |
111                                              (ctx->total[0] >> 29));
112
113   /* Process last bytes.  */
114   md4_process_block (ctx->buffer, bytes + pad + 8, ctx);
115
116   return md4_read_ctx (ctx, resbuf);
117 }
118
119 /* Compute MD4 message digest for bytes read from STREAM.  The
120    resulting message digest number will be written into the 16 bytes
121    beginning at RESBLOCK.  */
122 int
123 md4_stream (FILE * stream, void *resblock)
124 {
125   struct md4_ctx ctx;
126   size_t sum;
127
128   char *buffer = malloc (BLOCKSIZE + 72);
129   if (!buffer)
130     return 1;
131
132   /* Initialize the computation context.  */
133   md4_init_ctx (&ctx);
134
135   /* Iterate over full file contents.  */
136   while (1)
137     {
138       /* We read the file in blocks of BLOCKSIZE bytes.  One call of the
139          computation function processes the whole buffer so that with the
140          next round of the loop another block can be read.  */
141       size_t n;
142       sum = 0;
143
144       /* Read block.  Take care for partial reads.  */
145       while (1)
146         {
147           n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
148
149           sum += n;
150
151           if (sum == BLOCKSIZE)
152             break;
153
154           if (n == 0)
155             {
156               /* Check for the error flag IFF N == 0, so that we don't
157                  exit the loop after a partial read due to e.g., EAGAIN
158                  or EWOULDBLOCK.  */
159               if (ferror (stream))
160                 {
161                   free (buffer);
162                   return 1;
163                 }
164               goto process_partial_block;
165             }
166
167           /* We've read at least one byte, so ignore errors.  But always
168              check for EOF, since feof may be true even though N > 0.
169              Otherwise, we could end up calling fread after EOF.  */
170           if (feof (stream))
171             goto process_partial_block;
172         }
173
174       /* Process buffer with BLOCKSIZE bytes.  Note that
175          BLOCKSIZE % 64 == 0
176        */
177       md4_process_block (buffer, BLOCKSIZE, &ctx);
178     }
179
180 process_partial_block:;
181
182   /* Process any remaining bytes.  */
183   if (sum > 0)
184     md4_process_bytes (buffer, sum, &ctx);
185
186   /* Construct result in desired memory.  */
187   md4_finish_ctx (&ctx, resblock);
188   free (buffer);
189   return 0;
190 }
191
192 /* Compute MD4 message digest for LEN bytes beginning at BUFFER.  The
193    result is always in little endian byte order, so that a byte-wise
194    output yields to the wanted ASCII representation of the message
195    digest.  */
196 void *
197 md4_buffer (const char *buffer, size_t len, void *resblock)
198 {
199   struct md4_ctx ctx;
200
201   /* Initialize the computation context.  */
202   md4_init_ctx (&ctx);
203
204   /* Process whole buffer but last len % 64 bytes.  */
205   md4_process_bytes (buffer, len, &ctx);
206
207   /* Put result in desired memory area.  */
208   return md4_finish_ctx (&ctx, resblock);
209 }
210
211 void
212 md4_process_bytes (const void *buffer, size_t len, struct md4_ctx *ctx)
213 {
214   /* When we already have some bits in our internal buffer concatenate
215      both inputs first.  */
216   if (ctx->buflen != 0)
217     {
218       size_t left_over = ctx->buflen;
219       size_t add = 128 - left_over > len ? len : 128 - left_over;
220
221       memcpy (&((char*)ctx->buffer)[left_over], buffer, add);
222       ctx->buflen += add;
223
224       if (ctx->buflen > 64)
225         {
226           md4_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
227
228           ctx->buflen &= 63;
229           /* The regions in the following copy operation cannot overlap.  */
230           memcpy (ctx->buffer, &((char*)ctx->buffer)[(left_over + add) & ~63],
231                   ctx->buflen);
232         }
233
234       buffer = (const char *) buffer + add;
235       len -= add;
236     }
237
238   /* Process available complete blocks.  */
239   if (len >= 64)
240     {
241 #if !_STRING_ARCH_unaligned
242 # define UNALIGNED_P(p) ((uintptr_t) (p) % alignof (uint32_t) != 0)
243       if (UNALIGNED_P (buffer))
244         while (len > 64)
245           {
246             md4_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
247             buffer = (const char *) buffer + 64;
248             len -= 64;
249           }
250       else
251 #endif
252         {
253           md4_process_block (buffer, len & ~63, ctx);
254           buffer = (const char *) buffer + (len & ~63);
255           len &= 63;
256         }
257     }
258
259   /* Move remaining bytes in internal buffer.  */
260   if (len > 0)
261     {
262       size_t left_over = ctx->buflen;
263
264       memcpy (&((char*)ctx->buffer)[left_over], buffer, len);
265       left_over += len;
266       if (left_over >= 64)
267         {
268           md4_process_block (ctx->buffer, 64, ctx);
269           left_over -= 64;
270           memcpy (ctx->buffer, &ctx->buffer[16], left_over);
271         }
272       ctx->buflen = left_over;
273     }
274 }
275
276 /* --- Code below is the primary difference between md5.c and md4.c --- */
277
278 /* MD4 round constants */
279 #define K1 0x5a827999
280 #define K2 0x6ed9eba1
281
282 /* Round functions.  */
283 #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
284 #define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
285 #define H(x, y, z) ((x) ^ (y) ^ (z))
286 #define rol(x, n) (((x) << (n)) | ((uint32_t) (x) >> (32 - (n))))
287 #define R1(a,b,c,d,k,s) a=rol(a+F(b,c,d)+x[k],s);
288 #define R2(a,b,c,d,k,s) a=rol(a+G(b,c,d)+x[k]+K1,s);
289 #define R3(a,b,c,d,k,s) a=rol(a+H(b,c,d)+x[k]+K2,s);
290
291 /* Process LEN bytes of BUFFER, accumulating context into CTX.
292    It is assumed that LEN % 64 == 0.  */
293
294 void
295 md4_process_block (const void *buffer, size_t len, struct md4_ctx *ctx)
296 {
297   const uint32_t *words = buffer;
298   size_t nwords = len / sizeof (uint32_t);
299   const uint32_t *endp = words + nwords;
300   uint32_t x[16];
301   uint32_t A = ctx->A;
302   uint32_t B = ctx->B;
303   uint32_t C = ctx->C;
304   uint32_t D = ctx->D;
305
306   /* First increment the byte count.  RFC 1320 specifies the possible
307      length of the file up to 2^64 bits.  Here we only compute the
308      number of bytes.  Do a double word increment.  */
309   ctx->total[0] += len;
310   if (ctx->total[0] < len)
311     ++ctx->total[1];
312
313   /* Process all bytes in the buffer with 64 bytes in each round of
314      the loop.  */
315   while (words < endp)
316     {
317       int t;
318       for (t = 0; t < 16; t++)
319         {
320           x[t] = SWAP (*words);
321           words++;
322         }
323
324       /* Round 1.  */
325       R1 (A, B, C, D, 0, 3);
326       R1 (D, A, B, C, 1, 7);
327       R1 (C, D, A, B, 2, 11);
328       R1 (B, C, D, A, 3, 19);
329       R1 (A, B, C, D, 4, 3);
330       R1 (D, A, B, C, 5, 7);
331       R1 (C, D, A, B, 6, 11);
332       R1 (B, C, D, A, 7, 19);
333       R1 (A, B, C, D, 8, 3);
334       R1 (D, A, B, C, 9, 7);
335       R1 (C, D, A, B, 10, 11);
336       R1 (B, C, D, A, 11, 19);
337       R1 (A, B, C, D, 12, 3);
338       R1 (D, A, B, C, 13, 7);
339       R1 (C, D, A, B, 14, 11);
340       R1 (B, C, D, A, 15, 19);
341
342       /* Round 2.  */
343       R2 (A, B, C, D, 0, 3);
344       R2 (D, A, B, C, 4, 5);
345       R2 (C, D, A, B, 8, 9);
346       R2 (B, C, D, A, 12, 13);
347       R2 (A, B, C, D, 1, 3);
348       R2 (D, A, B, C, 5, 5);
349       R2 (C, D, A, B, 9, 9);
350       R2 (B, C, D, A, 13, 13);
351       R2 (A, B, C, D, 2, 3);
352       R2 (D, A, B, C, 6, 5);
353       R2 (C, D, A, B, 10, 9);
354       R2 (B, C, D, A, 14, 13);
355       R2 (A, B, C, D, 3, 3);
356       R2 (D, A, B, C, 7, 5);
357       R2 (C, D, A, B, 11, 9);
358       R2 (B, C, D, A, 15, 13);
359
360       /* Round 3.  */
361       R3 (A, B, C, D, 0, 3);
362       R3 (D, A, B, C, 8, 9);
363       R3 (C, D, A, B, 4, 11);
364       R3 (B, C, D, A, 12, 15);
365       R3 (A, B, C, D, 2, 3);
366       R3 (D, A, B, C, 10, 9);
367       R3 (C, D, A, B, 6, 11);
368       R3 (B, C, D, A, 14, 15);
369       R3 (A, B, C, D, 1, 3);
370       R3 (D, A, B, C, 9, 9);
371       R3 (C, D, A, B, 5, 11);
372       R3 (B, C, D, A, 13, 15);
373       R3 (A, B, C, D, 3, 3);
374       R3 (D, A, B, C, 11, 9);
375       R3 (C, D, A, B, 7, 11);
376       R3 (B, C, D, A, 15, 15);
377
378       A = ctx->A += A;
379       B = ctx->B += B;
380       C = ctx->C += C;
381       D = ctx->D += D;
382     }
383 }