Merge frem coreutils.
[gnulib.git] / lib / sha.c
1 /* sha.c - Functions to compute the SHA1 hash (message-digest) of files
2    or blocks of memory.  Complies to the NIST specification FIPS-180-1.
3
4    Copyright (C) 2000, 2001, 2003 Scott G. Miller
5
6    Credits:
7       Robert Klep <robert@ilse.nl>  -- Expansion function fix
8 */
9
10 #ifdef HAVE_CONFIG_H
11 # include <config.h>
12 #endif
13
14 #include <sys/types.h>
15
16 #if STDC_HEADERS || defined _LIBC
17 # include <stdlib.h>
18 # include <string.h>
19 #else
20 # ifndef HAVE_MEMCPY
21 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
22 # endif
23 #endif
24
25 #include "md5.h"
26 #include "sha.h"
27 #include "unlocked-io.h"
28
29 /*
30   Not-swap is a macro that does an endian swap on architectures that are
31   big-endian, as SHA needs some data in a little-endian format
32 */
33
34 #ifdef WORDS_BIGENDIAN
35 # define NOTSWAP(n) (n)
36 # define SWAP(n)                                                        \
37     (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
38 #else
39 # define NOTSWAP(n)                                                         \
40     (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
41 # define SWAP(n) (n)
42 #endif
43
44 #define BLOCKSIZE 4096
45 /* Ensure that BLOCKSIZE is a multiple of 64.  */
46 #if BLOCKSIZE % 64 != 0
47 /* FIXME-someday (soon?): use #error instead of this kludge.  */
48 "invalid BLOCKSIZE"
49 #endif
50
51 /* This array contains the bytes used to pad the buffer to the next
52    64-byte boundary.  (RFC 1321, 3.1: Step 1)  */
53 static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ...  */ };
54
55
56 /*
57   Takes a pointer to a 160 bit block of data (five 32 bit ints) and
58   intializes it to the start constants of the SHA1 algorithm.  This
59   must be called before using hash in the call to sha_hash
60 */
61 void
62 sha_init_ctx (struct sha_ctx *ctx)
63 {
64   ctx->A = 0x67452301;
65   ctx->B = 0xefcdab89;
66   ctx->C = 0x98badcfe;
67   ctx->D = 0x10325476;
68   ctx->E = 0xc3d2e1f0;
69
70   ctx->total[0] = ctx->total[1] = 0;
71   ctx->buflen = 0;
72 }
73
74 /* Put result from CTX in first 20 bytes following RESBUF.  The result
75    must be in little endian byte order.
76
77    IMPORTANT: On some systems it is required that RESBUF is correctly
78    aligned for a 32 bits value.  */
79 void *
80 sha_read_ctx (const struct sha_ctx *ctx, void *resbuf)
81 {
82   ((md5_uint32 *) resbuf)[0] = NOTSWAP (ctx->A);
83   ((md5_uint32 *) resbuf)[1] = NOTSWAP (ctx->B);
84   ((md5_uint32 *) resbuf)[2] = NOTSWAP (ctx->C);
85   ((md5_uint32 *) resbuf)[3] = NOTSWAP (ctx->D);
86   ((md5_uint32 *) resbuf)[4] = NOTSWAP (ctx->E);
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
94    IMPORTANT: On some systems it is required that RESBUF is correctly
95    aligned for a 32 bits value.  */
96 void *
97 sha_finish_ctx (struct sha_ctx *ctx, void *resbuf)
98 {
99   /* Take yet unprocessed bytes into account.  */
100   md5_uint32 bytes = ctx->buflen;
101   size_t pad;
102
103   /* Now count remaining bytes.  */
104   ctx->total[0] += bytes;
105   if (ctx->total[0] < bytes)
106     ++ctx->total[1];
107
108   pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
109   memcpy (&ctx->buffer[bytes], fillbuf, pad);
110
111   /* Put the 64-bit file length in *bits* at the end of the buffer.  */
112   *(md5_uint32 *) &ctx->buffer[bytes + pad + 4] = NOTSWAP (ctx->total[0] << 3);
113   *(md5_uint32 *) &ctx->buffer[bytes + pad] = NOTSWAP ((ctx->total[1] << 3) |
114                                                     (ctx->total[0] >> 29));
115
116   /* Process last bytes.  */
117   sha_process_block (ctx->buffer, bytes + pad + 8, ctx);
118
119   return sha_read_ctx (ctx, resbuf);
120 }
121
122 /* Compute SHA1 message digest for bytes read from STREAM.  The
123    resulting message digest number will be written into the 16 bytes
124    beginning at RESBLOCK.  */
125 int
126 sha_stream (FILE *stream, void *resblock)
127 {
128   struct sha_ctx ctx;
129   char buffer[BLOCKSIZE + 72];
130   size_t sum;
131
132   /* Initialize the computation context.  */
133   sha_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                 return 1;
161               goto process_partial_block;
162             }
163
164           /* We've read at least one byte, so ignore errors.  But always
165              check for EOF, since feof may be true even though N > 0.
166              Otherwise, we could end up calling fread after EOF.  */
167           if (feof (stream))
168             goto process_partial_block;
169         }
170
171       /* Process buffer with BLOCKSIZE bytes.  Note that
172                         BLOCKSIZE % 64 == 0
173        */
174       sha_process_block (buffer, BLOCKSIZE, &ctx);
175     }
176
177  process_partial_block:;
178
179   /* Process any remaining bytes.  */
180   if (sum > 0)
181     sha_process_bytes (buffer, sum, &ctx);
182
183   /* Construct result in desired memory.  */
184   sha_finish_ctx (&ctx, resblock);
185   return 0;
186 }
187
188 /* Compute MD5 message digest for LEN bytes beginning at BUFFER.  The
189    result is always in little endian byte order, so that a byte-wise
190    output yields to the wanted ASCII representation of the message
191    digest.  */
192 void *
193 sha_buffer (const char *buffer, size_t len, void *resblock)
194 {
195   struct sha_ctx ctx;
196
197   /* Initialize the computation context.  */
198   sha_init_ctx (&ctx);
199
200   /* Process whole buffer but last len % 64 bytes.  */
201   sha_process_bytes (buffer, len, &ctx);
202
203   /* Put result in desired memory area.  */
204   return sha_finish_ctx (&ctx, resblock);
205 }
206
207 void
208 sha_process_bytes (const void *buffer, size_t len, struct sha_ctx *ctx)
209 {
210   /* When we already have some bits in our internal buffer concatenate
211      both inputs first.  */
212   if (ctx->buflen != 0)
213     {
214       size_t left_over = ctx->buflen;
215       size_t add = 128 - left_over > len ? len : 128 - left_over;
216
217       memcpy (&ctx->buffer[left_over], buffer, add);
218       ctx->buflen += add;
219
220       if (ctx->buflen > 64)
221         {
222           sha_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
223
224           ctx->buflen &= 63;
225           /* The regions in the following copy operation cannot overlap.  */
226           memcpy (ctx->buffer, &ctx->buffer[(left_over + add) & ~63],
227                   ctx->buflen);
228         }
229
230       buffer = (const char *) buffer + add;
231       len -= add;
232     }
233
234   /* Process available complete blocks.  */
235   if (len >= 64)
236     {
237 #if !_STRING_ARCH_unaligned
238 /* To check alignment gcc has an appropriate operator.  Other
239    compilers don't.  */
240 # if __GNUC__ >= 2
241 #  define UNALIGNED_P(p) (((md5_uintptr) p) % __alignof__ (md5_uint32) != 0)
242 # else
243 #  define UNALIGNED_P(p) (((md5_uintptr) p) % sizeof (md5_uint32) != 0)
244 # endif
245       if (UNALIGNED_P (buffer))
246         while (len > 64)
247           {
248             sha_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
249             buffer = (const char *) buffer + 64;
250             len -= 64;
251           }
252       else
253 #endif
254         {
255           sha_process_block (buffer, len & ~63, ctx);
256           buffer = (const char *) buffer + (len & ~63);
257           len &= 63;
258         }
259     }
260
261   /* Move remaining bytes in internal buffer.  */
262   if (len > 0)
263     {
264       size_t left_over = ctx->buflen;
265
266       memcpy (&ctx->buffer[left_over], buffer, len);
267       left_over += len;
268       if (left_over >= 64)
269         {
270           sha_process_block (ctx->buffer, 64, ctx);
271           left_over -= 64;
272           memcpy (ctx->buffer, &ctx->buffer[64], left_over);
273         }
274       ctx->buflen = left_over;
275     }
276 }
277
278 /* --- Code below is the primary difference between md5.c and sha.c --- */
279
280 /* SHA1 round constants */
281 #define K1 0x5a827999L
282 #define K2 0x6ed9eba1L
283 #define K3 0x8f1bbcdcL
284 #define K4 0xca62c1d6L
285
286 /* Round functions.  Note that F2 is the same as F4.  */
287 #define F1(B,C,D) ( D ^ ( B & ( C ^ D ) ) )
288 #define F2(B,C,D) (B ^ C ^ D)
289 #define F3(B,C,D) ( ( B & C ) | ( D & ( B | C ) ) )
290 #define F4(B,C,D) (B ^ C ^ D)
291
292 /* Process LEN bytes of BUFFER, accumulating context into CTX.
293    It is assumed that LEN % 64 == 0.
294    Most of this code comes from GnuPG's cipher/sha1.c.  */
295
296 void
297 sha_process_block (const void *buffer, size_t len, struct sha_ctx *ctx)
298 {
299   const md5_uint32 *words = buffer;
300   size_t nwords = len / sizeof (md5_uint32);
301   const md5_uint32 *endp = words + nwords;
302   md5_uint32 x[16];
303   md5_uint32 a = ctx->A;
304   md5_uint32 b = ctx->B;
305   md5_uint32 c = ctx->C;
306   md5_uint32 d = ctx->D;
307   md5_uint32 e = ctx->E;
308
309   /* First increment the byte count.  RFC 1321 specifies the possible
310      length of the file up to 2^64 bits.  Here we only compute the
311      number of bytes.  Do a double word increment.  */
312   ctx->total[0] += len;
313   if (ctx->total[0] < len)
314     ++ctx->total[1];
315
316 #define M(I) ( tm =   x[I&0x0f] ^ x[(I-14)&0x0f] \
317                     ^ x[(I-8)&0x0f] ^ x[(I-3)&0x0f] \
318                , (x[I&0x0f] = rol(tm, 1)) )
319
320 #define R(A,B,C,D,E,F,K,M)  do { E += rol( A, 5 )     \
321                                       + F( B, C, D )  \
322                                       + K             \
323                                       + M;            \
324                                  B = rol( B, 30 );    \
325                                } while(0)
326
327   while (words < endp)
328     {
329       md5_uint32 tm;
330       int t;
331       /* FIXME: see sha1.c for a better implementation.  */
332       for (t = 0; t < 16; t++)
333         {
334           x[t] = NOTSWAP (*words);
335           words++;
336         }
337
338       R( a, b, c, d, e, F1, K1, x[ 0] );
339       R( e, a, b, c, d, F1, K1, x[ 1] );
340       R( d, e, a, b, c, F1, K1, x[ 2] );
341       R( c, d, e, a, b, F1, K1, x[ 3] );
342       R( b, c, d, e, a, F1, K1, x[ 4] );
343       R( a, b, c, d, e, F1, K1, x[ 5] );
344       R( e, a, b, c, d, F1, K1, x[ 6] );
345       R( d, e, a, b, c, F1, K1, x[ 7] );
346       R( c, d, e, a, b, F1, K1, x[ 8] );
347       R( b, c, d, e, a, F1, K1, x[ 9] );
348       R( a, b, c, d, e, F1, K1, x[10] );
349       R( e, a, b, c, d, F1, K1, x[11] );
350       R( d, e, a, b, c, F1, K1, x[12] );
351       R( c, d, e, a, b, F1, K1, x[13] );
352       R( b, c, d, e, a, F1, K1, x[14] );
353       R( a, b, c, d, e, F1, K1, x[15] );
354       R( e, a, b, c, d, F1, K1, M(16) );
355       R( d, e, a, b, c, F1, K1, M(17) );
356       R( c, d, e, a, b, F1, K1, M(18) );
357       R( b, c, d, e, a, F1, K1, M(19) );
358       R( a, b, c, d, e, F2, K2, M(20) );
359       R( e, a, b, c, d, F2, K2, M(21) );
360       R( d, e, a, b, c, F2, K2, M(22) );
361       R( c, d, e, a, b, F2, K2, M(23) );
362       R( b, c, d, e, a, F2, K2, M(24) );
363       R( a, b, c, d, e, F2, K2, M(25) );
364       R( e, a, b, c, d, F2, K2, M(26) );
365       R( d, e, a, b, c, F2, K2, M(27) );
366       R( c, d, e, a, b, F2, K2, M(28) );
367       R( b, c, d, e, a, F2, K2, M(29) );
368       R( a, b, c, d, e, F2, K2, M(30) );
369       R( e, a, b, c, d, F2, K2, M(31) );
370       R( d, e, a, b, c, F2, K2, M(32) );
371       R( c, d, e, a, b, F2, K2, M(33) );
372       R( b, c, d, e, a, F2, K2, M(34) );
373       R( a, b, c, d, e, F2, K2, M(35) );
374       R( e, a, b, c, d, F2, K2, M(36) );
375       R( d, e, a, b, c, F2, K2, M(37) );
376       R( c, d, e, a, b, F2, K2, M(38) );
377       R( b, c, d, e, a, F2, K2, M(39) );
378       R( a, b, c, d, e, F3, K3, M(40) );
379       R( e, a, b, c, d, F3, K3, M(41) );
380       R( d, e, a, b, c, F3, K3, M(42) );
381       R( c, d, e, a, b, F3, K3, M(43) );
382       R( b, c, d, e, a, F3, K3, M(44) );
383       R( a, b, c, d, e, F3, K3, M(45) );
384       R( e, a, b, c, d, F3, K3, M(46) );
385       R( d, e, a, b, c, F3, K3, M(47) );
386       R( c, d, e, a, b, F3, K3, M(48) );
387       R( b, c, d, e, a, F3, K3, M(49) );
388       R( a, b, c, d, e, F3, K3, M(50) );
389       R( e, a, b, c, d, F3, K3, M(51) );
390       R( d, e, a, b, c, F3, K3, M(52) );
391       R( c, d, e, a, b, F3, K3, M(53) );
392       R( b, c, d, e, a, F3, K3, M(54) );
393       R( a, b, c, d, e, F3, K3, M(55) );
394       R( e, a, b, c, d, F3, K3, M(56) );
395       R( d, e, a, b, c, F3, K3, M(57) );
396       R( c, d, e, a, b, F3, K3, M(58) );
397       R( b, c, d, e, a, F3, K3, M(59) );
398       R( a, b, c, d, e, F4, K4, M(60) );
399       R( e, a, b, c, d, F4, K4, M(61) );
400       R( d, e, a, b, c, F4, K4, M(62) );
401       R( c, d, e, a, b, F4, K4, M(63) );
402       R( b, c, d, e, a, F4, K4, M(64) );
403       R( a, b, c, d, e, F4, K4, M(65) );
404       R( e, a, b, c, d, F4, K4, M(66) );
405       R( d, e, a, b, c, F4, K4, M(67) );
406       R( c, d, e, a, b, F4, K4, M(68) );
407       R( b, c, d, e, a, F4, K4, M(69) );
408       R( a, b, c, d, e, F4, K4, M(70) );
409       R( e, a, b, c, d, F4, K4, M(71) );
410       R( d, e, a, b, c, F4, K4, M(72) );
411       R( c, d, e, a, b, F4, K4, M(73) );
412       R( b, c, d, e, a, F4, K4, M(74) );
413       R( a, b, c, d, e, F4, K4, M(75) );
414       R( e, a, b, c, d, F4, K4, M(76) );
415       R( d, e, a, b, c, F4, K4, M(77) );
416       R( c, d, e, a, b, F4, K4, M(78) );
417       R( b, c, d, e, a, F4, K4, M(79) );
418
419       a = ctx->A += a;
420       b = ctx->B += b;
421       c = ctx->C += c;
422       d = ctx->D += d;
423       e = ctx->E += e;
424     }
425 }