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