3
* Generating big random numbers
6
/* nettle, low-level cryptographics library
8
* Copyright (C) 2002 Niels M�ller
10
* The nettle library is free software; you can redistribute it and/or modify
11
* it under the terms of the GNU Lesser General Public License as published by
12
* the Free Software Foundation; either version 2.1 of the License, or (at your
13
* option) any later version.
15
* The nettle library is distributed in the hope that it will be useful, but
16
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
18
* License for more details.
20
* You should have received a copy of the GNU Lesser General Public License
21
* along with the nettle library; see the file COPYING.LIB. If not, write to
22
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
35
#include "nettle-internal.h"
38
nettle_mpz_random_size(mpz_t x,
39
void *ctx, nettle_random_func random,
42
unsigned length = (bits + 7) / 8;
43
TMP_DECL(data, uint8_t, NETTLE_MAX_BIGNUM_BITS / 8);
44
TMP_ALLOC(data, length);
46
random(ctx, length, data);
48
nettle_mpz_set_str_256_u(x, length, data);
51
mpz_fdiv_r_2exp(x, x, bits);
54
/* Returns a random number x, 0 <= x < n */
56
nettle_mpz_random(mpz_t x,
57
void *ctx, nettle_random_func random,
60
/* FIXME: This leaves some bias, which may be bad for DSA. A better
61
* way might to generate a random number of mpz_sizeinbase(n, 2)
62
* bits, and loop until one smaller than n is found. */
64
/* From Daniel Bleichenbacher (via coderpunks):
66
* There is still a theoretical attack possible with 8 extra bits.
67
* But, the attack would need about 2^66 signatures 2^66 memory and
68
* 2^66 time (if I remember that correctly). Compare that to DSA,
69
* where the attack requires 2^22 signatures 2^40 memory and 2^64
70
* time. And of course, the numbers above are not a real threat for
71
* PGP. Using 16 extra bits (i.e. generating a 176 bit random number
72
* and reducing it modulo q) will defeat even this theoretical
75
* More generally log_2(q)/8 extra bits are enough to defeat my
76
* attack. NIST also plans to update the standard.
79
/* Add a few bits extra, to decrease the bias from the final modulo
82
nettle_mpz_random_size(x,
84
mpz_sizeinbase(n, 2) + 16);
89
#endif /* HAVE_LIBGMP */