umac.c revision 248619
1/* $OpenBSD: umac.c,v 1.4 2011/10/19 10:39:48 djm Exp $ */
2/* -----------------------------------------------------------------------
3 *
4 * umac.c -- C Implementation UMAC Message Authentication
5 *
6 * Version 0.93b of rfc4418.txt -- 2006 July 18
7 *
8 * For a full description of UMAC message authentication see the UMAC
9 * world-wide-web page at http://www.cs.ucdavis.edu/~rogaway/umac
10 * Please report bugs and suggestions to the UMAC webpage.
11 *
12 * Copyright (c) 1999-2006 Ted Krovetz
13 *
14 * Permission to use, copy, modify, and distribute this software and
15 * its documentation for any purpose and with or without fee, is hereby
16 * granted provided that the above copyright notice appears in all copies
17 * and in supporting documentation, and that the name of the copyright
18 * holder not be used in advertising or publicity pertaining to
19 * distribution of the software without specific, written prior permission.
20 *
21 * Comments should be directed to Ted Krovetz (tdk@acm.org)
22 *
23 * ---------------------------------------------------------------------- */
24
25 /* ////////////////////// IMPORTANT NOTES /////////////////////////////////
26  *
27  * 1) This version does not work properly on messages larger than 16MB
28  *
29  * 2) If you set the switch to use SSE2, then all data must be 16-byte
30  *    aligned
31  *
32  * 3) When calling the function umac(), it is assumed that msg is in
33  * a writable buffer of length divisible by 32 bytes. The message itself
34  * does not have to fill the entire buffer, but bytes beyond msg may be
35  * zeroed.
36  *
37  * 4) Three free AES implementations are supported by this implementation of
38  * UMAC. Paulo Barreto's version is in the public domain and can be found
39  * at http://www.esat.kuleuven.ac.be/~rijmen/rijndael/ (search for
40  * "Barreto"). The only two files needed are rijndael-alg-fst.c and
41  * rijndael-alg-fst.h. Brian Gladman's version is distributed with the GNU
42  * Public lisence at http://fp.gladman.plus.com/AES/index.htm. It
43  * includes a fast IA-32 assembly version. The OpenSSL crypo library is
44  * the third.
45  *
46  * 5) With FORCE_C_ONLY flags set to 0, incorrect results are sometimes
47  * produced under gcc with optimizations set -O3 or higher. Dunno why.
48  *
49  /////////////////////////////////////////////////////////////////////// */
50
51/* ---------------------------------------------------------------------- */
52/* --- User Switches ---------------------------------------------------- */
53/* ---------------------------------------------------------------------- */
54
55#ifndef UMAC_OUTPUT_LEN
56#define UMAC_OUTPUT_LEN     8  /* Alowable: 4, 8, 12, 16                  */
57#endif
58
59#if UMAC_OUTPUT_LEN != 4 && UMAC_OUTPUT_LEN != 8 && \
60    UMAC_OUTPUT_LEN != 12 && UMAC_OUTPUT_LEN != 16
61# error UMAC_OUTPUT_LEN must be defined to 4, 8, 12 or 16
62#endif
63
64/* #define FORCE_C_ONLY        1  ANSI C and 64-bit integers req'd        */
65/* #define AES_IMPLEMENTAION   1  1 = OpenSSL, 2 = Barreto, 3 = Gladman   */
66/* #define SSE2                0  Is SSE2 is available?                   */
67/* #define RUN_TESTS           0  Run basic correctness/speed tests       */
68/* #define UMAC_AE_SUPPORT     0  Enable auhthenticated encrytion         */
69
70/* ---------------------------------------------------------------------- */
71/* -- Global Includes --------------------------------------------------- */
72/* ---------------------------------------------------------------------- */
73
74#include "includes.h"
75#include <sys/types.h>
76
77#include "xmalloc.h"
78#include "umac.h"
79#include <string.h>
80#include <stdlib.h>
81#include <stddef.h>
82
83/* ---------------------------------------------------------------------- */
84/* --- Primitive Data Types ---                                           */
85/* ---------------------------------------------------------------------- */
86
87/* The following assumptions may need change on your system */
88typedef u_int8_t	UINT8;  /* 1 byte   */
89typedef u_int16_t	UINT16; /* 2 byte   */
90typedef u_int32_t	UINT32; /* 4 byte   */
91typedef u_int64_t	UINT64; /* 8 bytes  */
92typedef unsigned int	UWORD;  /* Register */
93
94/* ---------------------------------------------------------------------- */
95/* --- Constants -------------------------------------------------------- */
96/* ---------------------------------------------------------------------- */
97
98#define UMAC_KEY_LEN           16  /* UMAC takes 16 bytes of external key */
99
100/* Message "words" are read from memory in an endian-specific manner.     */
101/* For this implementation to behave correctly, __LITTLE_ENDIAN__ must    */
102/* be set true if the host computer is little-endian.                     */
103
104#if BYTE_ORDER == LITTLE_ENDIAN
105#define __LITTLE_ENDIAN__ 1
106#else
107#define __LITTLE_ENDIAN__ 0
108#endif
109
110/* ---------------------------------------------------------------------- */
111/* ---------------------------------------------------------------------- */
112/* ----- Architecture Specific ------------------------------------------ */
113/* ---------------------------------------------------------------------- */
114/* ---------------------------------------------------------------------- */
115
116
117/* ---------------------------------------------------------------------- */
118/* ---------------------------------------------------------------------- */
119/* ----- Primitive Routines --------------------------------------------- */
120/* ---------------------------------------------------------------------- */
121/* ---------------------------------------------------------------------- */
122
123
124/* ---------------------------------------------------------------------- */
125/* --- 32-bit by 32-bit to 64-bit Multiplication ------------------------ */
126/* ---------------------------------------------------------------------- */
127
128#define MUL64(a,b) ((UINT64)((UINT64)(UINT32)(a) * (UINT64)(UINT32)(b)))
129
130/* ---------------------------------------------------------------------- */
131/* --- Endian Conversion --- Forcing assembly on some platforms           */
132/* ---------------------------------------------------------------------- */
133
134#if HAVE_SWAP32
135#define LOAD_UINT32_REVERSED(p)		(swap32(*(UINT32 *)(p)))
136#define STORE_UINT32_REVERSED(p,v) 	(*(UINT32 *)(p) = swap32(v))
137#else /* HAVE_SWAP32 */
138
139static UINT32 LOAD_UINT32_REVERSED(void *ptr)
140{
141    UINT32 temp = *(UINT32 *)ptr;
142    temp = (temp >> 24) | ((temp & 0x00FF0000) >> 8 )
143         | ((temp & 0x0000FF00) << 8 ) | (temp << 24);
144    return (UINT32)temp;
145}
146
147# if (__LITTLE_ENDIAN__)
148static void STORE_UINT32_REVERSED(void *ptr, UINT32 x)
149{
150    UINT32 i = (UINT32)x;
151    *(UINT32 *)ptr = (i >> 24) | ((i & 0x00FF0000) >> 8 )
152                   | ((i & 0x0000FF00) << 8 ) | (i << 24);
153}
154# endif /* __LITTLE_ENDIAN */
155#endif /* HAVE_SWAP32 */
156
157/* The following definitions use the above reversal-primitives to do the right
158 * thing on endian specific load and stores.
159 */
160
161#if (__LITTLE_ENDIAN__)
162#define LOAD_UINT32_LITTLE(ptr)     (*(UINT32 *)(ptr))
163#define STORE_UINT32_BIG(ptr,x)     STORE_UINT32_REVERSED(ptr,x)
164#else
165#define LOAD_UINT32_LITTLE(ptr)     LOAD_UINT32_REVERSED(ptr)
166#define STORE_UINT32_BIG(ptr,x)     (*(UINT32 *)(ptr) = (UINT32)(x))
167#endif
168
169/* ---------------------------------------------------------------------- */
170/* ---------------------------------------------------------------------- */
171/* ----- Begin KDF & PDF Section ---------------------------------------- */
172/* ---------------------------------------------------------------------- */
173/* ---------------------------------------------------------------------- */
174
175/* UMAC uses AES with 16 byte block and key lengths */
176#define AES_BLOCK_LEN  16
177
178/* OpenSSL's AES */
179#include "openbsd-compat/openssl-compat.h"
180#ifndef USE_BUILTIN_RIJNDAEL
181# include <openssl/aes.h>
182#endif
183typedef AES_KEY aes_int_key[1];
184#define aes_encryption(in,out,int_key)                  \
185  AES_encrypt((u_char *)(in),(u_char *)(out),(AES_KEY *)int_key)
186#define aes_key_setup(key,int_key)                      \
187  AES_set_encrypt_key((u_char *)(key),UMAC_KEY_LEN*8,int_key)
188
189/* The user-supplied UMAC key is stretched using AES in a counter
190 * mode to supply all random bits needed by UMAC. The kdf function takes
191 * an AES internal key representation 'key' and writes a stream of
192 * 'nbytes' bytes to the memory pointed at by 'bufp'. Each distinct
193 * 'ndx' causes a distinct byte stream.
194 */
195static void kdf(void *bufp, aes_int_key key, UINT8 ndx, int nbytes)
196{
197    UINT8 in_buf[AES_BLOCK_LEN] = {0};
198    UINT8 out_buf[AES_BLOCK_LEN];
199    UINT8 *dst_buf = (UINT8 *)bufp;
200    int i;
201
202    /* Setup the initial value */
203    in_buf[AES_BLOCK_LEN-9] = ndx;
204    in_buf[AES_BLOCK_LEN-1] = i = 1;
205
206    while (nbytes >= AES_BLOCK_LEN) {
207        aes_encryption(in_buf, out_buf, key);
208        memcpy(dst_buf,out_buf,AES_BLOCK_LEN);
209        in_buf[AES_BLOCK_LEN-1] = ++i;
210        nbytes -= AES_BLOCK_LEN;
211        dst_buf += AES_BLOCK_LEN;
212    }
213    if (nbytes) {
214        aes_encryption(in_buf, out_buf, key);
215        memcpy(dst_buf,out_buf,nbytes);
216    }
217}
218
219/* The final UHASH result is XOR'd with the output of a pseudorandom
220 * function. Here, we use AES to generate random output and
221 * xor the appropriate bytes depending on the last bits of nonce.
222 * This scheme is optimized for sequential, increasing big-endian nonces.
223 */
224
225typedef struct {
226    UINT8 cache[AES_BLOCK_LEN];  /* Previous AES output is saved      */
227    UINT8 nonce[AES_BLOCK_LEN];  /* The AES input making above cache  */
228    aes_int_key prf_key;         /* Expanded AES key for PDF          */
229} pdf_ctx;
230
231static void pdf_init(pdf_ctx *pc, aes_int_key prf_key)
232{
233    UINT8 buf[UMAC_KEY_LEN];
234
235    kdf(buf, prf_key, 0, UMAC_KEY_LEN);
236    aes_key_setup(buf, pc->prf_key);
237
238    /* Initialize pdf and cache */
239    memset(pc->nonce, 0, sizeof(pc->nonce));
240    aes_encryption(pc->nonce, pc->cache, pc->prf_key);
241}
242
243static void pdf_gen_xor(pdf_ctx *pc, UINT8 nonce[8], UINT8 buf[8])
244{
245    /* 'ndx' indicates that we'll be using the 0th or 1st eight bytes
246     * of the AES output. If last time around we returned the ndx-1st
247     * element, then we may have the result in the cache already.
248     */
249
250#if (UMAC_OUTPUT_LEN == 4)
251#define LOW_BIT_MASK 3
252#elif (UMAC_OUTPUT_LEN == 8)
253#define LOW_BIT_MASK 1
254#elif (UMAC_OUTPUT_LEN > 8)
255#define LOW_BIT_MASK 0
256#endif
257
258    UINT8 tmp_nonce_lo[4];
259#if LOW_BIT_MASK != 0
260    int ndx = nonce[7] & LOW_BIT_MASK;
261#endif
262    *(UINT32 *)tmp_nonce_lo = ((UINT32 *)nonce)[1];
263    tmp_nonce_lo[3] &= ~LOW_BIT_MASK; /* zero last bit */
264
265    if ( (((UINT32 *)tmp_nonce_lo)[0] != ((UINT32 *)pc->nonce)[1]) ||
266         (((UINT32 *)nonce)[0] != ((UINT32 *)pc->nonce)[0]) )
267    {
268        ((UINT32 *)pc->nonce)[0] = ((UINT32 *)nonce)[0];
269        ((UINT32 *)pc->nonce)[1] = ((UINT32 *)tmp_nonce_lo)[0];
270        aes_encryption(pc->nonce, pc->cache, pc->prf_key);
271    }
272
273#if (UMAC_OUTPUT_LEN == 4)
274    *((UINT32 *)buf) ^= ((UINT32 *)pc->cache)[ndx];
275#elif (UMAC_OUTPUT_LEN == 8)
276    *((UINT64 *)buf) ^= ((UINT64 *)pc->cache)[ndx];
277#elif (UMAC_OUTPUT_LEN == 12)
278    ((UINT64 *)buf)[0] ^= ((UINT64 *)pc->cache)[0];
279    ((UINT32 *)buf)[2] ^= ((UINT32 *)pc->cache)[2];
280#elif (UMAC_OUTPUT_LEN == 16)
281    ((UINT64 *)buf)[0] ^= ((UINT64 *)pc->cache)[0];
282    ((UINT64 *)buf)[1] ^= ((UINT64 *)pc->cache)[1];
283#endif
284}
285
286/* ---------------------------------------------------------------------- */
287/* ---------------------------------------------------------------------- */
288/* ----- Begin NH Hash Section ------------------------------------------ */
289/* ---------------------------------------------------------------------- */
290/* ---------------------------------------------------------------------- */
291
292/* The NH-based hash functions used in UMAC are described in the UMAC paper
293 * and specification, both of which can be found at the UMAC website.
294 * The interface to this implementation has two
295 * versions, one expects the entire message being hashed to be passed
296 * in a single buffer and returns the hash result immediately. The second
297 * allows the message to be passed in a sequence of buffers. In the
298 * muliple-buffer interface, the client calls the routine nh_update() as
299 * many times as necessary. When there is no more data to be fed to the
300 * hash, the client calls nh_final() which calculates the hash output.
301 * Before beginning another hash calculation the nh_reset() routine
302 * must be called. The single-buffer routine, nh(), is equivalent to
303 * the sequence of calls nh_update() and nh_final(); however it is
304 * optimized and should be prefered whenever the multiple-buffer interface
305 * is not necessary. When using either interface, it is the client's
306 * responsability to pass no more than L1_KEY_LEN bytes per hash result.
307 *
308 * The routine nh_init() initializes the nh_ctx data structure and
309 * must be called once, before any other PDF routine.
310 */
311
312 /* The "nh_aux" routines do the actual NH hashing work. They
313  * expect buffers to be multiples of L1_PAD_BOUNDARY. These routines
314  * produce output for all STREAMS NH iterations in one call,
315  * allowing the parallel implementation of the streams.
316  */
317
318#define STREAMS (UMAC_OUTPUT_LEN / 4) /* Number of times hash is applied  */
319#define L1_KEY_LEN         1024     /* Internal key bytes                 */
320#define L1_KEY_SHIFT         16     /* Toeplitz key shift between streams */
321#define L1_PAD_BOUNDARY      32     /* pad message to boundary multiple   */
322#define ALLOC_BOUNDARY       16     /* Keep buffers aligned to this       */
323#define HASH_BUF_BYTES       64     /* nh_aux_hb buffer multiple          */
324
325typedef struct {
326    UINT8  nh_key [L1_KEY_LEN + L1_KEY_SHIFT * (STREAMS - 1)]; /* NH Key */
327    UINT8  data   [HASH_BUF_BYTES];    /* Incoming data buffer           */
328    int next_data_empty;    /* Bookeeping variable for data buffer.       */
329    int bytes_hashed;        /* Bytes (out of L1_KEY_LEN) incorperated.   */
330    UINT64 state[STREAMS];               /* on-line state     */
331} nh_ctx;
332
333
334#if (UMAC_OUTPUT_LEN == 4)
335
336static void nh_aux(void *kp, void *dp, void *hp, UINT32 dlen)
337/* NH hashing primitive. Previous (partial) hash result is loaded and
338* then stored via hp pointer. The length of the data pointed at by "dp",
339* "dlen", is guaranteed to be divisible by L1_PAD_BOUNDARY (32).  Key
340* is expected to be endian compensated in memory at key setup.
341*/
342{
343    UINT64 h;
344    UWORD c = dlen / 32;
345    UINT32 *k = (UINT32 *)kp;
346    UINT32 *d = (UINT32 *)dp;
347    UINT32 d0,d1,d2,d3,d4,d5,d6,d7;
348    UINT32 k0,k1,k2,k3,k4,k5,k6,k7;
349
350    h = *((UINT64 *)hp);
351    do {
352        d0 = LOAD_UINT32_LITTLE(d+0); d1 = LOAD_UINT32_LITTLE(d+1);
353        d2 = LOAD_UINT32_LITTLE(d+2); d3 = LOAD_UINT32_LITTLE(d+3);
354        d4 = LOAD_UINT32_LITTLE(d+4); d5 = LOAD_UINT32_LITTLE(d+5);
355        d6 = LOAD_UINT32_LITTLE(d+6); d7 = LOAD_UINT32_LITTLE(d+7);
356        k0 = *(k+0); k1 = *(k+1); k2 = *(k+2); k3 = *(k+3);
357        k4 = *(k+4); k5 = *(k+5); k6 = *(k+6); k7 = *(k+7);
358        h += MUL64((k0 + d0), (k4 + d4));
359        h += MUL64((k1 + d1), (k5 + d5));
360        h += MUL64((k2 + d2), (k6 + d6));
361        h += MUL64((k3 + d3), (k7 + d7));
362
363        d += 8;
364        k += 8;
365    } while (--c);
366  *((UINT64 *)hp) = h;
367}
368
369#elif (UMAC_OUTPUT_LEN == 8)
370
371static void nh_aux(void *kp, void *dp, void *hp, UINT32 dlen)
372/* Same as previous nh_aux, but two streams are handled in one pass,
373 * reading and writing 16 bytes of hash-state per call.
374 */
375{
376  UINT64 h1,h2;
377  UWORD c = dlen / 32;
378  UINT32 *k = (UINT32 *)kp;
379  UINT32 *d = (UINT32 *)dp;
380  UINT32 d0,d1,d2,d3,d4,d5,d6,d7;
381  UINT32 k0,k1,k2,k3,k4,k5,k6,k7,
382        k8,k9,k10,k11;
383
384  h1 = *((UINT64 *)hp);
385  h2 = *((UINT64 *)hp + 1);
386  k0 = *(k+0); k1 = *(k+1); k2 = *(k+2); k3 = *(k+3);
387  do {
388    d0 = LOAD_UINT32_LITTLE(d+0); d1 = LOAD_UINT32_LITTLE(d+1);
389    d2 = LOAD_UINT32_LITTLE(d+2); d3 = LOAD_UINT32_LITTLE(d+3);
390    d4 = LOAD_UINT32_LITTLE(d+4); d5 = LOAD_UINT32_LITTLE(d+5);
391    d6 = LOAD_UINT32_LITTLE(d+6); d7 = LOAD_UINT32_LITTLE(d+7);
392    k4 = *(k+4); k5 = *(k+5); k6 = *(k+6); k7 = *(k+7);
393    k8 = *(k+8); k9 = *(k+9); k10 = *(k+10); k11 = *(k+11);
394
395    h1 += MUL64((k0 + d0), (k4 + d4));
396    h2 += MUL64((k4 + d0), (k8 + d4));
397
398    h1 += MUL64((k1 + d1), (k5 + d5));
399    h2 += MUL64((k5 + d1), (k9 + d5));
400
401    h1 += MUL64((k2 + d2), (k6 + d6));
402    h2 += MUL64((k6 + d2), (k10 + d6));
403
404    h1 += MUL64((k3 + d3), (k7 + d7));
405    h2 += MUL64((k7 + d3), (k11 + d7));
406
407    k0 = k8; k1 = k9; k2 = k10; k3 = k11;
408
409    d += 8;
410    k += 8;
411  } while (--c);
412  ((UINT64 *)hp)[0] = h1;
413  ((UINT64 *)hp)[1] = h2;
414}
415
416#elif (UMAC_OUTPUT_LEN == 12)
417
418static void nh_aux(void *kp, void *dp, void *hp, UINT32 dlen)
419/* Same as previous nh_aux, but two streams are handled in one pass,
420 * reading and writing 24 bytes of hash-state per call.
421*/
422{
423    UINT64 h1,h2,h3;
424    UWORD c = dlen / 32;
425    UINT32 *k = (UINT32 *)kp;
426    UINT32 *d = (UINT32 *)dp;
427    UINT32 d0,d1,d2,d3,d4,d5,d6,d7;
428    UINT32 k0,k1,k2,k3,k4,k5,k6,k7,
429        k8,k9,k10,k11,k12,k13,k14,k15;
430
431    h1 = *((UINT64 *)hp);
432    h2 = *((UINT64 *)hp + 1);
433    h3 = *((UINT64 *)hp + 2);
434    k0 = *(k+0); k1 = *(k+1); k2 = *(k+2); k3 = *(k+3);
435    k4 = *(k+4); k5 = *(k+5); k6 = *(k+6); k7 = *(k+7);
436    do {
437        d0 = LOAD_UINT32_LITTLE(d+0); d1 = LOAD_UINT32_LITTLE(d+1);
438        d2 = LOAD_UINT32_LITTLE(d+2); d3 = LOAD_UINT32_LITTLE(d+3);
439        d4 = LOAD_UINT32_LITTLE(d+4); d5 = LOAD_UINT32_LITTLE(d+5);
440        d6 = LOAD_UINT32_LITTLE(d+6); d7 = LOAD_UINT32_LITTLE(d+7);
441        k8 = *(k+8); k9 = *(k+9); k10 = *(k+10); k11 = *(k+11);
442        k12 = *(k+12); k13 = *(k+13); k14 = *(k+14); k15 = *(k+15);
443
444        h1 += MUL64((k0 + d0), (k4 + d4));
445        h2 += MUL64((k4 + d0), (k8 + d4));
446        h3 += MUL64((k8 + d0), (k12 + d4));
447
448        h1 += MUL64((k1 + d1), (k5 + d5));
449        h2 += MUL64((k5 + d1), (k9 + d5));
450        h3 += MUL64((k9 + d1), (k13 + d5));
451
452        h1 += MUL64((k2 + d2), (k6 + d6));
453        h2 += MUL64((k6 + d2), (k10 + d6));
454        h3 += MUL64((k10 + d2), (k14 + d6));
455
456        h1 += MUL64((k3 + d3), (k7 + d7));
457        h2 += MUL64((k7 + d3), (k11 + d7));
458        h3 += MUL64((k11 + d3), (k15 + d7));
459
460        k0 = k8; k1 = k9; k2 = k10; k3 = k11;
461        k4 = k12; k5 = k13; k6 = k14; k7 = k15;
462
463        d += 8;
464        k += 8;
465    } while (--c);
466    ((UINT64 *)hp)[0] = h1;
467    ((UINT64 *)hp)[1] = h2;
468    ((UINT64 *)hp)[2] = h3;
469}
470
471#elif (UMAC_OUTPUT_LEN == 16)
472
473static void nh_aux(void *kp, void *dp, void *hp, UINT32 dlen)
474/* Same as previous nh_aux, but two streams are handled in one pass,
475 * reading and writing 24 bytes of hash-state per call.
476*/
477{
478    UINT64 h1,h2,h3,h4;
479    UWORD c = dlen / 32;
480    UINT32 *k = (UINT32 *)kp;
481    UINT32 *d = (UINT32 *)dp;
482    UINT32 d0,d1,d2,d3,d4,d5,d6,d7;
483    UINT32 k0,k1,k2,k3,k4,k5,k6,k7,
484        k8,k9,k10,k11,k12,k13,k14,k15,
485        k16,k17,k18,k19;
486
487    h1 = *((UINT64 *)hp);
488    h2 = *((UINT64 *)hp + 1);
489    h3 = *((UINT64 *)hp + 2);
490    h4 = *((UINT64 *)hp + 3);
491    k0 = *(k+0); k1 = *(k+1); k2 = *(k+2); k3 = *(k+3);
492    k4 = *(k+4); k5 = *(k+5); k6 = *(k+6); k7 = *(k+7);
493    do {
494        d0 = LOAD_UINT32_LITTLE(d+0); d1 = LOAD_UINT32_LITTLE(d+1);
495        d2 = LOAD_UINT32_LITTLE(d+2); d3 = LOAD_UINT32_LITTLE(d+3);
496        d4 = LOAD_UINT32_LITTLE(d+4); d5 = LOAD_UINT32_LITTLE(d+5);
497        d6 = LOAD_UINT32_LITTLE(d+6); d7 = LOAD_UINT32_LITTLE(d+7);
498        k8 = *(k+8); k9 = *(k+9); k10 = *(k+10); k11 = *(k+11);
499        k12 = *(k+12); k13 = *(k+13); k14 = *(k+14); k15 = *(k+15);
500        k16 = *(k+16); k17 = *(k+17); k18 = *(k+18); k19 = *(k+19);
501
502        h1 += MUL64((k0 + d0), (k4 + d4));
503        h2 += MUL64((k4 + d0), (k8 + d4));
504        h3 += MUL64((k8 + d0), (k12 + d4));
505        h4 += MUL64((k12 + d0), (k16 + d4));
506
507        h1 += MUL64((k1 + d1), (k5 + d5));
508        h2 += MUL64((k5 + d1), (k9 + d5));
509        h3 += MUL64((k9 + d1), (k13 + d5));
510        h4 += MUL64((k13 + d1), (k17 + d5));
511
512        h1 += MUL64((k2 + d2), (k6 + d6));
513        h2 += MUL64((k6 + d2), (k10 + d6));
514        h3 += MUL64((k10 + d2), (k14 + d6));
515        h4 += MUL64((k14 + d2), (k18 + d6));
516
517        h1 += MUL64((k3 + d3), (k7 + d7));
518        h2 += MUL64((k7 + d3), (k11 + d7));
519        h3 += MUL64((k11 + d3), (k15 + d7));
520        h4 += MUL64((k15 + d3), (k19 + d7));
521
522        k0 = k8; k1 = k9; k2 = k10; k3 = k11;
523        k4 = k12; k5 = k13; k6 = k14; k7 = k15;
524        k8 = k16; k9 = k17; k10 = k18; k11 = k19;
525
526        d += 8;
527        k += 8;
528    } while (--c);
529    ((UINT64 *)hp)[0] = h1;
530    ((UINT64 *)hp)[1] = h2;
531    ((UINT64 *)hp)[2] = h3;
532    ((UINT64 *)hp)[3] = h4;
533}
534
535/* ---------------------------------------------------------------------- */
536#endif  /* UMAC_OUTPUT_LENGTH */
537/* ---------------------------------------------------------------------- */
538
539
540/* ---------------------------------------------------------------------- */
541
542static void nh_transform(nh_ctx *hc, UINT8 *buf, UINT32 nbytes)
543/* This function is a wrapper for the primitive NH hash functions. It takes
544 * as argument "hc" the current hash context and a buffer which must be a
545 * multiple of L1_PAD_BOUNDARY. The key passed to nh_aux is offset
546 * appropriately according to how much message has been hashed already.
547 */
548{
549    UINT8 *key;
550
551    key = hc->nh_key + hc->bytes_hashed;
552    nh_aux(key, buf, hc->state, nbytes);
553}
554
555/* ---------------------------------------------------------------------- */
556
557#if (__LITTLE_ENDIAN__)
558static void endian_convert(void *buf, UWORD bpw, UINT32 num_bytes)
559/* We endian convert the keys on little-endian computers to               */
560/* compensate for the lack of big-endian memory reads during hashing.     */
561{
562    UWORD iters = num_bytes / bpw;
563    if (bpw == 4) {
564        UINT32 *p = (UINT32 *)buf;
565        do {
566            *p = LOAD_UINT32_REVERSED(p);
567            p++;
568        } while (--iters);
569    } else if (bpw == 8) {
570        UINT32 *p = (UINT32 *)buf;
571        UINT32 t;
572        do {
573            t = LOAD_UINT32_REVERSED(p+1);
574            p[1] = LOAD_UINT32_REVERSED(p);
575            p[0] = t;
576            p += 2;
577        } while (--iters);
578    }
579}
580#define endian_convert_if_le(x,y,z) endian_convert((x),(y),(z))
581#else
582#define endian_convert_if_le(x,y,z) do{}while(0)  /* Do nothing */
583#endif
584
585/* ---------------------------------------------------------------------- */
586
587static void nh_reset(nh_ctx *hc)
588/* Reset nh_ctx to ready for hashing of new data */
589{
590    hc->bytes_hashed = 0;
591    hc->next_data_empty = 0;
592    hc->state[0] = 0;
593#if (UMAC_OUTPUT_LEN >= 8)
594    hc->state[1] = 0;
595#endif
596#if (UMAC_OUTPUT_LEN >= 12)
597    hc->state[2] = 0;
598#endif
599#if (UMAC_OUTPUT_LEN == 16)
600    hc->state[3] = 0;
601#endif
602
603}
604
605/* ---------------------------------------------------------------------- */
606
607static void nh_init(nh_ctx *hc, aes_int_key prf_key)
608/* Generate nh_key, endian convert and reset to be ready for hashing.   */
609{
610    kdf(hc->nh_key, prf_key, 1, sizeof(hc->nh_key));
611    endian_convert_if_le(hc->nh_key, 4, sizeof(hc->nh_key));
612    nh_reset(hc);
613}
614
615/* ---------------------------------------------------------------------- */
616
617static void nh_update(nh_ctx *hc, UINT8 *buf, UINT32 nbytes)
618/* Incorporate nbytes of data into a nh_ctx, buffer whatever is not an    */
619/* even multiple of HASH_BUF_BYTES.                                       */
620{
621    UINT32 i,j;
622
623    j = hc->next_data_empty;
624    if ((j + nbytes) >= HASH_BUF_BYTES) {
625        if (j) {
626            i = HASH_BUF_BYTES - j;
627            memcpy(hc->data+j, buf, i);
628            nh_transform(hc,hc->data,HASH_BUF_BYTES);
629            nbytes -= i;
630            buf += i;
631            hc->bytes_hashed += HASH_BUF_BYTES;
632        }
633        if (nbytes >= HASH_BUF_BYTES) {
634            i = nbytes & ~(HASH_BUF_BYTES - 1);
635            nh_transform(hc, buf, i);
636            nbytes -= i;
637            buf += i;
638            hc->bytes_hashed += i;
639        }
640        j = 0;
641    }
642    memcpy(hc->data + j, buf, nbytes);
643    hc->next_data_empty = j + nbytes;
644}
645
646/* ---------------------------------------------------------------------- */
647
648static void zero_pad(UINT8 *p, int nbytes)
649{
650/* Write "nbytes" of zeroes, beginning at "p" */
651    if (nbytes >= (int)sizeof(UWORD)) {
652        while ((ptrdiff_t)p % sizeof(UWORD)) {
653            *p = 0;
654            nbytes--;
655            p++;
656        }
657        while (nbytes >= (int)sizeof(UWORD)) {
658            *(UWORD *)p = 0;
659            nbytes -= sizeof(UWORD);
660            p += sizeof(UWORD);
661        }
662    }
663    while (nbytes) {
664        *p = 0;
665        nbytes--;
666        p++;
667    }
668}
669
670/* ---------------------------------------------------------------------- */
671
672static void nh_final(nh_ctx *hc, UINT8 *result)
673/* After passing some number of data buffers to nh_update() for integration
674 * into an NH context, nh_final is called to produce a hash result. If any
675 * bytes are in the buffer hc->data, incorporate them into the
676 * NH context. Finally, add into the NH accumulation "state" the total number
677 * of bits hashed. The resulting numbers are written to the buffer "result".
678 * If nh_update was never called, L1_PAD_BOUNDARY zeroes are incorporated.
679 */
680{
681    int nh_len, nbits;
682
683    if (hc->next_data_empty != 0) {
684        nh_len = ((hc->next_data_empty + (L1_PAD_BOUNDARY - 1)) &
685                                                ~(L1_PAD_BOUNDARY - 1));
686        zero_pad(hc->data + hc->next_data_empty,
687                                          nh_len - hc->next_data_empty);
688        nh_transform(hc, hc->data, nh_len);
689        hc->bytes_hashed += hc->next_data_empty;
690    } else if (hc->bytes_hashed == 0) {
691    	nh_len = L1_PAD_BOUNDARY;
692        zero_pad(hc->data, L1_PAD_BOUNDARY);
693        nh_transform(hc, hc->data, nh_len);
694    }
695
696    nbits = (hc->bytes_hashed << 3);
697    ((UINT64 *)result)[0] = ((UINT64 *)hc->state)[0] + nbits;
698#if (UMAC_OUTPUT_LEN >= 8)
699    ((UINT64 *)result)[1] = ((UINT64 *)hc->state)[1] + nbits;
700#endif
701#if (UMAC_OUTPUT_LEN >= 12)
702    ((UINT64 *)result)[2] = ((UINT64 *)hc->state)[2] + nbits;
703#endif
704#if (UMAC_OUTPUT_LEN == 16)
705    ((UINT64 *)result)[3] = ((UINT64 *)hc->state)[3] + nbits;
706#endif
707    nh_reset(hc);
708}
709
710/* ---------------------------------------------------------------------- */
711
712static void nh(nh_ctx *hc, UINT8 *buf, UINT32 padded_len,
713               UINT32 unpadded_len, UINT8 *result)
714/* All-in-one nh_update() and nh_final() equivalent.
715 * Assumes that padded_len is divisible by L1_PAD_BOUNDARY and result is
716 * well aligned
717 */
718{
719    UINT32 nbits;
720
721    /* Initialize the hash state */
722    nbits = (unpadded_len << 3);
723
724    ((UINT64 *)result)[0] = nbits;
725#if (UMAC_OUTPUT_LEN >= 8)
726    ((UINT64 *)result)[1] = nbits;
727#endif
728#if (UMAC_OUTPUT_LEN >= 12)
729    ((UINT64 *)result)[2] = nbits;
730#endif
731#if (UMAC_OUTPUT_LEN == 16)
732    ((UINT64 *)result)[3] = nbits;
733#endif
734
735    nh_aux(hc->nh_key, buf, result, padded_len);
736}
737
738/* ---------------------------------------------------------------------- */
739/* ---------------------------------------------------------------------- */
740/* ----- Begin UHASH Section -------------------------------------------- */
741/* ---------------------------------------------------------------------- */
742/* ---------------------------------------------------------------------- */
743
744/* UHASH is a multi-layered algorithm. Data presented to UHASH is first
745 * hashed by NH. The NH output is then hashed by a polynomial-hash layer
746 * unless the initial data to be hashed is short. After the polynomial-
747 * layer, an inner-product hash is used to produce the final UHASH output.
748 *
749 * UHASH provides two interfaces, one all-at-once and another where data
750 * buffers are presented sequentially. In the sequential interface, the
751 * UHASH client calls the routine uhash_update() as many times as necessary.
752 * When there is no more data to be fed to UHASH, the client calls
753 * uhash_final() which
754 * calculates the UHASH output. Before beginning another UHASH calculation
755 * the uhash_reset() routine must be called. The all-at-once UHASH routine,
756 * uhash(), is equivalent to the sequence of calls uhash_update() and
757 * uhash_final(); however it is optimized and should be
758 * used whenever the sequential interface is not necessary.
759 *
760 * The routine uhash_init() initializes the uhash_ctx data structure and
761 * must be called once, before any other UHASH routine.
762 */
763
764/* ---------------------------------------------------------------------- */
765/* ----- Constants and uhash_ctx ---------------------------------------- */
766/* ---------------------------------------------------------------------- */
767
768/* ---------------------------------------------------------------------- */
769/* ----- Poly hash and Inner-Product hash Constants --------------------- */
770/* ---------------------------------------------------------------------- */
771
772/* Primes and masks */
773#define p36    ((UINT64)0x0000000FFFFFFFFBull)              /* 2^36 -  5 */
774#define p64    ((UINT64)0xFFFFFFFFFFFFFFC5ull)              /* 2^64 - 59 */
775#define m36    ((UINT64)0x0000000FFFFFFFFFull)  /* The low 36 of 64 bits */
776
777
778/* ---------------------------------------------------------------------- */
779
780typedef struct uhash_ctx {
781    nh_ctx hash;                          /* Hash context for L1 NH hash  */
782    UINT64 poly_key_8[STREAMS];           /* p64 poly keys                */
783    UINT64 poly_accum[STREAMS];           /* poly hash result             */
784    UINT64 ip_keys[STREAMS*4];            /* Inner-product keys           */
785    UINT32 ip_trans[STREAMS];             /* Inner-product translation    */
786    UINT32 msg_len;                       /* Total length of data passed  */
787                                          /* to uhash */
788} uhash_ctx;
789typedef struct uhash_ctx *uhash_ctx_t;
790
791/* ---------------------------------------------------------------------- */
792
793
794/* The polynomial hashes use Horner's rule to evaluate a polynomial one
795 * word at a time. As described in the specification, poly32 and poly64
796 * require keys from special domains. The following implementations exploit
797 * the special domains to avoid overflow. The results are not guaranteed to
798 * be within Z_p32 and Z_p64, but the Inner-Product hash implementation
799 * patches any errant values.
800 */
801
802static UINT64 poly64(UINT64 cur, UINT64 key, UINT64 data)
803{
804    UINT32 key_hi = (UINT32)(key >> 32),
805           key_lo = (UINT32)key,
806           cur_hi = (UINT32)(cur >> 32),
807           cur_lo = (UINT32)cur,
808           x_lo,
809           x_hi;
810    UINT64 X,T,res;
811
812    X =  MUL64(key_hi, cur_lo) + MUL64(cur_hi, key_lo);
813    x_lo = (UINT32)X;
814    x_hi = (UINT32)(X >> 32);
815
816    res = (MUL64(key_hi, cur_hi) + x_hi) * 59 + MUL64(key_lo, cur_lo);
817
818    T = ((UINT64)x_lo << 32);
819    res += T;
820    if (res < T)
821        res += 59;
822
823    res += data;
824    if (res < data)
825        res += 59;
826
827    return res;
828}
829
830
831/* Although UMAC is specified to use a ramped polynomial hash scheme, this
832 * implementation does not handle all ramp levels. Because we don't handle
833 * the ramp up to p128 modulus in this implementation, we are limited to
834 * 2^14 poly_hash() invocations per stream (for a total capacity of 2^24
835 * bytes input to UMAC per tag, ie. 16MB).
836 */
837static void poly_hash(uhash_ctx_t hc, UINT32 data_in[])
838{
839    int i;
840    UINT64 *data=(UINT64*)data_in;
841
842    for (i = 0; i < STREAMS; i++) {
843        if ((UINT32)(data[i] >> 32) == 0xfffffffful) {
844            hc->poly_accum[i] = poly64(hc->poly_accum[i],
845                                       hc->poly_key_8[i], p64 - 1);
846            hc->poly_accum[i] = poly64(hc->poly_accum[i],
847                                       hc->poly_key_8[i], (data[i] - 59));
848        } else {
849            hc->poly_accum[i] = poly64(hc->poly_accum[i],
850                                       hc->poly_key_8[i], data[i]);
851        }
852    }
853}
854
855
856/* ---------------------------------------------------------------------- */
857
858
859/* The final step in UHASH is an inner-product hash. The poly hash
860 * produces a result not neccesarily WORD_LEN bytes long. The inner-
861 * product hash breaks the polyhash output into 16-bit chunks and
862 * multiplies each with a 36 bit key.
863 */
864
865static UINT64 ip_aux(UINT64 t, UINT64 *ipkp, UINT64 data)
866{
867    t = t + ipkp[0] * (UINT64)(UINT16)(data >> 48);
868    t = t + ipkp[1] * (UINT64)(UINT16)(data >> 32);
869    t = t + ipkp[2] * (UINT64)(UINT16)(data >> 16);
870    t = t + ipkp[3] * (UINT64)(UINT16)(data);
871
872    return t;
873}
874
875static UINT32 ip_reduce_p36(UINT64 t)
876{
877/* Divisionless modular reduction */
878    UINT64 ret;
879
880    ret = (t & m36) + 5 * (t >> 36);
881    if (ret >= p36)
882        ret -= p36;
883
884    /* return least significant 32 bits */
885    return (UINT32)(ret);
886}
887
888
889/* If the data being hashed by UHASH is no longer than L1_KEY_LEN, then
890 * the polyhash stage is skipped and ip_short is applied directly to the
891 * NH output.
892 */
893static void ip_short(uhash_ctx_t ahc, UINT8 *nh_res, u_char *res)
894{
895    UINT64 t;
896    UINT64 *nhp = (UINT64 *)nh_res;
897
898    t  = ip_aux(0,ahc->ip_keys, nhp[0]);
899    STORE_UINT32_BIG((UINT32 *)res+0, ip_reduce_p36(t) ^ ahc->ip_trans[0]);
900#if (UMAC_OUTPUT_LEN >= 8)
901    t  = ip_aux(0,ahc->ip_keys+4, nhp[1]);
902    STORE_UINT32_BIG((UINT32 *)res+1, ip_reduce_p36(t) ^ ahc->ip_trans[1]);
903#endif
904#if (UMAC_OUTPUT_LEN >= 12)
905    t  = ip_aux(0,ahc->ip_keys+8, nhp[2]);
906    STORE_UINT32_BIG((UINT32 *)res+2, ip_reduce_p36(t) ^ ahc->ip_trans[2]);
907#endif
908#if (UMAC_OUTPUT_LEN == 16)
909    t  = ip_aux(0,ahc->ip_keys+12, nhp[3]);
910    STORE_UINT32_BIG((UINT32 *)res+3, ip_reduce_p36(t) ^ ahc->ip_trans[3]);
911#endif
912}
913
914/* If the data being hashed by UHASH is longer than L1_KEY_LEN, then
915 * the polyhash stage is not skipped and ip_long is applied to the
916 * polyhash output.
917 */
918static void ip_long(uhash_ctx_t ahc, u_char *res)
919{
920    int i;
921    UINT64 t;
922
923    for (i = 0; i < STREAMS; i++) {
924        /* fix polyhash output not in Z_p64 */
925        if (ahc->poly_accum[i] >= p64)
926            ahc->poly_accum[i] -= p64;
927        t  = ip_aux(0,ahc->ip_keys+(i*4), ahc->poly_accum[i]);
928        STORE_UINT32_BIG((UINT32 *)res+i,
929                         ip_reduce_p36(t) ^ ahc->ip_trans[i]);
930    }
931}
932
933
934/* ---------------------------------------------------------------------- */
935
936/* ---------------------------------------------------------------------- */
937
938/* Reset uhash context for next hash session */
939static int uhash_reset(uhash_ctx_t pc)
940{
941    nh_reset(&pc->hash);
942    pc->msg_len = 0;
943    pc->poly_accum[0] = 1;
944#if (UMAC_OUTPUT_LEN >= 8)
945    pc->poly_accum[1] = 1;
946#endif
947#if (UMAC_OUTPUT_LEN >= 12)
948    pc->poly_accum[2] = 1;
949#endif
950#if (UMAC_OUTPUT_LEN == 16)
951    pc->poly_accum[3] = 1;
952#endif
953    return 1;
954}
955
956/* ---------------------------------------------------------------------- */
957
958/* Given a pointer to the internal key needed by kdf() and a uhash context,
959 * initialize the NH context and generate keys needed for poly and inner-
960 * product hashing. All keys are endian adjusted in memory so that native
961 * loads cause correct keys to be in registers during calculation.
962 */
963static void uhash_init(uhash_ctx_t ahc, aes_int_key prf_key)
964{
965    int i;
966    UINT8 buf[(8*STREAMS+4)*sizeof(UINT64)];
967
968    /* Zero the entire uhash context */
969    memset(ahc, 0, sizeof(uhash_ctx));
970
971    /* Initialize the L1 hash */
972    nh_init(&ahc->hash, prf_key);
973
974    /* Setup L2 hash variables */
975    kdf(buf, prf_key, 2, sizeof(buf));    /* Fill buffer with index 1 key */
976    for (i = 0; i < STREAMS; i++) {
977        /* Fill keys from the buffer, skipping bytes in the buffer not
978         * used by this implementation. Endian reverse the keys if on a
979         * little-endian computer.
980         */
981        memcpy(ahc->poly_key_8+i, buf+24*i, 8);
982        endian_convert_if_le(ahc->poly_key_8+i, 8, 8);
983        /* Mask the 64-bit keys to their special domain */
984        ahc->poly_key_8[i] &= ((UINT64)0x01ffffffu << 32) + 0x01ffffffu;
985        ahc->poly_accum[i] = 1;  /* Our polyhash prepends a non-zero word */
986    }
987
988    /* Setup L3-1 hash variables */
989    kdf(buf, prf_key, 3, sizeof(buf)); /* Fill buffer with index 2 key */
990    for (i = 0; i < STREAMS; i++)
991          memcpy(ahc->ip_keys+4*i, buf+(8*i+4)*sizeof(UINT64),
992                                                 4*sizeof(UINT64));
993    endian_convert_if_le(ahc->ip_keys, sizeof(UINT64),
994                                                  sizeof(ahc->ip_keys));
995    for (i = 0; i < STREAMS*4; i++)
996        ahc->ip_keys[i] %= p36;  /* Bring into Z_p36 */
997
998    /* Setup L3-2 hash variables    */
999    /* Fill buffer with index 4 key */
1000    kdf(ahc->ip_trans, prf_key, 4, STREAMS * sizeof(UINT32));
1001    endian_convert_if_le(ahc->ip_trans, sizeof(UINT32),
1002                         STREAMS * sizeof(UINT32));
1003}
1004
1005/* ---------------------------------------------------------------------- */
1006
1007#if 0
1008static uhash_ctx_t uhash_alloc(u_char key[])
1009{
1010/* Allocate memory and force to a 16-byte boundary. */
1011    uhash_ctx_t ctx;
1012    u_char bytes_to_add;
1013    aes_int_key prf_key;
1014
1015    ctx = (uhash_ctx_t)malloc(sizeof(uhash_ctx)+ALLOC_BOUNDARY);
1016    if (ctx) {
1017        if (ALLOC_BOUNDARY) {
1018            bytes_to_add = ALLOC_BOUNDARY -
1019                              ((ptrdiff_t)ctx & (ALLOC_BOUNDARY -1));
1020            ctx = (uhash_ctx_t)((u_char *)ctx + bytes_to_add);
1021            *((u_char *)ctx - 1) = bytes_to_add;
1022        }
1023        aes_key_setup(key,prf_key);
1024        uhash_init(ctx, prf_key);
1025    }
1026    return (ctx);
1027}
1028#endif
1029
1030/* ---------------------------------------------------------------------- */
1031
1032#if 0
1033static int uhash_free(uhash_ctx_t ctx)
1034{
1035/* Free memory allocated by uhash_alloc */
1036    u_char bytes_to_sub;
1037
1038    if (ctx) {
1039        if (ALLOC_BOUNDARY) {
1040            bytes_to_sub = *((u_char *)ctx - 1);
1041            ctx = (uhash_ctx_t)((u_char *)ctx - bytes_to_sub);
1042        }
1043        free(ctx);
1044    }
1045    return (1);
1046}
1047#endif
1048/* ---------------------------------------------------------------------- */
1049
1050static int uhash_update(uhash_ctx_t ctx, u_char *input, long len)
1051/* Given len bytes of data, we parse it into L1_KEY_LEN chunks and
1052 * hash each one with NH, calling the polyhash on each NH output.
1053 */
1054{
1055    UWORD bytes_hashed, bytes_remaining;
1056    UINT64 result_buf[STREAMS];
1057    UINT8 *nh_result = (UINT8 *)&result_buf;
1058
1059    if (ctx->msg_len + len <= L1_KEY_LEN) {
1060        nh_update(&ctx->hash, (UINT8 *)input, len);
1061        ctx->msg_len += len;
1062    } else {
1063
1064         bytes_hashed = ctx->msg_len % L1_KEY_LEN;
1065         if (ctx->msg_len == L1_KEY_LEN)
1066             bytes_hashed = L1_KEY_LEN;
1067
1068         if (bytes_hashed + len >= L1_KEY_LEN) {
1069
1070             /* If some bytes have been passed to the hash function      */
1071             /* then we want to pass at most (L1_KEY_LEN - bytes_hashed) */
1072             /* bytes to complete the current nh_block.                  */
1073             if (bytes_hashed) {
1074                 bytes_remaining = (L1_KEY_LEN - bytes_hashed);
1075                 nh_update(&ctx->hash, (UINT8 *)input, bytes_remaining);
1076                 nh_final(&ctx->hash, nh_result);
1077                 ctx->msg_len += bytes_remaining;
1078                 poly_hash(ctx,(UINT32 *)nh_result);
1079                 len -= bytes_remaining;
1080                 input += bytes_remaining;
1081             }
1082
1083             /* Hash directly from input stream if enough bytes */
1084             while (len >= L1_KEY_LEN) {
1085                 nh(&ctx->hash, (UINT8 *)input, L1_KEY_LEN,
1086                                   L1_KEY_LEN, nh_result);
1087                 ctx->msg_len += L1_KEY_LEN;
1088                 len -= L1_KEY_LEN;
1089                 input += L1_KEY_LEN;
1090                 poly_hash(ctx,(UINT32 *)nh_result);
1091             }
1092         }
1093
1094         /* pass remaining < L1_KEY_LEN bytes of input data to NH */
1095         if (len) {
1096             nh_update(&ctx->hash, (UINT8 *)input, len);
1097             ctx->msg_len += len;
1098         }
1099     }
1100
1101    return (1);
1102}
1103
1104/* ---------------------------------------------------------------------- */
1105
1106static int uhash_final(uhash_ctx_t ctx, u_char *res)
1107/* Incorporate any pending data, pad, and generate tag */
1108{
1109    UINT64 result_buf[STREAMS];
1110    UINT8 *nh_result = (UINT8 *)&result_buf;
1111
1112    if (ctx->msg_len > L1_KEY_LEN) {
1113        if (ctx->msg_len % L1_KEY_LEN) {
1114            nh_final(&ctx->hash, nh_result);
1115            poly_hash(ctx,(UINT32 *)nh_result);
1116        }
1117        ip_long(ctx, res);
1118    } else {
1119        nh_final(&ctx->hash, nh_result);
1120        ip_short(ctx,nh_result, res);
1121    }
1122    uhash_reset(ctx);
1123    return (1);
1124}
1125
1126/* ---------------------------------------------------------------------- */
1127
1128#if 0
1129static int uhash(uhash_ctx_t ahc, u_char *msg, long len, u_char *res)
1130/* assumes that msg is in a writable buffer of length divisible by */
1131/* L1_PAD_BOUNDARY. Bytes beyond msg[len] may be zeroed.           */
1132{
1133    UINT8 nh_result[STREAMS*sizeof(UINT64)];
1134    UINT32 nh_len;
1135    int extra_zeroes_needed;
1136
1137    /* If the message to be hashed is no longer than L1_HASH_LEN, we skip
1138     * the polyhash.
1139     */
1140    if (len <= L1_KEY_LEN) {
1141    	if (len == 0)                  /* If zero length messages will not */
1142    		nh_len = L1_PAD_BOUNDARY;  /* be seen, comment out this case   */
1143    	else
1144        	nh_len = ((len + (L1_PAD_BOUNDARY - 1)) & ~(L1_PAD_BOUNDARY - 1));
1145        extra_zeroes_needed = nh_len - len;
1146        zero_pad((UINT8 *)msg + len, extra_zeroes_needed);
1147        nh(&ahc->hash, (UINT8 *)msg, nh_len, len, nh_result);
1148        ip_short(ahc,nh_result, res);
1149    } else {
1150        /* Otherwise, we hash each L1_KEY_LEN chunk with NH, passing the NH
1151         * output to poly_hash().
1152         */
1153        do {
1154            nh(&ahc->hash, (UINT8 *)msg, L1_KEY_LEN, L1_KEY_LEN, nh_result);
1155            poly_hash(ahc,(UINT32 *)nh_result);
1156            len -= L1_KEY_LEN;
1157            msg += L1_KEY_LEN;
1158        } while (len >= L1_KEY_LEN);
1159        if (len) {
1160            nh_len = ((len + (L1_PAD_BOUNDARY - 1)) & ~(L1_PAD_BOUNDARY - 1));
1161            extra_zeroes_needed = nh_len - len;
1162            zero_pad((UINT8 *)msg + len, extra_zeroes_needed);
1163            nh(&ahc->hash, (UINT8 *)msg, nh_len, len, nh_result);
1164            poly_hash(ahc,(UINT32 *)nh_result);
1165        }
1166
1167        ip_long(ahc, res);
1168    }
1169
1170    uhash_reset(ahc);
1171    return 1;
1172}
1173#endif
1174
1175/* ---------------------------------------------------------------------- */
1176/* ---------------------------------------------------------------------- */
1177/* ----- Begin UMAC Section --------------------------------------------- */
1178/* ---------------------------------------------------------------------- */
1179/* ---------------------------------------------------------------------- */
1180
1181/* The UMAC interface has two interfaces, an all-at-once interface where
1182 * the entire message to be authenticated is passed to UMAC in one buffer,
1183 * and a sequential interface where the message is presented a little at a
1184 * time. The all-at-once is more optimaized than the sequential version and
1185 * should be preferred when the sequential interface is not required.
1186 */
1187struct umac_ctx {
1188    uhash_ctx hash;          /* Hash function for message compression    */
1189    pdf_ctx pdf;             /* PDF for hashed output                    */
1190    void *free_ptr;          /* Address to free this struct via          */
1191} umac_ctx;
1192
1193/* ---------------------------------------------------------------------- */
1194
1195#if 0
1196int umac_reset(struct umac_ctx *ctx)
1197/* Reset the hash function to begin a new authentication.        */
1198{
1199    uhash_reset(&ctx->hash);
1200    return (1);
1201}
1202#endif
1203
1204/* ---------------------------------------------------------------------- */
1205
1206int umac_delete(struct umac_ctx *ctx)
1207/* Deallocate the ctx structure */
1208{
1209    if (ctx) {
1210        if (ALLOC_BOUNDARY)
1211            ctx = (struct umac_ctx *)ctx->free_ptr;
1212        xfree(ctx);
1213    }
1214    return (1);
1215}
1216
1217/* ---------------------------------------------------------------------- */
1218
1219struct umac_ctx *umac_new(u_char key[])
1220/* Dynamically allocate a umac_ctx struct, initialize variables,
1221 * generate subkeys from key. Align to 16-byte boundary.
1222 */
1223{
1224    struct umac_ctx *ctx, *octx;
1225    size_t bytes_to_add;
1226    aes_int_key prf_key;
1227
1228    octx = ctx = xmalloc(sizeof(*ctx) + ALLOC_BOUNDARY);
1229    if (ctx) {
1230        if (ALLOC_BOUNDARY) {
1231            bytes_to_add = ALLOC_BOUNDARY -
1232                              ((ptrdiff_t)ctx & (ALLOC_BOUNDARY - 1));
1233            ctx = (struct umac_ctx *)((u_char *)ctx + bytes_to_add);
1234        }
1235        ctx->free_ptr = octx;
1236        aes_key_setup(key,prf_key);
1237        pdf_init(&ctx->pdf, prf_key);
1238        uhash_init(&ctx->hash, prf_key);
1239    }
1240
1241    return (ctx);
1242}
1243
1244/* ---------------------------------------------------------------------- */
1245
1246int umac_final(struct umac_ctx *ctx, u_char tag[], u_char nonce[8])
1247/* Incorporate any pending data, pad, and generate tag */
1248{
1249    uhash_final(&ctx->hash, (u_char *)tag);
1250    pdf_gen_xor(&ctx->pdf, (UINT8 *)nonce, (UINT8 *)tag);
1251
1252    return (1);
1253}
1254
1255/* ---------------------------------------------------------------------- */
1256
1257int umac_update(struct umac_ctx *ctx, u_char *input, long len)
1258/* Given len bytes of data, we parse it into L1_KEY_LEN chunks and   */
1259/* hash each one, calling the PDF on the hashed output whenever the hash- */
1260/* output buffer is full.                                                 */
1261{
1262    uhash_update(&ctx->hash, input, len);
1263    return (1);
1264}
1265
1266/* ---------------------------------------------------------------------- */
1267
1268#if 0
1269int umac(struct umac_ctx *ctx, u_char *input,
1270         long len, u_char tag[],
1271         u_char nonce[8])
1272/* All-in-one version simply calls umac_update() and umac_final().        */
1273{
1274    uhash(&ctx->hash, input, len, (u_char *)tag);
1275    pdf_gen_xor(&ctx->pdf, (UINT8 *)nonce, (UINT8 *)tag);
1276
1277    return (1);
1278}
1279#endif
1280
1281/* ---------------------------------------------------------------------- */
1282/* ---------------------------------------------------------------------- */
1283/* ----- End UMAC Section ----------------------------------------------- */
1284/* ---------------------------------------------------------------------- */
1285/* ---------------------------------------------------------------------- */
1286