*** empty log message ***
[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 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
28 /*
29   Not-swap is a macro that does an endian swap on architectures that are
30   big-endian, as SHA needs some data in a little-endian format
31 */
32
33 #ifdef WORDS_BIGENDIAN
34 # define NOTSWAP(n) (n)
35 # define SWAP(n)                                                        \
36     (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
37 #else
38 # define NOTSWAP(n)                                                         \
39     (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
40 # define SWAP(n) (n)
41 #endif
42
43 /* This array contains the bytes used to pad the buffer to the next
44    64-byte boundary.  (RFC 1321, 3.1: Step 1)  */
45 static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ...  */ };
46
47
48 /*
49   Takes a pointer to a 160 bit block of data (five 32 bit ints) and
50   intializes it to the start constants of the SHA1 algorithm.  This
51   must be called before using hash in the call to sha_hash
52 */
53 void
54 sha_init_ctx (struct sha_ctx *ctx)
55 {
56   ctx->A = 0x67452301;
57   ctx->B = 0xefcdab89;
58   ctx->C = 0x98badcfe;
59   ctx->D = 0x10325476;
60   ctx->E = 0xc3d2e1f0;
61
62   ctx->total[0] = ctx->total[1] = 0;
63   ctx->buflen = 0;
64 }
65
66 /* Put result from CTX in first 20 bytes following RESBUF.  The result
67    must be in little endian byte order.
68
69    IMPORTANT: On some systems it is required that RESBUF is correctly
70    aligned for a 32 bits value.  */
71 void *
72 sha_read_ctx (const struct sha_ctx *ctx, void *resbuf)
73 {
74   ((md5_uint32 *) resbuf)[0] = NOTSWAP (ctx->A);
75   ((md5_uint32 *) resbuf)[1] = NOTSWAP (ctx->B);
76   ((md5_uint32 *) resbuf)[2] = NOTSWAP (ctx->C);
77   ((md5_uint32 *) resbuf)[3] = NOTSWAP (ctx->D);
78   ((md5_uint32 *) resbuf)[4] = NOTSWAP (ctx->E);
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 sha_finish_ctx (struct sha_ctx *ctx, void *resbuf)
90 {
91   /* Take yet unprocessed bytes into account.  */
92   md5_uint32 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 (&ctx->buffer[bytes], fillbuf, pad);
102
103   /* Put the 64-bit file length in *bits* at the end of the buffer.  */
104   *(md5_uint32 *) &ctx->buffer[bytes + pad + 4] = NOTSWAP (ctx->total[0] << 3);
105   *(md5_uint32 *) &ctx->buffer[bytes + pad] = NOTSWAP ((ctx->total[1] << 3) |
106                                                     (ctx->total[0] >> 29));
107
108   /* Process last bytes.  */
109   sha_process_block (ctx->buffer, bytes + pad + 8, ctx);
110
111   return sha_read_ctx (ctx, resbuf);
112 }
113
114 /* Compute SHA1 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 sha_stream (FILE *stream, void *resblock)
119 {
120   /* Important: BLOCKSIZE must be a multiple of 64.  */
121 #define BLOCKSIZE 4096
122   struct sha_ctx ctx;
123   char buffer[BLOCKSIZE + 72];
124   size_t sum;
125
126   /* Initialize the computation context.  */
127   sha_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       do
140         {
141           n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
142
143           sum += n;
144         }
145       while (sum < BLOCKSIZE && n != 0);
146       if (n == 0 && ferror (stream))
147         return 1;
148
149       /* If end of file is reached, end the loop.  */
150       if (n == 0)
151         break;
152
153       /* Process buffer with BLOCKSIZE bytes.  Note that
154                         BLOCKSIZE % 64 == 0
155        */
156       sha_process_block (buffer, BLOCKSIZE, &ctx);
157     }
158
159   /* Add the last bytes if necessary.  */
160   if (sum > 0)
161     sha_process_bytes (buffer, sum, &ctx);
162
163   /* Construct result in desired memory.  */
164   sha_finish_ctx (&ctx, resblock);
165   return 0;
166 }
167
168 /* Compute MD5 message digest for LEN bytes beginning at BUFFER.  The
169    result is always in little endian byte order, so that a byte-wise
170    output yields to the wanted ASCII representation of the message
171    digest.  */
172 void *
173 sha_buffer (const char *buffer, size_t len, void *resblock)
174 {
175   struct sha_ctx ctx;
176
177   /* Initialize the computation context.  */
178   sha_init_ctx (&ctx);
179
180   /* Process whole buffer but last len % 64 bytes.  */
181   sha_process_bytes (buffer, len, &ctx);
182
183   /* Put result in desired memory area.  */
184   return sha_finish_ctx (&ctx, resblock);
185 }
186
187 void
188 sha_process_bytes (const void *buffer, size_t len, struct sha_ctx *ctx)
189 {
190   /* When we already have some bits in our internal buffer concatenate
191      both inputs first.  */
192   if (ctx->buflen != 0)
193     {
194       size_t left_over = ctx->buflen;
195       size_t add = 128 - left_over > len ? len : 128 - left_over;
196
197       memcpy (&ctx->buffer[left_over], buffer, add);
198       ctx->buflen += add;
199
200       if (left_over + add > 64)
201         {
202           sha_process_block (ctx->buffer, (left_over + add) & ~63, ctx);
203           /* The regions in the following copy operation cannot overlap.  */
204           memcpy (ctx->buffer, &ctx->buffer[(left_over + add) & ~63],
205                   (left_over + add) & 63);
206           ctx->buflen = (left_over + add) & 63;
207         }
208
209       buffer = (const char *) buffer + add;
210       len -= add;
211     }
212
213   /* Process available complete blocks.  */
214   if (len > 64)
215     {
216       sha_process_block (buffer, len & ~63, ctx);
217       buffer = (const char *) buffer + (len & ~63);
218       len &= 63;
219     }
220
221   /* Move remaining bytes in internal buffer.  */
222   if (len > 0)
223     {
224       memcpy (ctx->buffer, buffer, len);
225       ctx->buflen = len;
226     }
227 }
228
229 /* --- Code below is the primary difference between md5.c and sha.c --- */
230
231 /* SHA1 round constants */
232 #define K1 0x5a827999L
233 #define K2 0x6ed9eba1L
234 #define K3 0x8f1bbcdcL
235 #define K4 0xca62c1d6L
236
237 /* Round functions.  Note that F2() is used in both rounds 2 and 4 */
238 #define F1(B,C,D) ( D ^ ( B & ( C ^ D ) ) )
239 #define F2(B,C,D) (B ^ C ^ D)
240 #define F3(B,C,D) ( ( B & C ) | ( D & ( B | C ) ) )
241
242 /* Process LEN bytes of BUFFER, accumulating context into CTX.
243    It is assumed that LEN % 64 == 0.  */
244
245 void
246 sha_process_block (const void *buffer, size_t len, struct sha_ctx *ctx)
247 {
248   const md5_uint32 *words = buffer;
249   size_t nwords = len / sizeof (md5_uint32);
250   const md5_uint32 *endp = words + nwords;
251   md5_uint32 W[80];
252   md5_uint32 A = ctx->A;
253   md5_uint32 B = ctx->B;
254   md5_uint32 C = ctx->C;
255   md5_uint32 D = ctx->D;
256   md5_uint32 E = ctx->E;
257
258   /* First increment the byte count.  RFC 1321 specifies the possible
259      length of the file up to 2^64 bits.  Here we only compute the
260      number of bytes.  Do a double word increment.  */
261   ctx->total[0] += len;
262   if (ctx->total[0] < len)
263     ++ctx->total[1];
264
265   while (words < endp)
266     {
267       int t;
268       for (t = 0; t < 16; t++)
269         {
270           W[t] = NOTSWAP (*words);
271           words++;
272         }
273
274       /* SHA1 Data expansion */
275       for (t = 16; t < 80; t++)
276         {
277           md5_uint32 tmp = W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16];
278           W[t] = rol (tmp, 1);
279         }
280
281       /* SHA1 main loop (t=0 to 79)
282          This is broken down into four subloops in order to use
283          the correct round function and constant */
284       for (t = 0; t < 20; t++)
285         {
286           md5_uint32 tmp = rol (A, 5) + F1 (B, C, D) + E + W[t] + K1;
287           E = D;
288           D = C;
289           C = rol (B, 30);
290           B = A;
291           A = tmp;
292         }
293       for (; t < 40; t++)
294         {
295           md5_uint32 tmp = rol (A, 5) + F2 (B, C, D) + E + W[t] + K2;
296           E = D;
297           D = C;
298           C = rol (B, 30);
299           B = A;
300           A = tmp;
301         }
302       for (; t < 60; t++)
303         {
304           md5_uint32 tmp = rol (A, 5) + F3 (B, C, D) + E + W[t] + K3;
305           E = D;
306           D = C;
307           C = rol (B, 30);
308           B = A;
309           A = tmp;
310         }
311       for (; t < 80; t++)
312         {
313           md5_uint32 tmp = rol (A, 5) + F2 (B, C, D) + E + W[t] + K4;
314           E = D;
315           D = C;
316           C = rol (B, 30);
317           B = A;
318           A = tmp;
319         }
320       A = ctx->A += A;
321       B = ctx->B += B;
322       C = ctx->C += C;
323       D = ctx->D += D;
324       E = ctx->E += E;
325     }
326 }