3 Generating big random numbers
5 Copyright (C) 2002, 2013 Niels Möller
7 This file is part of GNU Nettle.
9 GNU Nettle is free software: you can redistribute it and/or
10 modify it under the terms of either:
12 * the GNU Lesser General Public License as published by the Free
13 Software Foundation; either version 3 of the License, or (at your
14 option) any later version.
18 * the GNU General Public License as published by the Free
19 Software Foundation; either version 2 of the License, or (at your
20 option) any later version.
22 or both in parallel, as here.
24 GNU Nettle is distributed in the hope that it will be useful,
25 but WITHOUT ANY WARRANTY; without even the implied warranty of
26 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27 General Public License for more details.
29 You should have received copies of the GNU General Public License and
30 the GNU Lesser General Public License along with this program. If
31 not, see http://www.gnu.org/licenses/.
44 nettle_mpz_random_size(mpz_t x,
45 void *ctx, nettle_random_func *random,
48 unsigned length = (bits + 7) / 8;
49 TMP_GMP_DECL(data, uint8_t);
51 TMP_GMP_ALLOC(data, length);
53 random(ctx, length, data);
54 nettle_mpz_set_str_256_u(x, length, data);
57 mpz_fdiv_r_2exp(x, x, bits);
62 /* Returns a random number x, 0 <= x < n */
64 nettle_mpz_random(mpz_t x,
65 void *ctx, nettle_random_func *random,
68 /* NOTE: This leaves some bias, which may be bad for DSA. A better
69 * way might be to generate a random number of mpz_sizeinbase(n, 2)
70 * bits, and loop until one smaller than n is found. */
72 /* From Daniel Bleichenbacher (via coderpunks):
74 * There is still a theoretical attack possible with 8 extra bits.
75 * But, the attack would need about 2^66 signatures 2^66 memory and
76 * 2^66 time (if I remember that correctly). Compare that to DSA,
77 * where the attack requires 2^22 signatures 2^40 memory and 2^64
78 * time. And of course, the numbers above are not a real threat for
79 * PGP. Using 16 extra bits (i.e. generating a 176 bit random number
80 * and reducing it modulo q) will defeat even this theoretical
83 * More generally log_2(q)/8 extra bits are enough to defeat my
84 * attack. NIST also plans to update the standard.
87 /* Add a few bits extra, to decrease the bias from the final modulo
88 * operation. NIST FIPS 186-3 specifies 64 extra bits, for use with
91 nettle_mpz_random_size(x,
93 mpz_sizeinbase(n, 2) + 64);