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