]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/apr/random/unix/sha2.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / apr / random / unix / sha2.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 /*
17  * FILE:        sha2.c
18  * AUTHOR:      Aaron D. Gifford <me@aarongifford.com>
19  *
20  * A licence was granted to the ASF by Aaron on 4 November 2003.
21  */
22
23 #include <string.h>     /* memcpy()/memset() or bcopy()/bzero() */
24 #include <assert.h>     /* assert() */
25 #include "sha2.h"
26
27 /*
28  * ASSERT NOTE:
29  * Some sanity checking code is included using assert().  On my FreeBSD
30  * system, this additional code can be removed by compiling with NDEBUG
31  * defined.  Check your own systems manpage on assert() to see how to
32  * compile WITHOUT the sanity checking code on your system.
33  *
34  * UNROLLED TRANSFORM LOOP NOTE:
35  * You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform
36  * loop version for the hash transform rounds (defined using macros
37  * later in this file).  Either define on the command line, for example:
38  *
39  *   cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c
40  *
41  * or define below:
42  *
43  *   #define SHA2_UNROLL_TRANSFORM
44  *
45  */
46
47 /*** SHA-256/384/512 Machine Architecture Definitions *****************/
48 typedef apr_byte_t   sha2_byte;         /* Exactly 1 byte */
49 typedef apr_uint32_t sha2_word32;       /* Exactly 4 bytes */
50 typedef apr_uint64_t sha2_word64;       /* Exactly 8 bytes */
51
52 /*** SHA-256/384/512 Various Length Definitions ***********************/
53 /* NOTE: Most of these are in sha2.h */
54 #define SHA256_SHORT_BLOCK_LENGTH       (SHA256_BLOCK_LENGTH - 8)
55
56
57 /*** ENDIAN REVERSAL MACROS *******************************************/
58 #if !APR_IS_BIGENDIAN
59 #define REVERSE32(w,x)  { \
60         sha2_word32 tmp = (w); \
61         tmp = (tmp >> 16) | (tmp << 16); \
62         (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \
63 }
64 #define REVERSE64(w,x)  { \
65         sha2_word64 tmp = (w); \
66         tmp = (tmp >> 32) | (tmp << 32); \
67         tmp = ((tmp & APR_UINT64_C(0xff00ff00ff00ff00)) >> 8) | \
68               ((tmp & APR_UINT64_C(0x00ff00ff00ff00ff)) << 8); \
69         (x) = ((tmp & APR_UINT64_C(0xffff0000ffff0000)) >> 16) | \
70               ((tmp & APR_UINT64_C(0x0000ffff0000ffff)) << 16); \
71 }
72 #endif /* !APR_IS_BIGENDIAN */
73
74 /*
75  * Macro for incrementally adding the unsigned 64-bit integer n to the
76  * unsigned 128-bit integer (represented using a two-element array of
77  * 64-bit words):
78  */
79 #define ADDINC128(w,n)  { \
80         (w)[0] += (sha2_word64)(n); \
81         if ((w)[0] < (n)) { \
82                 (w)[1]++; \
83         } \
84 }
85
86 /*
87  * Macros for copying blocks of memory and for zeroing out ranges
88  * of memory.  Using these macros makes it easy to switch from
89  * using memset()/memcpy() and using bzero()/bcopy().
90  *
91  * Please define either SHA2_USE_MEMSET_MEMCPY or define
92  * SHA2_USE_BZERO_BCOPY depending on which function set you
93  * choose to use:
94  */
95 #if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY)
96 /* Default to memset()/memcpy() if no option is specified */
97 #define SHA2_USE_MEMSET_MEMCPY  1
98 #endif
99 #if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY)
100 /* Abort with an error if BOTH options are defined */
101 #error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both!
102 #endif
103
104 #ifdef SHA2_USE_MEMSET_MEMCPY
105 #define MEMSET_BZERO(p,l)       memset((p), 0, (l))
106 #define MEMCPY_BCOPY(d,s,l)     memcpy((d), (s), (l))
107 #endif
108 #ifdef SHA2_USE_BZERO_BCOPY
109 #define MEMSET_BZERO(p,l)       bzero((p), (l))
110 #define MEMCPY_BCOPY(d,s,l)     bcopy((s), (d), (l))
111 #endif
112
113
114 /*** THE SIX LOGICAL FUNCTIONS ****************************************/
115 /*
116  * Bit shifting and rotation (used by the six SHA-XYZ logical functions:
117  *
118  *   NOTE:  The naming of R and S appears backwards here (R is a SHIFT and
119  *   S is a ROTATION) because the SHA-256/384/512 description document
120  *   (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this
121  *   same "backwards" definition.
122  */
123 /* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
124 #define R(b,x)          ((x) >> (b))
125 /* 32-bit Rotate-right (used in SHA-256): */
126 #define S32(b,x)        (((x) >> (b)) | ((x) << (32 - (b))))
127 /* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
128 #define S64(b,x)        (((x) >> (b)) | ((x) << (64 - (b))))
129
130 /* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */
131 #define Ch(x,y,z)       (((x) & (y)) ^ ((~(x)) & (z)))
132 #define Maj(x,y,z)      (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
133
134 /* Four of six logical functions used in SHA-256: */
135 #define Sigma0_256(x)   (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))
136 #define Sigma1_256(x)   (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
137 #define sigma0_256(x)   (S32(7,  (x)) ^ S32(18, (x)) ^ R(3 ,   (x)))
138 #define sigma1_256(x)   (S32(17, (x)) ^ S32(19, (x)) ^ R(10,   (x)))
139
140 /* Four of six logical functions used in SHA-384 and SHA-512: */
141 #define Sigma0_512(x)   (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x)))
142 #define Sigma1_512(x)   (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x)))
143 #define sigma0_512(x)   (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7,   (x)))
144 #define sigma1_512(x)   (S64(19, (x)) ^ S64(61, (x)) ^ R( 6,   (x)))
145
146 /*** INTERNAL FUNCTION PROTOTYPES *************************************/
147 /* NOTE: These should not be accessed directly from outside this
148  * library -- they are intended for private internal visibility/use
149  * only.
150  */
151 void apr__SHA256_Transform(SHA256_CTX*, const sha2_word32*);
152
153
154 /*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
155 /* Hash constant words K for SHA-256: */
156 static const sha2_word32 K256[64] = {
157         0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL,
158         0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL,
159         0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL,
160         0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL,
161         0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
162         0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL,
163         0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL,
164         0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL,
165         0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL,
166         0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
167         0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL,
168         0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL,
169         0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL,
170         0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL,
171         0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
172         0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
173 };
174
175 /* Initial hash value H for SHA-256: */
176 static const sha2_word32 sha256_initial_hash_value[8] = {
177         0x6a09e667UL,
178         0xbb67ae85UL,
179         0x3c6ef372UL,
180         0xa54ff53aUL,
181         0x510e527fUL,
182         0x9b05688cUL,
183         0x1f83d9abUL,
184         0x5be0cd19UL
185 };
186
187 /*
188  * Constant used by SHA256/384/512_End() functions for converting the
189  * digest to a readable hexadecimal character string:
190  */
191 static const char *sha2_hex_digits = "0123456789abcdef";
192
193
194 /*** SHA-256: *********************************************************/
195 void apr__SHA256_Init(SHA256_CTX* context) {
196         if (context == (SHA256_CTX*)0) {
197                 return;
198         }
199         MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH);
200         MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH);
201         context->bitcount = 0;
202 }
203
204 #ifdef SHA2_UNROLL_TRANSFORM
205
206 /* Unrolled SHA-256 round macros: */
207
208 #if !APR_IS_BIGENDIAN
209
210 #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h)       \
211         REVERSE32(*data++, W256[j]); \
212         T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
213              K256[j] + W256[j]; \
214         (d) += T1; \
215         (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
216         j++
217
218
219 #else /* APR_IS_BIGENDIAN */
220
221 #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h)       \
222         T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
223              K256[j] + (W256[j] = *data++); \
224         (d) += T1; \
225         (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
226         j++
227
228 #endif /* APR_IS_BIGENDIAN */
229
230 #define ROUND256(a,b,c,d,e,f,g,h)       \
231         s0 = W256[(j+1)&0x0f]; \
232         s0 = sigma0_256(s0); \
233         s1 = W256[(j+14)&0x0f]; \
234         s1 = sigma1_256(s1); \
235         T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \
236              (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \
237         (d) += T1; \
238         (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
239         j++
240
241 void apr__SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
242         sha2_word32     a, b, c, d, e, f, g, h, s0, s1;
243         sha2_word32     T1, *W256;
244         int             j;
245
246         W256 = (sha2_word32*)context->buffer;
247
248         /* Initialize registers with the prev. intermediate value */
249         a = context->state[0];
250         b = context->state[1];
251         c = context->state[2];
252         d = context->state[3];
253         e = context->state[4];
254         f = context->state[5];
255         g = context->state[6];
256         h = context->state[7];
257
258         j = 0;
259         do {
260                 /* Rounds 0 to 15 (unrolled): */
261                 ROUND256_0_TO_15(a,b,c,d,e,f,g,h);
262                 ROUND256_0_TO_15(h,a,b,c,d,e,f,g);
263                 ROUND256_0_TO_15(g,h,a,b,c,d,e,f);
264                 ROUND256_0_TO_15(f,g,h,a,b,c,d,e);
265                 ROUND256_0_TO_15(e,f,g,h,a,b,c,d);
266                 ROUND256_0_TO_15(d,e,f,g,h,a,b,c);
267                 ROUND256_0_TO_15(c,d,e,f,g,h,a,b);
268                 ROUND256_0_TO_15(b,c,d,e,f,g,h,a);
269         } while (j < 16);
270
271         /* Now for the remaining rounds to 64: */
272         do {
273                 ROUND256(a,b,c,d,e,f,g,h);
274                 ROUND256(h,a,b,c,d,e,f,g);
275                 ROUND256(g,h,a,b,c,d,e,f);
276                 ROUND256(f,g,h,a,b,c,d,e);
277                 ROUND256(e,f,g,h,a,b,c,d);
278                 ROUND256(d,e,f,g,h,a,b,c);
279                 ROUND256(c,d,e,f,g,h,a,b);
280                 ROUND256(b,c,d,e,f,g,h,a);
281         } while (j < 64);
282
283         /* Compute the current intermediate hash value */
284         context->state[0] += a;
285         context->state[1] += b;
286         context->state[2] += c;
287         context->state[3] += d;
288         context->state[4] += e;
289         context->state[5] += f;
290         context->state[6] += g;
291         context->state[7] += h;
292
293         /* Clean up */
294         a = b = c = d = e = f = g = h = T1 = 0;
295 }
296
297 #else /* SHA2_UNROLL_TRANSFORM */
298
299 void apr__SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) {
300         sha2_word32     a, b, c, d, e, f, g, h, s0, s1;
301         sha2_word32     T1, T2, *W256;
302         int             j;
303
304         W256 = (sha2_word32*)context->buffer;
305
306         /* Initialize registers with the prev. intermediate value */
307         a = context->state[0];
308         b = context->state[1];
309         c = context->state[2];
310         d = context->state[3];
311         e = context->state[4];
312         f = context->state[5];
313         g = context->state[6];
314         h = context->state[7];
315
316         j = 0;
317         do {
318 #if !APR_IS_BIGENDIAN
319                 /* Copy data while converting to host byte order */
320                 REVERSE32(*data++,W256[j]);
321                 /* Apply the SHA-256 compression function to update a..h */
322                 T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j];
323 #else /* APR_IS_BIGENDIAN */
324                 /* Apply the SHA-256 compression function to update a..h with copy */
325                 T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++);
326 #endif /* APR_IS_BIGENDIAN */
327                 T2 = Sigma0_256(a) + Maj(a, b, c);
328                 h = g;
329                 g = f;
330                 f = e;
331                 e = d + T1;
332                 d = c;
333                 c = b;
334                 b = a;
335                 a = T1 + T2;
336
337                 j++;
338         } while (j < 16);
339
340         do {
341                 /* Part of the message block expansion: */
342                 s0 = W256[(j+1)&0x0f];
343                 s0 = sigma0_256(s0);
344                 s1 = W256[(j+14)&0x0f]; 
345                 s1 = sigma1_256(s1);
346
347                 /* Apply the SHA-256 compression function to update a..h */
348                 T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + 
349                      (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
350                 T2 = Sigma0_256(a) + Maj(a, b, c);
351                 h = g;
352                 g = f;
353                 f = e;
354                 e = d + T1;
355                 d = c;
356                 c = b;
357                 b = a;
358                 a = T1 + T2;
359
360                 j++;
361         } while (j < 64);
362
363         /* Compute the current intermediate hash value */
364         context->state[0] += a;
365         context->state[1] += b;
366         context->state[2] += c;
367         context->state[3] += d;
368         context->state[4] += e;
369         context->state[5] += f;
370         context->state[6] += g;
371         context->state[7] += h;
372
373         /* Clean up */
374         a = b = c = d = e = f = g = h = T1 = T2 = 0;
375 }
376
377 #endif /* SHA2_UNROLL_TRANSFORM */
378
379 void apr__SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) {
380         unsigned int    freespace, usedspace;
381
382         if (len == 0) {
383                 /* Calling with no data is valid - we do nothing */
384                 return;
385         }
386
387         /* Sanity check: */
388         assert(context != (SHA256_CTX*)0 && data != (sha2_byte*)0);
389
390         usedspace = (unsigned int)((context->bitcount >> 3) 
391                                  % SHA256_BLOCK_LENGTH);
392         if (usedspace > 0) {
393                 /* Calculate how much free space is available in the buffer */
394                 freespace = SHA256_BLOCK_LENGTH - usedspace;
395
396                 if (len >= freespace) {
397                         /* Fill the buffer completely and process it */
398                         MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
399                         context->bitcount += freespace << 3;
400                         len -= freespace;
401                         data += freespace;
402                         apr__SHA256_Transform(context, (sha2_word32*)context->buffer);
403                 } else {
404                         /* The buffer is not yet full */
405                         MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
406                         context->bitcount += len << 3;
407                         /* Clean up: */
408                         usedspace = freespace = 0;
409                         return;
410                 }
411         }
412         while (len >= SHA256_BLOCK_LENGTH) {
413                 /* Process as many complete blocks as we can */
414                 apr__SHA256_Transform(context, (sha2_word32*)data);
415                 context->bitcount += SHA256_BLOCK_LENGTH << 3;
416                 len -= SHA256_BLOCK_LENGTH;
417                 data += SHA256_BLOCK_LENGTH;
418         }
419         if (len > 0) {
420                 /* There's left-overs, so save 'em */
421                 MEMCPY_BCOPY(context->buffer, data, len);
422                 context->bitcount += len << 3;
423         }
424         /* Clean up: */
425         usedspace = freespace = 0;
426 }
427
428 void apr__SHA256_Final(sha2_byte digest[], SHA256_CTX* context) {
429         sha2_word32     *d = (sha2_word32*)digest;
430         unsigned int    usedspace;
431
432         /* Sanity check: */
433         assert(context != (SHA256_CTX*)0);
434
435         /* If no digest buffer is passed, we don't bother doing this: */
436         if (digest != (sha2_byte*)0) {
437                 usedspace = (unsigned int)((context->bitcount >> 3) 
438                                          % SHA256_BLOCK_LENGTH);
439 #if !APR_IS_BIGENDIAN
440                 /* Convert FROM host byte order */
441                 REVERSE64(context->bitcount,context->bitcount);
442 #endif
443                 if (usedspace > 0) {
444                         /* Begin padding with a 1 bit: */
445                         context->buffer[usedspace++] = 0x80;
446
447                         if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) {
448                                 /* Set-up for the last transform: */
449                                 MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace);
450                         } else {
451                                 if (usedspace < SHA256_BLOCK_LENGTH) {
452                                         MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace);
453                                 }
454                                 /* Do second-to-last transform: */
455                                 apr__SHA256_Transform(context, (sha2_word32*)context->buffer);
456
457                                 /* And set-up for the last transform: */
458                                 MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
459                         }
460                 } else {
461                         /* Set-up for the last transform: */
462                         MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH);
463
464                         /* Begin padding with a 1 bit: */
465                         *context->buffer = 0x80;
466                 }
467                 /* Set the bit count: */
468                 {
469                         union dummy {
470                                 apr_uint64_t bitcount;
471                                 apr_byte_t bytes[8];
472                         } bitcount;
473                         bitcount.bitcount = context->bitcount;
474                         MEMCPY_BCOPY(&context->buffer[SHA256_SHORT_BLOCK_LENGTH], bitcount.bytes, 8);
475                 }
476
477                 /* Final transform: */
478                 apr__SHA256_Transform(context, (sha2_word32*)context->buffer);
479
480 #if !APR_IS_BIGENDIAN
481                 {
482                         /* Convert TO host byte order */
483                         int     j;
484                         for (j = 0; j < 8; j++) {
485                                 REVERSE32(context->state[j],context->state[j]);
486                                 *d++ = context->state[j];
487                         }
488                 }
489 #else
490                 MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH);
491 #endif
492         }
493
494         /* Clean up state data: */
495         MEMSET_BZERO(context, sizeof(*context));
496         usedspace = 0;
497 }
498
499 char *apr__SHA256_End(SHA256_CTX* context, char buffer[]) {
500         sha2_byte       digest[SHA256_DIGEST_LENGTH], *d = digest;
501         int             i;
502
503         /* Sanity check: */
504         assert(context != (SHA256_CTX*)0);
505
506         if (buffer != (char*)0) {
507                 apr__SHA256_Final(digest, context);
508
509                 for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
510                         *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
511                         *buffer++ = sha2_hex_digits[*d & 0x0f];
512                         d++;
513                 }
514                 *buffer = (char)0;
515         } else {
516                 MEMSET_BZERO(context, sizeof(*context));
517         }
518         MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH);
519         return buffer;
520 }
521
522 char* apr__SHA256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) {
523         SHA256_CTX      context;
524
525         apr__SHA256_Init(&context);
526         apr__SHA256_Update(&context, data, len);
527         return apr__SHA256_End(&context, digest);
528 }