testutils.c: Fix high bits of the mpz_urandomb used with mini-gmp.
[gd/nettle] / poly1305-aes.c
1 /* poly1305-aes.c
2
3    Copyright (C) 2013 Nikos Mavrogiannopoulos
4    Copyright (C) 2014 Niels Möller
5
6    This file is part of GNU Nettle.
7
8    GNU Nettle is free software: you can redistribute it and/or
9    modify it under the terms of either:
10
11      * the GNU Lesser General Public License as published by the Free
12        Software Foundation; either version 3 of the License, or (at your
13        option) any later version.
14
15    or
16
17      * the GNU General Public License as published by the Free
18        Software Foundation; either version 2 of the License, or (at your
19        option) any later version.
20
21    or both in parallel, as here.
22
23    GNU Nettle is distributed in the hope that it will be useful,
24    but WITHOUT ANY WARRANTY; without even the implied warranty of
25    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
26    General Public License for more details.
27
28    You should have received copies of the GNU General Public License and
29    the GNU Lesser General Public License along with this program.  If
30    not, see http://www.gnu.org/licenses/.
31 */
32
33 #if HAVE_CONFIG_H
34 #include "config.h"
35 #endif
36
37 #include <assert.h>
38 #include <string.h>
39
40 #include "poly1305.h"
41 #include "macros.h"
42
43 void
44 poly1305_aes_set_key (struct poly1305_aes_ctx *ctx, const uint8_t * key)
45 {
46   aes128_set_encrypt_key(&ctx->aes, (key));
47   poly1305_set_key(&ctx->pctx, (key+16));
48   ctx->index = 0;
49 }
50
51 void
52 poly1305_aes_set_nonce (struct poly1305_aes_ctx *ctx,
53                         const uint8_t * nonce)
54 {
55   memcpy (ctx->nonce, nonce, POLY1305_AES_NONCE_SIZE);
56 }
57
58 #define COMPRESS(ctx, data) _poly1305_block(&(ctx)->pctx, (data), 1)
59
60 void
61 poly1305_aes_update (struct poly1305_aes_ctx *ctx,
62                      size_t length, const uint8_t *data)
63 {
64   MD_UPDATE (ctx, length, data, COMPRESS, (void) 0);
65 }
66
67 void
68 poly1305_aes_digest (struct poly1305_aes_ctx *ctx,
69                      size_t length, uint8_t *digest)
70 {
71   union nettle_block16 s;
72   /* final bytes */
73   if (ctx->index > 0)
74     {
75       assert (ctx->index < POLY1305_BLOCK_SIZE);
76
77       ctx->block[ctx->index] = 1;
78       memset (ctx->block + ctx->index + 1,
79               0, POLY1305_BLOCK_SIZE - 1 - ctx->index);
80
81       _poly1305_block (&ctx->pctx, ctx->block, 0);
82     }
83   aes128_encrypt(&ctx->aes, POLY1305_BLOCK_SIZE, s.b, ctx->nonce);
84   
85   poly1305_digest (&ctx->pctx, &s);
86   memcpy (digest, s.b, length);
87
88   INCREMENT (16, ctx->nonce);
89   ctx->index = 0;
90 }