Add GOST R 34.11-94 to nettle_hashes
[gd/nettle] / ecc-random.c
1 /* ecc-random.c
2
3    Copyright (C) 2013 Niels Möller
4
5    This file is part of GNU Nettle.
6
7    GNU Nettle is free software: you can redistribute it and/or
8    modify it under the terms of either:
9
10      * the GNU Lesser General Public License as published by the Free
11        Software Foundation; either version 3 of the License, or (at your
12        option) any later version.
13
14    or
15
16      * the GNU General Public License as published by the Free
17        Software Foundation; either version 2 of the License, or (at your
18        option) any later version.
19
20    or both in parallel, as here.
21
22    GNU Nettle is distributed in the hope that it will be useful,
23    but WITHOUT ANY WARRANTY; without even the implied warranty of
24    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25    General Public License for more details.
26
27    You should have received copies of the GNU General Public License and
28    the GNU Lesser General Public License along with this program.  If
29    not, see http://www.gnu.org/licenses/.
30 */
31
32 /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */
33
34 #if HAVE_CONFIG_H
35 # include "config.h"
36 #endif
37
38 #include <assert.h>
39
40 #include "ecc.h"
41 #include "ecc-internal.h"
42 #include "nettle-internal.h"
43
44 static int
45 zero_p (const struct ecc_modulo *m,
46         const mp_limb_t *xp)
47 {
48   mp_limb_t t;
49   mp_size_t i;
50
51   for (i = t = 0; i < m->size; i++)
52     t |= xp[i];
53
54   return t == 0;
55 }
56
57 static int
58 ecdsa_in_range (const struct ecc_modulo *m,
59                 const mp_limb_t *xp, mp_limb_t *scratch)
60 {
61   /* Check if 0 < x < q, with data independent timing. */
62   return !zero_p (m, xp)
63     & (mpn_sub_n (scratch, xp, m->m, m->size) != 0);
64 }
65
66 void
67 ecc_mod_random (const struct ecc_modulo *m, mp_limb_t *xp,
68                 void *ctx, nettle_random_func *random, mp_limb_t *scratch)
69 {
70   uint8_t *buf = (uint8_t *) scratch;
71   unsigned nbytes = (m->bit_size + 7)/8;
72
73   /* The bytes ought to fit in the scratch area, unless we have very
74      unusual limb and byte sizes. */
75   assert (nbytes <= m->size * sizeof (mp_limb_t));
76
77   do
78     {
79       random (ctx, nbytes, buf);
80       buf[0] &= 0xff >> (nbytes * 8 - m->bit_size);
81
82       mpn_set_base256 (xp, m->size, buf, nbytes);
83     }
84   while (!ecdsa_in_range (m, xp, scratch));
85 }
86
87 void
88 ecc_scalar_random (struct ecc_scalar *x,
89                    void *random_ctx, nettle_random_func *random)
90 {
91   TMP_DECL (scratch, mp_limb_t, ECC_MOD_RANDOM_ITCH (ECC_MAX_SIZE));
92   TMP_ALLOC (scratch, ECC_MOD_RANDOM_ITCH (x->ecc->q.size));
93
94   ecc_mod_random (&x->ecc->q, x->p, random_ctx, random, scratch);
95 }