Botan 3.0.0
Crypto and TLS for C&
make_prm.cpp
Go to the documentation of this file.
1/*
2* Prime Generation
3* (C) 1999-2007,2018,2019 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/internal/primality.h>
9#include <botan/numthry.h>
10#include <botan/rng.h>
11#include <botan/internal/bit_ops.h>
12#include <botan/internal/ct_utils.h>
13#include <botan/internal/loadstor.h>
14#include <botan/reducer.h>
15#include <algorithm>
16
17namespace Botan {
18
19namespace {
20
21class Prime_Sieve final
22 {
23 public:
24 Prime_Sieve(const BigInt& init_value, size_t sieve_size, word step, bool check_2p1) :
25 m_sieve(std::min(sieve_size, PRIME_TABLE_SIZE)),
26 m_step(step),
27 m_check_2p1(check_2p1)
28 {
29 for(size_t i = 0; i != m_sieve.size(); ++i)
30 m_sieve[i] = init_value % PRIMES[i];
31 }
32
33 size_t sieve_size() const { return m_sieve.size(); }
34
35 bool check_2p1() const { return m_check_2p1; }
36
37 bool next()
38 {
39 auto passes = CT::Mask<word>::set();
40 for(size_t i = 0; i != m_sieve.size(); ++i)
41 {
42 m_sieve[i] = (m_sieve[i] + m_step) % PRIMES[i];
43
44 // If m_sieve[i] == 0 then val % p == 0 -> not prime
45 passes &= CT::Mask<word>::expand(m_sieve[i]);
46
47 if(this->check_2p1())
48 {
49 /*
50 If v % p == (p-1)/2 then 2*v+1 == 0 (mod p)
51
52 So if potentially generating a safe prime, we want to
53 avoid this value because 2*v+1 will certainly not be prime.
54
55 See "Safe Prime Generation with a Combined Sieve" M. Wiener
56 https://eprint.iacr.org/2003/186.pdf
57 */
58 passes &= ~CT::Mask<word>::is_equal(m_sieve[i], (PRIMES[i] - 1) / 2);
59 }
60 }
61
62 return passes.is_set();
63 }
64
65 private:
66 std::vector<word> m_sieve;
67 const word m_step;
68 const bool m_check_2p1;
69 };
70
71#if defined(BOTAN_ENABLE_DEBUG_ASSERTS)
72
73bool no_small_multiples(const BigInt& v, const Prime_Sieve& sieve)
74 {
75 const size_t sieve_size = sieve.sieve_size();
76 const bool check_2p1 = sieve.check_2p1();
77
78 if(v.is_even())
79 return false;
80
81 const BigInt v_x2_p1 = 2*v + 1;
82
83 for(size_t i = 0; i != sieve_size; ++i)
84 {
85 if((v % PRIMES[i]) == 0)
86 return false;
87
88 if(check_2p1)
89 {
90 if(v_x2_p1 % PRIMES[i] == 0)
91 return false;
92 }
93 }
94
95 return true;
96 }
97
98#endif
99
100}
101
102
103/*
104* Generate a random prime
105*/
107 size_t bits, const BigInt& coprime,
108 size_t equiv, size_t modulo,
109 size_t prob)
110 {
111 if(bits <= 1)
112 {
113 throw Invalid_Argument("random_prime: Can't make a prime of " +
114 std::to_string(bits) + " bits");
115 }
116 if(coprime.is_negative() || (!coprime.is_zero() && coprime.is_even()) || coprime.bits() >= bits)
117 {
118 throw Invalid_Argument("random_prime: invalid coprime");
119 }
120 if(modulo == 0 || modulo >= 100000)
121 {
122 throw Invalid_Argument("random_prime: Invalid modulo value");
123 }
124
125 equiv %= modulo;
126
127 if(equiv == 0)
128 throw Invalid_Argument("random_prime Invalid value for equiv/modulo");
129
130 // Handle small values:
131
132 if(bits <= 16)
133 {
134 if(equiv != 1 || modulo != 2 || coprime != 0)
135 throw Not_Implemented("random_prime equiv/modulo/coprime options not usable for small primes");
136
137 if(bits == 2)
138 {
139 return BigInt::from_word(((rng.next_byte() % 2) ? 2 : 3));
140 }
141 else if(bits == 3)
142 {
143 return BigInt::from_word(((rng.next_byte() % 2) ? 5 : 7));
144 }
145 else if(bits == 4)
146 {
147 return BigInt::from_word(((rng.next_byte() % 2) ? 11 : 13));
148 }
149 else
150 {
151 for(;;)
152 {
153 // This is slightly biased, but for small primes it does not seem to matter
154 uint8_t b[4];
155 rng.randomize(b, 4);
156 const size_t idx = load_le<uint32_t>(b, 0) % PRIME_TABLE_SIZE;
157 const uint16_t small_prime = PRIMES[idx];
158
159 if(high_bit(small_prime) == bits)
160 return BigInt::from_word(small_prime);
161 }
162 }
163 }
164
165 const size_t MAX_ATTEMPTS = 32*1024;
166
167 const size_t mr_trials = miller_rabin_test_iterations(bits, prob, true);
168
169 while(true)
170 {
171 BigInt p(rng, bits);
172
173 // Force lowest and two top bits on
174 p.set_bit(bits - 1);
175 p.set_bit(bits - 2);
176 p.set_bit(0);
177
178 // Force p to be equal to equiv mod modulo
179 p += (modulo - (p % modulo)) + equiv;
180
181 Prime_Sieve sieve(p, bits, modulo, true);
182
183 for(size_t attempt = 0; attempt <= MAX_ATTEMPTS; ++attempt)
184 {
185 p += modulo;
186
187 if(!sieve.next())
188 continue;
189
190 // here p can be even if modulo is odd, continue on in that case
191 if(p.is_even())
192 continue;
193
194 BOTAN_DEBUG_ASSERT(no_small_multiples(p, sieve));
195
196 Modular_Reducer mod_p(p);
197
198 if(coprime > 1)
199 {
200 /*
201 First do a single M-R iteration to quickly elimate most non-primes,
202 before doing the coprimality check which is expensive
203 */
204 if(is_miller_rabin_probable_prime(p, mod_p, rng, 1) == false)
205 continue;
206
207 /*
208 * Check if p - 1 and coprime are relatively prime, using gcd.
209 * The gcd computation is const-time
210 */
211 if(gcd(p - 1, coprime) > 1)
212 continue;
213 }
214
215 if(p.bits() > bits)
216 break;
217
218 if(is_miller_rabin_probable_prime(p, mod_p, rng, mr_trials) == false)
219 continue;
220
221 if(prob > 32 && !is_lucas_probable_prime(p, mod_p))
222 continue;
223
224 return p;
225 }
226 }
227 }
228
230 RandomNumberGenerator& prime_test_rng,
231 size_t bits,
232 const BigInt& coprime,
233 size_t prob)
234 {
235 if(bits < 512)
236 throw Invalid_Argument("generate_rsa_prime bits too small");
237
238 /*
239 * The restriction on coprime <= 64 bits is arbitrary but generally speaking
240 * very large RSA public exponents are a bad idea both for performance and due
241 * to attacks on small d.
242 */
243 if(coprime <= 1 || coprime.is_even() || coprime.bits() > 64)
244 throw Invalid_Argument("generate_rsa_prime coprime must be small odd positive integer");
245
246 const size_t MAX_ATTEMPTS = 32*1024;
247
248 const size_t mr_trials = miller_rabin_test_iterations(bits, prob, true);
249
250 while(true)
251 {
252 BigInt p(keygen_rng, bits);
253
254 /*
255 Force high two bits so multiplication always results in expected n bit integer
256
257 Force the two low bits, and step by 4, so the generated prime is always == 3 (mod 4).
258 This way when we perform the inversion modulo phi(n) it is always of the form 2*o
259 with o odd, which allows a fastpath and avoids leaking any information about the
260 structure of the prime.
261 */
262 p.set_bit(bits - 1);
263 p.set_bit(bits - 2);
264 p.set_bit(1);
265 p.set_bit(0);
266
267 const word step = 4;
268
269 Prime_Sieve sieve(p, bits, step, false);
270
271 for(size_t attempt = 0; attempt <= MAX_ATTEMPTS; ++attempt)
272 {
273 p += step;
274
275 if(!sieve.next())
276 continue;
277
278 BOTAN_DEBUG_ASSERT(no_small_multiples(p, sieve));
279
280 Modular_Reducer mod_p(p);
281
282 /*
283 * Do a single primality test first before checking coprimality, since
284 * currently a single Miller-Rabin test is faster than computing gcd,
285 * and this eliminates almost all wasted gcd computations.
286 */
287 if(is_miller_rabin_probable_prime(p, mod_p, prime_test_rng, 1) == false)
288 continue;
289
290 /*
291 * Check if p - 1 and coprime are relatively prime.
292 */
293 if(gcd(p - 1, coprime) > 1)
294 continue;
295
296 if(p.bits() > bits)
297 break;
298
299 if(is_miller_rabin_probable_prime(p, mod_p, prime_test_rng, mr_trials) == true)
300 return p;
301 }
302 }
303 }
304
305/*
306* Generate a random safe prime
307*/
309 {
310 if(bits <= 64)
311 throw Invalid_Argument("random_safe_prime: Can't make a prime of " +
312 std::to_string(bits) + " bits");
313
314 const size_t error_bound = 128;
315
316 BigInt q, p;
317 for(;;)
318 {
319 /*
320 Generate q == 2 (mod 3), since otherwise [in the case of q == 1 (mod 3)],
321 2*q+1 == 3 (mod 3) and so certainly not prime.
322 */
323 q = random_prime(rng, bits - 1, BigInt::zero(), 2, 3, error_bound);
324 p = (q << 1) + 1;
325
326 if(is_prime(p, rng, error_bound, true))
327 {
328 return p;
329 }
330 }
331 }
332
333}
#define BOTAN_DEBUG_ASSERT(expr)
Definition: assert.h:122
static BigInt zero()
Definition: bigint.h:45
void set_bit(size_t n)
Definition: bigint.h:443
size_t bits() const
Definition: bigint.cpp:312
bool is_even() const
Definition: bigint.h:416
static BigInt from_word(word n)
Definition: bigint.cpp:43
bool is_zero() const
Definition: bigint.h:434
bool is_negative() const
Definition: bigint.h:556
static Mask< T > expand(T v)
Definition: ct_utils.h:121
static Mask< T > set()
Definition: ct_utils.h:105
void randomize(std::span< uint8_t > output)
Definition: rng.h:53
int(* final)(unsigned char *, CTX *)
Definition: alg_id.cpp:12
constexpr uint32_t load_le< uint32_t >(const uint8_t in[], size_t off)
Definition: loadstor.h:209
BigInt random_prime(RandomNumberGenerator &rng, size_t bits, const BigInt &coprime, size_t equiv, size_t modulo, size_t prob)
Definition: make_prm.cpp:106
const uint16_t PRIMES[]
Definition: primes.cpp:12
constexpr size_t high_bit(T n)
Definition: bit_ops.h:58
const size_t PRIME_TABLE_SIZE
Definition: numthry.h:171
bool is_prime(const BigInt &n, RandomNumberGenerator &rng, size_t prob, bool is_random)
Definition: numthry.cpp:370
bool is_miller_rabin_probable_prime(const BigInt &n, const Modular_Reducer &mod_n, RandomNumberGenerator &rng, size_t test_iterations)
Definition: primality.cpp:149
BigInt generate_rsa_prime(RandomNumberGenerator &keygen_rng, RandomNumberGenerator &prime_test_rng, size_t bits, const BigInt &coprime, size_t prob)
Definition: make_prm.cpp:229
BigInt gcd(const BigInt &a, const BigInt &b)
Definition: numthry.cpp:220
size_t miller_rabin_test_iterations(size_t n_bits, size_t prob, bool random)
Definition: primality.cpp:172
BigInt random_safe_prime(RandomNumberGenerator &rng, size_t bits)
Definition: make_prm.cpp:308
bool is_lucas_probable_prime(const BigInt &C, const Modular_Reducer &mod_C)
Definition: primality.cpp:17
Definition: bigint.h:1092