Coverage Report

Created: 2022-01-14 08:07

/src/botan/src/lib/math/numbertheory/numthry.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* Number Theory Functions
3
* (C) 1999-2011,2016,2018,2019 Jack Lloyd
4
* (C) 2007,2008 Falko Strenzke, FlexSecure GmbH
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8
9
#include <botan/numthry.h>
10
#include <botan/reducer.h>
11
#include <botan/internal/monty.h>
12
#include <botan/internal/divide.h>
13
#include <botan/rng.h>
14
#include <botan/internal/ct_utils.h>
15
#include <botan/internal/mp_core.h>
16
#include <botan/internal/monty_exp.h>
17
#include <botan/internal/primality.h>
18
#include <algorithm>
19
20
namespace Botan {
21
22
namespace {
23
24
void sub_abs(BigInt& z, const BigInt& x, const BigInt& y)
25
613k
   {
26
613k
   const size_t x_sw = x.sig_words();
27
613k
   const size_t y_sw = y.sig_words();
28
613k
   z.resize(std::max(x_sw, y_sw));
29
30
613k
   bigint_sub_abs(z.mutable_data(),
31
613k
                  x.data(), x_sw,
32
613k
                  y.data(), y_sw);
33
613k
   }
34
35
}
36
37
/*
38
* Tonelli-Shanks algorithm
39
*/
40
BigInt ressol(const BigInt& a, const BigInt& p)
41
35.0k
   {
42
35.0k
   if(p <= 1 || p.is_even())
43
0
      throw Invalid_Argument("ressol: invalid prime");
44
45
35.0k
   if(a == 0)
46
1
      return BigInt::zero();
47
35.0k
   else if(a < 0)
48
0
      throw Invalid_Argument("ressol: value to solve for must be positive");
49
35.0k
   else if(a >= p)
50
2
      throw Invalid_Argument("ressol: value to solve for must be less than p");
51
52
35.0k
   if(p == 2)
53
0
      return a;
54
55
35.0k
   if(jacobi(a, p) != 1) // not a quadratic residue
56
12.9k
      return BigInt::from_s32(-1);
57
58
22.0k
   Modular_Reducer mod_p(p);
59
22.0k
   auto monty_p = std::make_shared<Montgomery_Params>(p, mod_p);
60
61
22.0k
   if(p % 4 == 3) // The easy case
62
20.3k
      {
63
20.3k
      return monty_exp_vartime(monty_p, a, ((p+1) >> 2));
64
20.3k
      }
65
66
1.73k
   size_t s = low_zero_bits(p - 1);
67
1.73k
   BigInt q = p >> s;
68
69
1.73k
   q -= 1;
70
1.73k
   q >>= 1;
71
72
1.73k
   BigInt r = monty_exp_vartime(monty_p, a, q);
73
1.73k
   BigInt n = mod_p.multiply(a, mod_p.square(r));
74
1.73k
   r = mod_p.multiply(r, a);
75
76
1.73k
   if(n == 1)
77
117
      return r;
78
79
   // find random quadratic nonresidue z
80
1.61k
   word z = 2;
81
1.61k
   for(;;)
82
14.9k
      {
83
14.9k
      if(jacobi(BigInt::from_word(z), p) == -1) // found one
84
1.61k
         break;
85
86
13.2k
      z += 1; // try next z
87
88
      /*
89
      * The expected number of tests to find a non-residue modulo a
90
      * prime is 2. If we have not found one after 256 then almost
91
      * certainly we have been given a non-prime p.
92
      */
93
13.2k
      if(z >= 256)
94
0
         return BigInt::from_s32(-1);
95
13.2k
      }
96
97
1.61k
   BigInt c = monty_exp_vartime(monty_p, BigInt::from_word(z), (q << 1) + 1);
98
99
70.6k
   while(n > 1)
100
68.9k
      {
101
68.9k
      q = n;
102
103
68.9k
      size_t i = 0;
104
3.53M
      while(q != 1)
105
3.46M
         {
106
3.46M
         q = mod_p.square(q);
107
3.46M
         ++i;
108
109
3.46M
         if(i >= s)
110
0
            {
111
0
            return BigInt::from_s32(-1);
112
0
            }
113
3.46M
         }
114
115
68.9k
      BOTAN_ASSERT_NOMSG(s >= (i + 1)); // No underflow!
116
68.9k
      c = monty_exp_vartime(monty_p, c, BigInt::power_of_2(s-i-1));
117
68.9k
      r = mod_p.multiply(r, c);
118
68.9k
      c = mod_p.square(c);
119
68.9k
      n = mod_p.multiply(n, c);
120
121
      // s decreases as the algorithm proceeds
122
68.9k
      BOTAN_ASSERT_NOMSG(s >= i);
123
68.9k
      s = i;
124
68.9k
      }
125
126
1.61k
   return r;
127
1.61k
   }
128
129
/*
130
* Calculate the Jacobi symbol
131
*/
132
int32_t jacobi(const BigInt& a, const BigInt& n)
133
54.6k
   {
134
54.6k
   if(n.is_even() || n < 2)
135
0
      throw Invalid_Argument("jacobi: second argument must be odd and > 1");
136
137
54.6k
   BigInt x = a % n;
138
54.6k
   BigInt y = n;
139
54.6k
   int32_t J = 1;
140
141
3.84M
   while(y > 1)
142
3.78M
      {
143
3.78M
      x %= y;
144
3.78M
      if(x > y / 2)
145
1.76M
         {
146
1.76M
         x = y - x;
147
1.76M
         if(y % 4 == 3)
148
886k
            J = -J;
149
1.76M
         }
150
3.78M
      if(x.is_zero())
151
0
         return 0;
152
153
3.78M
      size_t shifts = low_zero_bits(x);
154
3.78M
      x >>= shifts;
155
3.78M
      if(shifts % 2)
156
1.21M
         {
157
1.21M
         word y_mod_8 = y % 8;
158
1.21M
         if(y_mod_8 == 3 || y_mod_8 == 5)
159
591k
            J = -J;
160
1.21M
         }
161
162
3.78M
      if(x % 4 == 3 && y % 4 == 3)
163
931k
         J = -J;
164
3.78M
      std::swap(x, y);
165
3.78M
      }
166
54.6k
   return J;
167
54.6k
   }
168
169
/*
170
* Square a BigInt
171
*/
172
BigInt square(const BigInt& x)
173
5.38M
   {
174
5.38M
   BigInt z = x;
175
5.38M
   secure_vector<word> ws;
176
5.38M
   z.square(ws);
177
5.38M
   return z;
178
5.38M
   }
179
180
/*
181
* Return the number of 0 bits at the end of n
182
*/
183
size_t low_zero_bits(const BigInt& n)
184
4.94M
   {
185
4.94M
   size_t low_zero = 0;
186
187
4.94M
   auto seen_nonempty_word = CT::Mask<word>::cleared();
188
189
82.0M
   for(size_t i = 0; i != n.size(); ++i)
190
77.1M
      {
191
77.1M
      const word x = n.word_at(i);
192
193
      // ctz(0) will return sizeof(word)
194
77.1M
      const size_t tz_x = ctz(x);
195
196
      // if x > 0 we want to count tz_x in total but not any
197
      // further words, so set the mask after the addition
198
77.1M
      low_zero += seen_nonempty_word.if_not_set_return(tz_x);
199
200
77.1M
      seen_nonempty_word |= CT::Mask<word>::expand(x);
201
77.1M
      }
202
203
   // if we saw no words with x > 0 then n == 0 and the value we have
204
   // computed is meaningless. Instead return BigInt::zero() in that case.
205
4.94M
   return seen_nonempty_word.if_set_return(low_zero);
206
4.94M
   }
207
208
209
namespace {
210
211
size_t safegcd_loop_bound(size_t f_bits, size_t g_bits)
212
1.43k
   {
213
1.43k
   const size_t d = std::max(f_bits, g_bits);
214
1.43k
   return 4 + 3*d;
215
1.43k
   }
216
217
}
218
219
/*
220
* Calculate the GCD
221
*/
222
BigInt gcd(const BigInt& a, const BigInt& b)
223
1.69k
   {
224
1.69k
   if(a.is_zero())
225
130
      return abs(b);
226
1.56k
   if(b.is_zero())
227
125
      return abs(a);
228
1.44k
   if(a == 1 || b == 1)
229
7
      return BigInt::one();
230
231
   // See https://gcd.cr.yp.to/safegcd-20190413.pdf fig 1.2
232
233
1.43k
   BigInt f = a;
234
1.43k
   BigInt g = b;
235
1.43k
   f.const_time_poison();
236
1.43k
   g.const_time_poison();
237
238
1.43k
   f.set_sign(BigInt::Positive);
239
1.43k
   g.set_sign(BigInt::Positive);
240
241
1.43k
   const size_t common2s = std::min(low_zero_bits(f), low_zero_bits(g));
242
1.43k
   CT::unpoison(common2s);
243
244
1.43k
   f >>= common2s;
245
1.43k
   g >>= common2s;
246
247
1.43k
   f.ct_cond_swap(f.is_even(), g);
248
249
1.43k
   int32_t delta = 1;
250
251
1.43k
   const size_t loop_cnt = safegcd_loop_bound(f.bits(), g.bits());
252
253
1.43k
   BigInt newg, t;
254
614k
   for(size_t i = 0; i != loop_cnt; ++i)
255
613k
      {
256
613k
      sub_abs(newg, f, g);
257
258
613k
      const bool need_swap = (g.is_odd() && delta > 0);
259
260
      // if(need_swap) { delta *= -1 } else { delta *= 1 }
261
613k
      delta *= CT::Mask<uint8_t>::expand(need_swap).if_not_set_return(2) - 1;
262
613k
      f.ct_cond_swap(need_swap, g);
263
613k
      g.ct_cond_swap(need_swap, newg);
264
265
613k
      delta += 1;
266
267
613k
      g.ct_cond_add(g.is_odd(), f);
268
613k
      g >>= 1;
269
613k
      }
270
271
1.43k
   f <<= common2s;
272
273
1.43k
   f.const_time_unpoison();
274
1.43k
   g.const_time_unpoison();
275
276
1.43k
   BOTAN_ASSERT_NOMSG(g.is_zero());
277
278
1.43k
   return f;
279
1.44k
   }
280
281
/*
282
* Calculate the LCM
283
*/
284
BigInt lcm(const BigInt& a, const BigInt& b)
285
0
   {
286
0
   if(a == b)
287
0
      return a;
288
289
0
   auto ab = a * b;
290
0
   ab.set_sign(BigInt::Positive); // ignore the signs of a & b
291
0
   const auto g = gcd(a, b);
292
0
   return ct_divide(ab, g);
293
0
   }
294
295
/*
296
* Modular Exponentiation
297
*/
298
BigInt power_mod(const BigInt& base, const BigInt& exp, const BigInt& mod)
299
1.55k
   {
300
1.55k
   if(mod.is_negative() || mod == 1)
301
16
      {
302
16
      return BigInt::zero();
303
16
      }
304
305
1.53k
   if(base.is_zero() || mod.is_zero())
306
29
      {
307
29
      if(exp.is_zero())
308
1
         return BigInt::one();
309
28
      return BigInt::zero();
310
29
      }
311
312
1.50k
   Modular_Reducer reduce_mod(mod);
313
314
1.50k
   const size_t exp_bits = exp.bits();
315
316
1.50k
   if(mod.is_odd())
317
759
      {
318
759
      auto monty_params = std::make_shared<Montgomery_Params>(mod, reduce_mod);
319
759
      return monty_exp(monty_params, reduce_mod.reduce(base), exp, exp_bits);
320
759
      }
321
322
   /*
323
   Support for even modulus is just a convenience and not considered
324
   cryptographically important, so this implementation is slow ...
325
   */
326
747
   BigInt accum = BigInt::one();
327
747
   BigInt g = reduce_mod.reduce(base);
328
747
   BigInt t;
329
330
343k
   for(size_t i = 0; i != exp_bits; ++i)
331
342k
      {
332
342k
      t = reduce_mod.multiply(g, accum);
333
342k
      g = reduce_mod.square(g);
334
342k
      accum.ct_cond_assign(exp.get_bit(i), t);
335
342k
      }
336
747
   return accum;
337
1.50k
   }
338
339
340
BigInt is_perfect_square(const BigInt& C)
341
164
   {
342
164
   if(C < 1)
343
0
      throw Invalid_Argument("is_perfect_square requires C >= 1");
344
164
   if(C == 1)
345
0
      return BigInt::one();
346
347
164
   const size_t n = C.bits();
348
164
   const size_t m = (n + 1) / 2;
349
164
   const BigInt B = C + BigInt::power_of_2(m);
350
351
164
   BigInt X = BigInt::power_of_2(m) - 1;
352
164
   BigInt X2 = (X*X);
353
354
164
   for(;;)
355
783
      {
356
783
      X = (X2 + C) / (2*X);
357
783
      X2 = (X*X);
358
359
783
      if(X2 < B)
360
164
         break;
361
783
      }
362
363
164
   if(X2 == C)
364
0
      return X;
365
164
   else
366
164
      return BigInt::zero();
367
164
   }
368
369
/*
370
* Test for primality using Miller-Rabin
371
*/
372
bool is_prime(const BigInt& n,
373
              RandomNumberGenerator& rng,
374
              size_t prob,
375
              bool is_random)
376
0
   {
377
0
   if(n == 2)
378
0
      return true;
379
0
   if(n <= 1 || n.is_even())
380
0
      return false;
381
382
0
   const size_t n_bits = n.bits();
383
384
   // Fast path testing for small numbers (<= 65521)
385
0
   if(n_bits <= 16)
386
0
      {
387
0
      const uint16_t num = static_cast<uint16_t>(n.word_at(0));
388
389
0
      return std::binary_search(PRIMES, PRIMES + PRIME_TABLE_SIZE, num);
390
0
      }
391
392
0
   Modular_Reducer mod_n(n);
393
394
0
   if(rng.is_seeded())
395
0
      {
396
0
      const size_t t = miller_rabin_test_iterations(n_bits, prob, is_random);
397
398
0
      if(is_miller_rabin_probable_prime(n, mod_n, rng, t) == false)
399
0
         return false;
400
401
0
      if(is_random)
402
0
         return true;
403
0
      else
404
0
         return is_lucas_probable_prime(n, mod_n);
405
0
      }
406
0
   else
407
0
      {
408
0
      return is_bailie_psw_probable_prime(n, mod_n);
409
0
      }
410
0
   }
411
412
}