• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 16055899095

03 Jul 2025 04:34PM UTC coverage: 90.571% (-0.003%) from 90.574%
16055899095

push

github

web-flow
Merge pull request #4931 from randombit/jack/moar-tidy

Address various warnings from clang-tidy

99050 of 109362 relevant lines covered (90.57%)

12478386.65 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.13
/src/lib/math/numbertheory/numthry.cpp
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

11
#include <botan/rng.h>
12
#include <botan/internal/barrett.h>
13
#include <botan/internal/ct_utils.h>
14
#include <botan/internal/divide.h>
15
#include <botan/internal/monty.h>
16
#include <botan/internal/monty_exp.h>
17
#include <botan/internal/mp_core.h>
18
#include <botan/internal/primality.h>
19
#include <algorithm>
20

21
namespace Botan {
22

23
/*
24
* Tonelli-Shanks algorithm
25
*/
26
BigInt sqrt_modulo_prime(const BigInt& a, const BigInt& p) {
1,484✔
27
   BOTAN_ARG_CHECK(p > 1, "invalid prime");
1,484✔
28
   BOTAN_ARG_CHECK(a < p, "value to solve for must be less than p");
1,484✔
29
   BOTAN_ARG_CHECK(a >= 0, "value to solve for must not be negative");
1,483✔
30

31
   // some very easy cases
32
   if(p == 2 || a <= 1) {
2,964✔
33
      return a;
3✔
34
   }
35

36
   BOTAN_ARG_CHECK(p.is_odd(), "invalid prime");
2,960✔
37

38
   if(jacobi(a, p) != 1) {  // not a quadratic residue
1,480✔
39
      return BigInt::from_s32(-1);
137✔
40
   }
41

42
   auto mod_p = Barrett_Reduction::for_public_modulus(p);
1,343✔
43
   auto monty_p = std::make_shared<Montgomery_Params>(p, mod_p);
1,343✔
44

45
   // If p == 3 (mod 4) there is a simple solution
46
   if(p % 4 == 3) {
1,343✔
47
      return monty_exp_vartime(monty_p, a, ((p + 1) >> 2)).value();
2,952✔
48
   }
49

50
   // Otherwise we have to use Shanks-Tonelli
51
   size_t s = low_zero_bits(p - 1);
359✔
52
   BigInt q = p >> s;
359✔
53

54
   q -= 1;
359✔
55
   q >>= 1;
359✔
56

57
   BigInt r = monty_exp_vartime(monty_p, a, q).value();
359✔
58
   BigInt n = mod_p.multiply(a, mod_p.square(r));
359✔
59
   r = mod_p.multiply(r, a);
359✔
60

61
   if(n == 1) {
359✔
62
      return r;
166✔
63
   }
64

65
   // find random quadratic nonresidue z
66
   word z = 2;
67
   for(;;) {
509✔
68
      if(jacobi(BigInt::from_word(z), p) == -1) {  // found one
509✔
69
         break;
70
      }
71

72
      z += 1;  // try next z
317✔
73

74
      /*
75
      * The expected number of tests to find a non-residue modulo a
76
      * prime is 2. If we have not found one after 256 then almost
77
      * certainly we have been given a non-prime p.
78
      */
79
      if(z >= 256) {
317✔
80
         return BigInt::from_s32(-1);
1✔
81
      }
82
   }
83

84
   BigInt c = monty_exp_vartime(monty_p, BigInt::from_word(z), (q << 1) + 1).value();
768✔
85

86
   while(n > 1) {
616✔
87
      q = n;
430✔
88

89
      size_t i = 0;
430✔
90
      while(q != 1) {
12,558✔
91
         q = mod_p.square(q);
12,134✔
92
         ++i;
12,134✔
93

94
         if(i >= s) {
12,134✔
95
            return BigInt::from_s32(-1);
6✔
96
         }
97
      }
98

99
      BOTAN_ASSERT_NOMSG(s >= (i + 1));  // No underflow!
424✔
100
      c = monty_exp_vartime(monty_p, c, BigInt::power_of_2(s - i - 1)).value();
1,272✔
101
      r = mod_p.multiply(r, c);
424✔
102
      c = mod_p.square(c);
424✔
103
      n = mod_p.multiply(n, c);
424✔
104

105
      // s decreases as the algorithm proceeds
106
      BOTAN_ASSERT_NOMSG(s >= i);
424✔
107
      s = i;
108
   }
109

110
   return r;
186✔
111
}
3,045✔
112

113
/*
114
* Calculate the Jacobi symbol
115
*/
116
int32_t jacobi(const BigInt& a, const BigInt& n) {
101,670✔
117
   if(n.is_even() || n < 2) {
305,010✔
118
      throw Invalid_Argument("jacobi: second argument must be odd and > 1");
×
119
   }
120

121
   BigInt x = a % n;
101,670✔
122
   BigInt y = n;
101,670✔
123
   int32_t J = 1;
101,670✔
124

125
   while(y > 1) {
412,593✔
126
      x %= y;
327,570✔
127
      if(x > y / 2) {
655,140✔
128
         x = y - x;
128,325✔
129
         if(y % 4 == 3) {
128,325✔
130
            J = -J;
57,480✔
131
         }
132
      }
133
      if(x.is_zero()) {
455,895✔
134
         return 0;
135
      }
136

137
      size_t shifts = low_zero_bits(x);
310,923✔
138
      x >>= shifts;
310,923✔
139
      if(shifts % 2 == 1) {
310,923✔
140
         word y_mod_8 = y % 8;
70,938✔
141
         if(y_mod_8 == 3 || y_mod_8 == 5) {
70,938✔
142
            J = -J;
43,372✔
143
         }
144
      }
145

146
      if(x % 4 == 3 && y % 4 == 3) {
310,923✔
147
         J = -J;
51,970✔
148
      }
149
      std::swap(x, y);
310,923✔
150
   }
151
   return J;
152
}
101,670✔
153

154
/*
155
* Square a BigInt
156
*/
157
BigInt square(const BigInt& x) {
1,021✔
158
   BigInt z = x;
1,021✔
159
   secure_vector<word> ws;
1,021✔
160
   z.square(ws);
1,021✔
161
   return z;
1,021✔
162
}
1,021✔
163

164
/*
165
* Return the number of 0 bits at the end of n
166
*/
167
size_t low_zero_bits(const BigInt& n) {
546,265✔
168
   size_t low_zero = 0;
546,265✔
169

170
   auto seen_nonempty_word = CT::Mask<word>::cleared();
546,265✔
171

172
   for(size_t i = 0; i != n.size(); ++i) {
5,928,674✔
173
      const word x = n.word_at(i);
5,382,409✔
174

175
      // ctz(0) will return sizeof(word)
176
      const size_t tz_x = ctz(x);
5,382,409✔
177

178
      // if x > 0 we want to count tz_x in total but not any
179
      // further words, so set the mask after the addition
180
      low_zero += seen_nonempty_word.if_not_set_return(tz_x);
5,382,409✔
181

182
      seen_nonempty_word |= CT::Mask<word>::expand(x);
5,382,409✔
183
   }
184

185
   // if we saw no words with x > 0 then n == 0 and the value we have
186
   // computed is meaningless. Instead return BigInt::zero() in that case.
187
   return static_cast<size_t>(seen_nonempty_word.if_set_return(low_zero));
546,265✔
188
}
189

190
/*
191
* Calculate the GCD in constant time
192
*/
193
BigInt gcd(const BigInt& a, const BigInt& b) {
26,634✔
194
   if(a.is_zero()) {
28,795✔
195
      return abs(b);
3✔
196
   }
197
   if(b.is_zero()) {
27,071✔
198
      return abs(a);
26,634✔
199
   }
200

201
   const size_t sz = std::max(a.sig_words(), b.sig_words());
26,629✔
202
   auto u = BigInt::with_capacity(sz);
26,629✔
203
   auto v = BigInt::with_capacity(sz);
26,629✔
204
   u += a;
26,629✔
205
   v += b;
26,629✔
206

207
   CT::poison_all(u, v);
26,629✔
208

209
   u.set_sign(BigInt::Positive);
26,629✔
210
   v.set_sign(BigInt::Positive);
26,629✔
211

212
   // In the worst case we have two fully populated big ints. After right
213
   // shifting so many times, we'll have reached the result for sure.
214
   const size_t loop_cnt = u.bits() + v.bits();
26,629✔
215

216
   // This temporary is big enough to hold all intermediate results of the
217
   // algorithm. No reallocation will happen during the loop.
218
   // Note however, that `ct_cond_assign()` will invalidate the 'sig_words'
219
   // cache, which _does not_ shrink the capacity of the underlying buffer.
220
   auto tmp = BigInt::with_capacity(sz);
26,629✔
221
   size_t factors_of_two = 0;
222
   for(size_t i = 0; i != loop_cnt; ++i) {
5,721,577✔
223
      auto both_odd = CT::Mask<word>::expand(u.is_odd()) & CT::Mask<word>::expand(v.is_odd());
17,084,844✔
224

225
      // Subtract the smaller from the larger if both are odd
226
      auto u_gt_v = CT::Mask<word>::expand(bigint_cmp(u._data(), u.size(), v._data(), v.size()) > 0);
5,694,948✔
227
      bigint_sub_abs(tmp.mutable_data(), u._data(), sz, v._data(), sz);
5,694,948✔
228
      u.ct_cond_assign((u_gt_v & both_odd).as_bool(), tmp);
5,694,948✔
229
      v.ct_cond_assign((~u_gt_v & both_odd).as_bool(), tmp);
5,694,948✔
230

231
      const auto u_is_even = CT::Mask<word>::expand(u.is_even());
11,389,896✔
232
      const auto v_is_even = CT::Mask<word>::expand(v.is_even());
11,389,896✔
233
      BOTAN_DEBUG_ASSERT((u_is_even | v_is_even).as_bool());
5,694,948✔
234

235
      // When both are even, we're going to eliminate a factor of 2.
236
      // We have to reapply this factor to the final result.
237
      factors_of_two += (u_is_even & v_is_even).if_set_return(1);
5,694,948✔
238

239
      // remove one factor of 2, if u is even
240
      bigint_shr2(tmp.mutable_data(), u._data(), sz, 1);
5,694,948✔
241
      u.ct_cond_assign(u_is_even.as_bool(), tmp);
5,694,948✔
242

243
      // remove one factor of 2, if v is even
244
      bigint_shr2(tmp.mutable_data(), v._data(), sz, 1);
5,694,948✔
245
      v.ct_cond_assign(v_is_even.as_bool(), tmp);
5,694,948✔
246
   }
247

248
   // The GCD (without factors of two) is either in u or v, the other one is
249
   // zero. The non-zero variable _must_ be odd, because all factors of two were
250
   // removed in the loop iterations above.
251
   BOTAN_DEBUG_ASSERT(u.is_zero() || v.is_zero());
26,629✔
252
   BOTAN_DEBUG_ASSERT(u.is_odd() || v.is_odd());
26,629✔
253

254
   // make sure that the GCD (without factors of two) is in u
255
   u.ct_cond_assign(u.is_even() /* .is_zero() would not be constant time */, v);
53,258✔
256

257
   // re-apply the factors of two
258
   u.ct_shift_left(factors_of_two);
26,629✔
259

260
   CT::unpoison_all(u, v);
26,629✔
261

262
   return u;
26,629✔
263
}
26,629✔
264

265
/*
266
* Calculate the LCM
267
*/
268
BigInt lcm(const BigInt& a, const BigInt& b) {
4,632✔
269
   if(a == b) {
4,632✔
270
      return a;
×
271
   }
272

273
   auto ab = a * b;
4,632✔
274
   ab.set_sign(BigInt::Positive);  // ignore the signs of a & b
4,632✔
275
   const auto g = gcd(a, b);
4,632✔
276
   return ct_divide(ab, g);
4,632✔
277
}
4,632✔
278

279
/*
280
* Modular Exponentiation
281
*/
282
BigInt power_mod(const BigInt& base, const BigInt& exp, const BigInt& mod) {
66✔
283
   if(mod.is_negative() || mod == 1) {
132✔
284
      return BigInt::zero();
×
285
   }
286

287
   if(base.is_zero() || mod.is_zero()) {
191✔
288
      if(exp.is_zero()) {
2✔
289
         return BigInt::one();
1✔
290
      }
291
      return BigInt::zero();
×
292
   }
293

294
   auto reduce_mod = Barrett_Reduction::for_secret_modulus(mod);
65✔
295

296
   const size_t exp_bits = exp.bits();
65✔
297

298
   if(mod.is_odd()) {
65✔
299
      auto monty_params = std::make_shared<Montgomery_Params>(mod, reduce_mod);
50✔
300
      return monty_exp(monty_params, ct_modulo(base, mod), exp, exp_bits).value();
150✔
301
   }
50✔
302

303
   /*
304
   Support for even modulus is just a convenience and not considered
305
   cryptographically important, so this implementation is slow ...
306
   */
307
   BigInt accum = BigInt::one();
15✔
308
   BigInt g = ct_modulo(base, mod);
15✔
309
   BigInt t;
15✔
310

311
   for(size_t i = 0; i != exp_bits; ++i) {
3,272✔
312
      t = reduce_mod.multiply(g, accum);
3,257✔
313
      g = reduce_mod.square(g);
3,257✔
314
      accum.ct_cond_assign(exp.get_bit(i), t);
6,514✔
315
   }
316
   return accum;
15✔
317
}
80✔
318

319
BigInt is_perfect_square(const BigInt& C) {
706✔
320
   if(C < 1) {
706✔
321
      throw Invalid_Argument("is_perfect_square requires C >= 1");
×
322
   }
323
   if(C == 1) {
706✔
324
      return BigInt::one();
×
325
   }
326

327
   const size_t n = C.bits();
706✔
328
   const size_t m = (n + 1) / 2;
706✔
329
   const BigInt B = C + BigInt::power_of_2(m);
706✔
330

331
   BigInt X = BigInt::power_of_2(m) - 1;
1,412✔
332
   BigInt X2 = (X * X);
706✔
333

334
   for(;;) {
1,666✔
335
      X = (X2 + C) / (2 * X);
1,666✔
336
      X2 = (X * X);
1,666✔
337

338
      if(X2 < B) {
1,666✔
339
         break;
340
      }
341
   }
342

343
   if(X2 == C) {
706✔
344
      return X;
63✔
345
   } else {
346
      return BigInt::zero();
643✔
347
   }
348
}
706✔
349

350
/*
351
* Test for primality using Miller-Rabin
352
*/
353
bool is_prime(const BigInt& n, RandomNumberGenerator& rng, size_t prob, bool is_random) {
54,773✔
354
   if(n == 2) {
54,773✔
355
      return true;
356
   }
357
   if(n <= 1 || n.is_even()) {
109,540✔
358
      return false;
359
   }
360

361
   const size_t n_bits = n.bits();
54,702✔
362

363
   // Fast path testing for small numbers (<= 65521)
364
   if(n_bits <= 16) {
54,702✔
365
      const uint16_t num = static_cast<uint16_t>(n.word_at(0));
32,802✔
366

367
      return std::binary_search(PRIMES, PRIMES + PRIME_TABLE_SIZE, num);
32,802✔
368
   }
369

370
   auto mod_n = Barrett_Reduction::for_secret_modulus(n);
21,900✔
371

372
   if(rng.is_seeded()) {
21,900✔
373
      const size_t t = miller_rabin_test_iterations(n_bits, prob, is_random);
21,900✔
374

375
      if(is_miller_rabin_probable_prime(n, mod_n, rng, t) == false) {
21,900✔
376
         return false;
377
      }
378

379
      if(is_random) {
3,359✔
380
         return true;
381
      } else {
382
         return is_lucas_probable_prime(n, mod_n);
3,164✔
383
      }
384
   } else {
385
      return is_bailie_psw_probable_prime(n, mod_n);
×
386
   }
387
}
21,900✔
388

389
}  // namespace Botan
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc