Coverage Report

Created: 2020-09-16 07:52

/src/botan/src/lib/math/numbertheory/make_prm.cpp
Line
Count
Source (jump to first uncovered line)
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/numthry.h>
9
#include <botan/rng.h>
10
#include <botan/internal/bit_ops.h>
11
#include <botan/loadstor.h>
12
#include <botan/reducer.h>
13
#include <botan/internal/primality.h>
14
#include <algorithm>
15
16
namespace Botan {
17
18
namespace {
19
20
class Prime_Sieve final
21
   {
22
   public:
23
      Prime_Sieve(const BigInt& init_value, size_t sieve_size) :
24
         m_sieve(std::min(sieve_size, PRIME_TABLE_SIZE))
25
1
         {
26
257
         for(size_t i = 0; i != m_sieve.size(); ++i)
27
256
            m_sieve[i] = static_cast<uint16_t>(init_value % PRIMES[i]);
28
1
         }
29
30
      void step(word increment)
31
999
         {
32
256k
         for(size_t i = 0; i != m_sieve.size(); ++i)
33
255k
            {
34
255k
            m_sieve[i] = (m_sieve[i] + increment) % PRIMES[i];
35
255k
            }
36
999
         }
37
38
      bool passes(bool check_2p1 = false) const
39
999
         {
40
7.25k
         for(size_t i = 0; i != m_sieve.size(); ++i)
41
7.23k
            {
42
            /*
43
            In this case, p is a multiple of PRIMES[i]
44
            */
45
7.23k
            if(m_sieve[i] == 0)
46
495
               return false;
47
6.74k
48
6.74k
            if(check_2p1)
49
6.74k
               {
50
               /*
51
               In this case, 2*p+1 will be a multiple of PRIMES[i]
52
53
               So if potentially generating a safe prime, we want to
54
               avoid this value because 2*p+1 will certainly not be prime.
55
56
               See "Safe Prime Generation with a Combined Sieve" M. Wiener
57
               https://eprint.iacr.org/2003/186.pdf
58
               */
59
6.74k
               if(m_sieve[i] == (PRIMES[i] - 1) / 2)
60
489
                  return false;
61
6.74k
               }
62
6.74k
            }
63
999
64
15
         return true;
65
999
         }
66
67
   private:
68
      std::vector<uint16_t> m_sieve;
69
   };
70
71
}
72
73
74
/*
75
* Generate a random prime
76
*/
77
BigInt random_prime(RandomNumberGenerator& rng,
78
                    size_t bits, const BigInt& coprime,
79
                    size_t equiv, size_t modulo,
80
                    size_t prob)
81
1
   {
82
1
   if(bits <= 1)
83
0
      {
84
0
      throw Invalid_Argument("random_prime: Can't make a prime of " +
85
0
                             std::to_string(bits) + " bits");
86
0
      }
87
1
   if(coprime.is_negative() || (!coprime.is_zero() && coprime.is_even()) || coprime.bits() >= bits)
88
0
      {
89
0
      throw Invalid_Argument("random_prime: invalid coprime");
90
0
      }
91
1
   if(modulo == 0)
92
0
      {
93
0
      throw Invalid_Argument("random_prime: Invalid modulo value");
94
0
      }
95
1
96
1
   equiv %= modulo;
97
1
98
1
   if(equiv == 0)
99
0
      throw Invalid_Argument("random_prime Invalid value for equiv/modulo");
100
1
101
   // Handle small values:
102
1
103
1
   if(bits <= 16)
104
0
      {
105
0
      if(equiv != 1 || modulo != 2 || coprime != 0)
106
0
         throw Not_Implemented("random_prime equiv/modulo/coprime options not usable for small primes");
107
0
108
0
      if(bits == 2)
109
0
         {
110
0
         return ((rng.next_byte() % 2) ? 2 : 3);
111
0
         }
112
0
      else if(bits == 3)
113
0
         {
114
0
         return ((rng.next_byte() % 2) ? 5 : 7);
115
0
         }
116
0
      else if(bits == 4)
117
0
         {
118
0
         return ((rng.next_byte() % 2) ? 11 : 13);
119
0
         }
120
0
      else
121
0
         {
122
0
         for(;;)
123
0
            {
124
            // This is slightly biased, but for small primes it does not seem to matter
125
0
            uint8_t b[4];
126
0
            rng.randomize(b, 4);
127
0
            const size_t idx = load_le<uint32_t>(b, 0) % PRIME_TABLE_SIZE;
128
0
            const uint16_t small_prime = PRIMES[idx];
129
0
130
0
            if(high_bit(small_prime) == bits)
131
0
               return small_prime;
132
0
            }
133
0
         }
134
0
      }
135
1
136
1
   const size_t MAX_ATTEMPTS = 32*1024;
137
1
138
1
   const size_t mr_trials = miller_rabin_test_iterations(bits, prob, true);
139
1
140
1
   while(true)
141
1
      {
142
1
      BigInt p(rng, bits);
143
1
144
      // Force lowest and two top bits on
145
1
      p.set_bit(bits - 1);
146
1
      p.set_bit(bits - 2);
147
1
      p.set_bit(0);
148
1
149
      // Force p to be equal to equiv mod modulo
150
1
      p += (modulo - (p % modulo)) + equiv;
151
1
152
1
      Prime_Sieve sieve(p, bits);
153
1
154
999
      for(size_t attempt = 0; attempt <= MAX_ATTEMPTS; ++attempt)
155
999
         {
156
999
         p += modulo;
157
999
158
999
         sieve.step(modulo);
159
999
160
         // p can be even if modulo is odd, continue on in that case
161
999
         if(p.is_even() || sieve.passes(true) == false)
162
984
            continue;
163
15
164
15
         Modular_Reducer mod_p(p);
165
15
166
15
         if(coprime > 1)
167
0
            {
168
            /*
169
            First do a single M-R iteration to quickly elimate most non-primes,
170
            before doing the coprimality check which is expensive
171
            */
172
0
            if(is_miller_rabin_probable_prime(p, mod_p, rng, 1) == false)
173
0
               continue;
174
0
175
            /*
176
            * Check if p - 1 and coprime are relatively prime, using gcd.
177
            * The gcd computation is const-time
178
            */
179
0
            if(gcd(p - 1, coprime) > 1)
180
0
               continue;
181
15
            }
182
15
183
15
         if(p.bits() > bits)
184
0
            break;
185
15
186
15
         if(is_miller_rabin_probable_prime(p, mod_p, rng, mr_trials) == false)
187
14
            continue;
188
1
189
1
         if(prob > 32 && !is_lucas_probable_prime(p, mod_p))
190
0
            continue;
191
1
192
1
         return p;
193
1
         }
194
1
      }
195
1
   }
196
197
BigInt generate_rsa_prime(RandomNumberGenerator& keygen_rng,
198
                          RandomNumberGenerator& prime_test_rng,
199
                          size_t bits,
200
                          const BigInt& coprime,
201
                          size_t prob)
202
0
   {
203
0
   if(bits < 512)
204
0
      throw Invalid_Argument("generate_rsa_prime bits too small");
205
0
206
   /*
207
   * The restriction on coprime <= 64 bits is arbitrary but generally speaking
208
   * very large RSA public exponents are a bad idea both for performance and due
209
   * to attacks on small d.
210
   */
211
0
   if(coprime <= 1 || coprime.is_even() || coprime.bits() > 64)
212
0
      throw Invalid_Argument("generate_rsa_prime coprime must be small odd positive integer");
213
0
214
0
   const size_t MAX_ATTEMPTS = 32*1024;
215
0
216
0
   const size_t mr_trials = miller_rabin_test_iterations(bits, prob, true);
217
0
218
0
   while(true)
219
0
      {
220
0
      BigInt p(keygen_rng, bits);
221
0
222
      // Force high two bits so multiplication always results in expected n bit integer
223
0
      p.set_bit(bits - 1);
224
0
      p.set_bit(bits - 2);
225
0
      p.set_bit(0);
226
0
227
0
      const word step = 2;
228
0
229
0
      Prime_Sieve sieve(p, bits);
230
0
231
0
      for(size_t attempt = 0; attempt <= MAX_ATTEMPTS; ++attempt)
232
0
         {
233
0
         p += step;
234
0
235
0
         sieve.step(step);
236
0
237
0
         if(sieve.passes() == false)
238
0
            continue;
239
0
240
0
         Modular_Reducer mod_p(p);
241
0
242
         /*
243
         * Do a single primality test first before checking coprimality, since
244
         * currently a single Miller-Rabin test is faster than computing gcd,
245
         * and this eliminates almost all wasted gcd computations.
246
         */
247
0
         if(is_miller_rabin_probable_prime(p, mod_p, prime_test_rng, 1) == false)
248
0
            continue;
249
0
250
         /*
251
         * Check if p - 1 and coprime are relatively prime.
252
         */
253
0
         if(gcd(p - 1, coprime) > 1)
254
0
            continue;
255
0
256
0
         if(p.bits() > bits)
257
0
            break;
258
0
259
0
         if(is_miller_rabin_probable_prime(p, mod_p, prime_test_rng, mr_trials) == true)
260
0
            return p;
261
0
         }
262
0
      }
263
0
   }
264
265
/*
266
* Generate a random safe prime
267
*/
268
BigInt random_safe_prime(RandomNumberGenerator& rng, size_t bits)
269
0
   {
270
0
   if(bits <= 64)
271
0
      throw Invalid_Argument("random_safe_prime: Can't make a prime of " +
272
0
                             std::to_string(bits) + " bits");
273
0
274
0
   const size_t error_bound = 128;
275
0
276
0
   BigInt q, p;
277
0
   for(;;)
278
0
      {
279
      /*
280
      Generate q == 2 (mod 3), since otherwise [in the case of q == 1 (mod 3)],
281
      2*q+1 == 3 (mod 3) and so certainly not prime.
282
      */
283
0
      q = random_prime(rng, bits - 1, 0, 2, 3, error_bound);
284
0
      p = (q << 1) + 1;
285
0
286
0
      if(is_prime(p, rng, error_bound, true))
287
0
         {
288
0
         return p;
289
0
         }
290
0
      }
291
0
   }
292
293
}