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