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