xref: /freebsd/contrib/unbound/compat/sha512.c (revision b077aed33b7b6aefca7b17ddb250cf521f938613)
1 /*
2  * FILE:	sha2.c
3  * AUTHOR:	Aaron D. Gifford - http://www.aarongifford.com/
4  *
5  * Copyright (c) 2000-2001, Aaron D. Gifford
6  * All rights reserved.
7  *
8  * Modified by Jelte Jansen to fit in ldns, and not clash with any
9  * system-defined SHA code.
10  * Changes:
11  * - Renamed (external) functions and constants to fit ldns style
12  * - Removed _End and _Data functions
13  * - Added ldns_shaX(data, len, digest) convenience functions
14  * - Removed prototypes of _Transform functions and made those static
15  * Modified by Wouter, and trimmed, to provide SHA512 for getentropy_fallback.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. Neither the name of the copyright holder nor the names of contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  * $Id: sha2.c,v 1.1 2001/11/08 00:01:51 adg Exp adg $
42  */
43 #include "config.h"
44 
45 #include <string.h>	/* memcpy()/memset() or bcopy()/bzero() */
46 #include <assert.h>	/* assert() */
47 
48 /* do we have sha512 header defs */
49 #ifndef SHA512_DIGEST_LENGTH
50 #define SHA512_BLOCK_LENGTH		128
51 #define SHA512_DIGEST_LENGTH		64
52 #define SHA512_DIGEST_STRING_LENGTH	(SHA512_DIGEST_LENGTH * 2 + 1)
53 typedef struct _SHA512_CTX {
54 	uint64_t	state[8];
55 	uint64_t	bitcount[2];
56 	uint8_t	buffer[SHA512_BLOCK_LENGTH];
57 } SHA512_CTX;
58 #endif /* do we have sha512 header defs */
59 
60 void SHA512_Init(SHA512_CTX*);
61 void SHA512_Update(SHA512_CTX*, void*, size_t);
62 void SHA512_Final(uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*);
63 unsigned char *SHA512(void *data, unsigned int data_len, unsigned char *digest);
64 
65 
66 /*** SHA-256/384/512 Machine Architecture Definitions *****************/
67 /*
68  * BYTE_ORDER NOTE:
69  *
70  * Please make sure that your system defines BYTE_ORDER.  If your
71  * architecture is little-endian, make sure it also defines
72  * LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are
73  * equivalent.
74  *
75  * If your system does not define the above, then you can do so by
76  * hand like this:
77  *
78  *   #define LITTLE_ENDIAN 1234
79  *   #define BIG_ENDIAN    4321
80  *
81  * And for little-endian machines, add:
82  *
83  *   #define BYTE_ORDER LITTLE_ENDIAN
84  *
85  * Or for big-endian machines:
86  *
87  *   #define BYTE_ORDER BIG_ENDIAN
88  *
89  * The FreeBSD machine this was written on defines BYTE_ORDER
90  * appropriately by including <sys/types.h> (which in turn includes
91  * <machine/endian.h> where the appropriate definitions are actually
92  * made).
93  */
94 #if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN)
95 #error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN
96 #endif
97 
98 typedef uint8_t  sha2_byte;	/* Exactly 1 byte */
99 typedef uint32_t sha2_word32;	/* Exactly 4 bytes */
100 #ifdef S_SPLINT_S
101 typedef unsigned long long sha2_word64; /* lint 8 bytes */
102 #else
103 typedef uint64_t sha2_word64;	/* Exactly 8 bytes */
104 #endif
105 
106 /*** SHA-256/384/512 Various Length Definitions ***********************/
107 #define SHA512_SHORT_BLOCK_LENGTH	(SHA512_BLOCK_LENGTH - 16)
108 
109 
110 /*** ENDIAN REVERSAL MACROS *******************************************/
111 #if BYTE_ORDER == LITTLE_ENDIAN
112 #define REVERSE32(w,x)	{ \
113 	sha2_word32 tmp = (w); \
114 	tmp = (tmp >> 16) | (tmp << 16); \
115 	(x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \
116 }
117 #ifndef S_SPLINT_S
118 #define REVERSE64(w,x)	{ \
119 	sha2_word64 tmp = (w); \
120 	tmp = (tmp >> 32) | (tmp << 32); \
121 	tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \
122 	      ((tmp & 0x00ff00ff00ff00ffULL) << 8); \
123 	(x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \
124 	      ((tmp & 0x0000ffff0000ffffULL) << 16); \
125 }
126 #else /* splint */
127 #define REVERSE64(w,x) /* splint */
128 #endif /* splint */
129 #endif /* BYTE_ORDER == LITTLE_ENDIAN */
130 
131 /*
132  * Macro for incrementally adding the unsigned 64-bit integer n to the
133  * unsigned 128-bit integer (represented using a two-element array of
134  * 64-bit words):
135  */
136 #define ADDINC128(w,n)	{ \
137 	(w)[0] += (sha2_word64)(n); \
138 	if ((w)[0] < (n)) { \
139 		(w)[1]++; \
140 	} \
141 }
142 #ifdef S_SPLINT_S
143 #undef ADDINC128
144 #define ADDINC128(w,n) /* splint */
145 #endif
146 
147 /*
148  * Macros for copying blocks of memory and for zeroing out ranges
149  * of memory.  Using these macros makes it easy to switch from
150  * using memset()/memcpy() and using bzero()/bcopy().
151  *
152  * Please define either SHA2_USE_MEMSET_MEMCPY or define
153  * SHA2_USE_BZERO_BCOPY depending on which function set you
154  * choose to use:
155  */
156 #if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY)
157 /* Default to memset()/memcpy() if no option is specified */
158 #define	SHA2_USE_MEMSET_MEMCPY	1
159 #endif
160 #if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY)
161 /* Abort with an error if BOTH options are defined */
162 #error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both!
163 #endif
164 
165 #ifdef SHA2_USE_MEMSET_MEMCPY
166 #define MEMSET_BZERO(p,l)	memset((p), 0, (l))
167 #define MEMCPY_BCOPY(d,s,l)	memcpy((d), (s), (l))
168 #endif
169 #ifdef SHA2_USE_BZERO_BCOPY
170 #define MEMSET_BZERO(p,l)	bzero((p), (l))
171 #define MEMCPY_BCOPY(d,s,l)	bcopy((s), (d), (l))
172 #endif
173 
174 
175 /*** THE SIX LOGICAL FUNCTIONS ****************************************/
176 /*
177  * Bit shifting and rotation (used by the six SHA-XYZ logical functions:
178  *
179  *   NOTE:  The naming of R and S appears backwards here (R is a SHIFT and
180  *   S is a ROTATION) because the SHA-256/384/512 description document
181  *   (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this
182  *   same "backwards" definition.
183  */
184 /* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
185 #define R(b,x) 		((x) >> (b))
186 /* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
187 #define S64(b,x)	(((x) >> (b)) | ((x) << (64 - (b))))
188 
189 /* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */
190 #define Ch(x,y,z)	(((x) & (y)) ^ ((~(x)) & (z)))
191 #define Maj(x,y,z)	(((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
192 
193 /* Four of six logical functions used in SHA-384 and SHA-512: */
194 #define Sigma0_512(x)	(S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x)))
195 #define Sigma1_512(x)	(S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x)))
196 #define sigma0_512(x)	(S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7,   (x)))
197 #define sigma1_512(x)	(S64(19, (x)) ^ S64(61, (x)) ^ R( 6,   (x)))
198 
199 /*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
200 /* Hash constant words K for SHA-384 and SHA-512: */
201 static const sha2_word64 K512[80] = {
202 	0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
203 	0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
204 	0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
205 	0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
206 	0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
207 	0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
208 	0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
209 	0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
210 	0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
211 	0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
212 	0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
213 	0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
214 	0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
215 	0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
216 	0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
217 	0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
218 	0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
219 	0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
220 	0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
221 	0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
222 	0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
223 	0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
224 	0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
225 	0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
226 	0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
227 	0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
228 	0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
229 	0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
230 	0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
231 	0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
232 	0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
233 	0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
234 	0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
235 	0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
236 	0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
237 	0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
238 	0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
239 	0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
240 	0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
241 	0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
242 };
243 
244 /* initial hash value H for SHA-512 */
245 static const sha2_word64 sha512_initial_hash_value[8] = {
246 	0x6a09e667f3bcc908ULL,
247 	0xbb67ae8584caa73bULL,
248 	0x3c6ef372fe94f82bULL,
249 	0xa54ff53a5f1d36f1ULL,
250 	0x510e527fade682d1ULL,
251 	0x9b05688c2b3e6c1fULL,
252 	0x1f83d9abfb41bd6bULL,
253 	0x5be0cd19137e2179ULL
254 };
255 
256 typedef union _ldns_sha2_buffer_union {
257         uint8_t*  theChars;
258         uint64_t* theLongs;
259 } ldns_sha2_buffer_union;
260 
261 /*** SHA-512: *********************************************************/
262 void SHA512_Init(SHA512_CTX* context) {
263 	if (context == (SHA512_CTX*)0) {
264 		return;
265 	}
266 	MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH);
267 	MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH);
268 	context->bitcount[0] = context->bitcount[1] =  0;
269 }
270 
271 static void SHA512_Transform(SHA512_CTX* context,
272                                   const sha2_word64* data) {
273 	sha2_word64	a, b, c, d, e, f, g, h, s0, s1;
274 	sha2_word64	T1, T2, *W512 = (sha2_word64*)context->buffer;
275 	int		j;
276 
277 	/* initialize registers with the prev. intermediate value */
278 	a = context->state[0];
279 	b = context->state[1];
280 	c = context->state[2];
281 	d = context->state[3];
282 	e = context->state[4];
283 	f = context->state[5];
284 	g = context->state[6];
285 	h = context->state[7];
286 
287 	j = 0;
288 	do {
289 #if BYTE_ORDER == LITTLE_ENDIAN
290 		/* Convert TO host byte order */
291 		REVERSE64(*data++, W512[j]);
292 		/* Apply the SHA-512 compression function to update a..h */
293 		T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j];
294 #else /* BYTE_ORDER == LITTLE_ENDIAN */
295 		/* Apply the SHA-512 compression function to update a..h with copy */
296 		T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++);
297 #endif /* BYTE_ORDER == LITTLE_ENDIAN */
298 		T2 = Sigma0_512(a) + Maj(a, b, c);
299 		h = g;
300 		g = f;
301 		f = e;
302 		e = d + T1;
303 		d = c;
304 		c = b;
305 		b = a;
306 		a = T1 + T2;
307 
308 		j++;
309 	} while (j < 16);
310 
311 	do {
312 		/* Part of the message block expansion: */
313 		s0 = W512[(j+1)&0x0f];
314 		s0 = sigma0_512(s0);
315 		s1 = W512[(j+14)&0x0f];
316 		s1 =  sigma1_512(s1);
317 
318 		/* Apply the SHA-512 compression function to update a..h */
319 		T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
320 		     (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
321 		T2 = Sigma0_512(a) + Maj(a, b, c);
322 		h = g;
323 		g = f;
324 		f = e;
325 		e = d + T1;
326 		d = c;
327 		c = b;
328 		b = a;
329 		a = T1 + T2;
330 
331 		j++;
332 	} while (j < 80);
333 
334 	/* Compute the current intermediate hash value */
335 	context->state[0] += a;
336 	context->state[1] += b;
337 	context->state[2] += c;
338 	context->state[3] += d;
339 	context->state[4] += e;
340 	context->state[5] += f;
341 	context->state[6] += g;
342 	context->state[7] += h;
343 
344 	/* Clean up */
345 	a = b = c = d = e = f = g = h = T1 = T2 = 0;
346 }
347 
348 void SHA512_Update(SHA512_CTX* context, void *datain, size_t len) {
349 	size_t freespace, usedspace;
350 	const sha2_byte* data = (const sha2_byte*)datain;
351 
352 	if (len == 0) {
353 		/* Calling with no data is valid - we do nothing */
354 		return;
355 	}
356 
357 	/* Sanity check: */
358 	assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0);
359 
360 	usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
361 	if (usedspace > 0) {
362 		/* Calculate how much free space is available in the buffer */
363 		freespace = SHA512_BLOCK_LENGTH - usedspace;
364 
365 		if (len >= freespace) {
366 			/* Fill the buffer completely and process it */
367 			MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace);
368 			ADDINC128(context->bitcount, freespace << 3);
369 			len -= freespace;
370 			data += freespace;
371 			SHA512_Transform(context, (sha2_word64*)context->buffer);
372 		} else {
373 			/* The buffer is not yet full */
374 			MEMCPY_BCOPY(&context->buffer[usedspace], data, len);
375 			ADDINC128(context->bitcount, len << 3);
376 			/* Clean up: */
377 			usedspace = freespace = 0;
378 			return;
379 		}
380 	}
381 	while (len >= SHA512_BLOCK_LENGTH) {
382 		/* Process as many complete blocks as we can */
383 		SHA512_Transform(context, (sha2_word64*)data);
384 		ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
385 		len -= SHA512_BLOCK_LENGTH;
386 		data += SHA512_BLOCK_LENGTH;
387 	}
388 	if (len > 0) {
389 		/* There's left-overs, so save 'em */
390 		MEMCPY_BCOPY(context->buffer, data, len);
391 		ADDINC128(context->bitcount, len << 3);
392 	}
393 	/* Clean up: */
394 	usedspace = freespace = 0;
395 }
396 
397 static void SHA512_Last(SHA512_CTX* context) {
398 	size_t usedspace;
399 	ldns_sha2_buffer_union cast_var;
400 
401 	usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
402 #if BYTE_ORDER == LITTLE_ENDIAN
403 	/* Convert FROM host byte order */
404 	REVERSE64(context->bitcount[0],context->bitcount[0]);
405 	REVERSE64(context->bitcount[1],context->bitcount[1]);
406 #endif
407 	if (usedspace > 0) {
408 		/* Begin padding with a 1 bit: */
409 		context->buffer[usedspace++] = 0x80;
410 
411 		if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) {
412 			/* Set-up for the last transform: */
413 			MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace);
414 		} else {
415 			if (usedspace < SHA512_BLOCK_LENGTH) {
416 				MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace);
417 			}
418 			/* Do second-to-last transform: */
419 			SHA512_Transform(context, (sha2_word64*)context->buffer);
420 
421 			/* And set-up for the last transform: */
422 			MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2);
423 		}
424 	} else {
425 		/* Prepare for final transform: */
426 		MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH);
427 
428 		/* Begin padding with a 1 bit: */
429 		*context->buffer = 0x80;
430 	}
431 	/* Store the length of input data (in bits): */
432 	cast_var.theChars = context->buffer;
433 	cast_var.theLongs[SHA512_SHORT_BLOCK_LENGTH / 8] = context->bitcount[1];
434 	cast_var.theLongs[SHA512_SHORT_BLOCK_LENGTH / 8 + 1] = context->bitcount[0];
435 
436 	/* final transform: */
437 	SHA512_Transform(context, (sha2_word64*)context->buffer);
438 }
439 
440 void SHA512_Final(sha2_byte digest[], SHA512_CTX* context) {
441 	sha2_word64	*d = (sha2_word64*)digest;
442 
443 	/* Sanity check: */
444 	assert(context != (SHA512_CTX*)0);
445 
446 	/* If no digest buffer is passed, we don't bother doing this: */
447 	if (digest != (sha2_byte*)0) {
448 		SHA512_Last(context);
449 
450 		/* Save the hash data for output: */
451 #if BYTE_ORDER == LITTLE_ENDIAN
452 		{
453 			/* Convert TO host byte order */
454 			int	j;
455 			for (j = 0; j < 8; j++) {
456 				REVERSE64(context->state[j],context->state[j]);
457 				*d++ = context->state[j];
458 			}
459 		}
460 #else
461 		MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH);
462 #endif
463 	}
464 
465 	/* Zero out state data */
466 	MEMSET_BZERO(context, sizeof(SHA512_CTX));
467 }
468 
469 unsigned char *
470 SHA512(void *data, unsigned int data_len, unsigned char *digest)
471 {
472     SHA512_CTX ctx;
473     SHA512_Init(&ctx);
474     SHA512_Update(&ctx, data, data_len);
475     SHA512_Final(digest, &ctx);
476     return digest;
477 }
478