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

randombit / botan / 17209789316

25 Aug 2025 01:08PM UTC coverage: 90.698% (+0.02%) from 90.677%
17209789316

Pull #5047

github

web-flow
Merge 3014a1a0c into 0852a2a74
Pull Request #5047: X.509 Path: Option for Non-Self-Signed Trust Anchors

100403 of 110700 relevant lines covered (90.7%)

12158073.92 hits per line

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

96.69
/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,474✔
27
   BOTAN_ARG_CHECK(p > 1, "invalid prime");
1,474✔
28
   BOTAN_ARG_CHECK(a < p, "value to solve for must be less than p");
1,474✔
29
   BOTAN_ARG_CHECK(a >= 0, "value to solve for must not be negative");
1,474✔
30

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

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

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

42
   auto mod_p = Barrett_Reduction::for_public_modulus(p);
1,338✔
43
   const Montgomery_Params monty_p(p, mod_p);
1,338✔
44

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

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

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

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

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

65
   // find random quadratic nonresidue z
66
   word z = 2;
67
   for(;;) {
501✔
68
      if(jacobi(BigInt::from_word(z), p) == -1) {  // found one
501✔
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();
368✔
85

86
   while(n > 1) {
567✔
87
      q = n;
389✔
88

89
      size_t i = 0;
389✔
90
      while(q != 1) {
10,766✔
91
         q = mod_p.square(q);
10,383✔
92
         ++i;
10,383✔
93

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

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

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

110
   return r;
178✔
111
}
3,030✔
112

113
/*
114
* Calculate the Jacobi symbol
115
*
116
* See Algorithm 2.149 in Handbook of Applied Cryptography
117
*/
118
int32_t jacobi(BigInt a, BigInt n) {
101,833✔
119
   BOTAN_ARG_CHECK(n.is_odd() && n >= 3, "Argument n must be an odd integer >= 3");
305,499✔
120

121
   if(a < 0 || a >= n) {
172,487✔
122
      a %= n;
31,451✔
123
   }
124

125
   if(a == 0) {
101,833✔
126
      return 0;
127
   }
128
   if(a == 1) {
101,810✔
129
      return 1;
130
   }
131

132
   int32_t s = 1;
133

134
   for(;;) {
389,966✔
135
      const size_t e = low_zero_bits(a);
389,966✔
136
      a >>= e;
389,966✔
137
      const word n_mod_8 = n.word_at(0) % 8;
389,966✔
138
      const word n_mod_4 = n_mod_8 % 4;
389,966✔
139

140
      if(e % 2 == 1 && (n_mod_8 == 3 || n_mod_8 == 5)) {
389,966✔
141
         s = -s;
66,997✔
142
      }
143

144
      if(n_mod_4 == 3 && a % 4 == 3) {
389,966✔
145
         s = -s;
68,310✔
146
      }
147

148
      /*
149
      * The HAC presentation of the algorithm uses recursion, which is not
150
      * desirable or necessary.
151
      *
152
      * Instead we loop accumulating the product of the various jacobi()
153
      * subcomputations into s, until we reach algorithm termination, which
154
      * occurs in one of two ways.
155
      *
156
      * If a == 1 then the recursion has completed; we can return the value of s.
157
      *
158
      * Otherwise, after swapping and reducing, check for a == 0 [this value is
159
      * called `n1` in HAC's presentation]. This would imply that jacobi(n1,a1)
160
      * would have the value 0, due to Line 1 in HAC 2.149, in which case the
161
      * entire product is zero, and we can immediately return that result.
162
      */
163

164
      if(a == 1) {
389,966✔
165
         return s;
85,184✔
166
      }
167

168
      std::swap(a, n);
304,782✔
169

170
      BOTAN_ASSERT_NOMSG(n.is_odd());
609,564✔
171

172
      a %= n;
304,782✔
173

174
      if(a == 0) {
304,782✔
175
         return 0;
176
      }
177
   }
178
}
179

180
/*
181
* Square a BigInt
182
*/
183
BigInt square(const BigInt& x) {
1,021✔
184
   BigInt z = x;
1,021✔
185
   secure_vector<word> ws;
1,021✔
186
   z.square(ws);
1,021✔
187
   return z;
1,021✔
188
}
1,021✔
189

190
/*
191
* Return the number of 0 bits at the end of n
192
*/
193
size_t low_zero_bits(const BigInt& n) {
628,912✔
194
   size_t low_zero = 0;
628,912✔
195

196
   auto seen_nonempty_word = CT::Mask<word>::cleared();
628,912✔
197

198
   for(size_t i = 0; i != n.size(); ++i) {
6,630,666✔
199
      const word x = n.word_at(i);
6,001,754✔
200

201
      // ctz(0) will return sizeof(word)
202
      const size_t tz_x = ctz(x);
6,001,754✔
203

204
      // if x > 0 we want to count tz_x in total but not any
205
      // further words, so set the mask after the addition
206
      low_zero += seen_nonempty_word.if_not_set_return(tz_x);
6,001,754✔
207

208
      seen_nonempty_word |= CT::Mask<word>::expand(x);
6,001,754✔
209
   }
210

211
   // if we saw no words with x > 0 then n == 0 and the value we have
212
   // computed is meaningless. Instead return BigInt::zero() in that case.
213
   return static_cast<size_t>(seen_nonempty_word.if_set_return(low_zero));
628,912✔
214
}
215

216
/*
217
* Calculate the GCD in constant time
218
*/
219
BigInt gcd(const BigInt& a, const BigInt& b) {
26,639✔
220
   if(a.is_zero()) {
28,800✔
221
      return abs(b);
3✔
222
   }
223
   if(b.is_zero()) {
27,076✔
224
      return abs(a);
26,639✔
225
   }
226

227
   const size_t sz = std::max(a.sig_words(), b.sig_words());
26,634✔
228
   auto u = BigInt::with_capacity(sz);
26,634✔
229
   auto v = BigInt::with_capacity(sz);
26,634✔
230
   u += a;
26,634✔
231
   v += b;
26,634✔
232

233
   CT::poison_all(u, v);
26,634✔
234

235
   u.set_sign(BigInt::Positive);
26,634✔
236
   v.set_sign(BigInt::Positive);
26,634✔
237

238
   // In the worst case we have two fully populated big ints. After right
239
   // shifting so many times, we'll have reached the result for sure.
240
   const size_t loop_cnt = u.bits() + v.bits();
26,634✔
241

242
   // This temporary is big enough to hold all intermediate results of the
243
   // algorithm. No reallocation will happen during the loop.
244
   // Note however, that `ct_cond_assign()` will invalidate the 'sig_words'
245
   // cache, which _does not_ shrink the capacity of the underlying buffer.
246
   auto tmp = BigInt::with_capacity(sz);
26,634✔
247
   secure_vector<word> ws(sz * 2);
26,634✔
248
   size_t factors_of_two = 0;
26,634✔
249
   for(size_t i = 0; i != loop_cnt; ++i) {
5,735,716✔
250
      auto both_odd = CT::Mask<word>::expand_bool(u.is_odd()) & CT::Mask<word>::expand_bool(v.is_odd());
17,127,246✔
251

252
      // Subtract the smaller from the larger if both are odd
253
      auto u_gt_v = CT::Mask<word>::expand_bool(bigint_cmp(u._data(), u.size(), v._data(), v.size()) > 0);
5,709,082✔
254
      bigint_sub_abs(tmp.mutable_data(), u._data(), v._data(), sz, ws.data());
5,709,082✔
255
      u.ct_cond_assign((u_gt_v & both_odd).as_bool(), tmp);
5,709,082✔
256
      v.ct_cond_assign((~u_gt_v & both_odd).as_bool(), tmp);
5,709,082✔
257

258
      const auto u_is_even = CT::Mask<word>::expand_bool(u.is_even());
11,418,164✔
259
      const auto v_is_even = CT::Mask<word>::expand_bool(v.is_even());
11,418,164✔
260
      BOTAN_DEBUG_ASSERT((u_is_even | v_is_even).as_bool());
5,709,082✔
261

262
      // When both are even, we're going to eliminate a factor of 2.
263
      // We have to reapply this factor to the final result.
264
      factors_of_two += (u_is_even & v_is_even).if_set_return(1);
5,709,082✔
265

266
      // remove one factor of 2, if u is even
267
      bigint_shr2(tmp.mutable_data(), u._data(), sz, 1);
5,709,082✔
268
      u.ct_cond_assign(u_is_even.as_bool(), tmp);
5,709,082✔
269

270
      // remove one factor of 2, if v is even
271
      bigint_shr2(tmp.mutable_data(), v._data(), sz, 1);
5,709,082✔
272
      v.ct_cond_assign(v_is_even.as_bool(), tmp);
5,709,082✔
273
   }
274

275
   // The GCD (without factors of two) is either in u or v, the other one is
276
   // zero. The non-zero variable _must_ be odd, because all factors of two were
277
   // removed in the loop iterations above.
278
   BOTAN_DEBUG_ASSERT(u.is_zero() || v.is_zero());
26,634✔
279
   BOTAN_DEBUG_ASSERT(u.is_odd() || v.is_odd());
26,634✔
280

281
   // make sure that the GCD (without factors of two) is in u
282
   u.ct_cond_assign(u.is_even() /* .is_zero() would not be constant time */, v);
53,268✔
283

284
   // re-apply the factors of two
285
   u.ct_shift_left(factors_of_two);
26,634✔
286

287
   CT::unpoison_all(u, v);
26,634✔
288

289
   return u;
26,634✔
290
}
26,634✔
291

292
/*
293
* Calculate the LCM
294
*/
295
BigInt lcm(const BigInt& a, const BigInt& b) {
4,636✔
296
   if(a == b) {
4,636✔
297
      return a;
×
298
   }
299

300
   auto ab = a * b;
4,636✔
301
   ab.set_sign(BigInt::Positive);  // ignore the signs of a & b
4,636✔
302
   const auto g = gcd(a, b);
4,636✔
303
   return ct_divide(ab, g);
4,636✔
304
}
4,636✔
305

306
/*
307
* Modular Exponentiation
308
*/
309
BigInt power_mod(const BigInt& base, const BigInt& exp, const BigInt& mod) {
71✔
310
   if(mod.is_negative() || mod == 1) {
142✔
311
      return BigInt::zero();
×
312
   }
313

314
   if(base.is_zero() || mod.is_zero()) {
206✔
315
      if(exp.is_zero()) {
2✔
316
         return BigInt::one();
1✔
317
      }
318
      return BigInt::zero();
×
319
   }
320

321
   auto reduce_mod = Barrett_Reduction::for_secret_modulus(mod);
70✔
322

323
   const size_t exp_bits = exp.bits();
70✔
324

325
   if(mod.is_odd()) {
70✔
326
      const Montgomery_Params monty_params(mod, reduce_mod);
54✔
327
      return monty_exp(monty_params, ct_modulo(base, mod), exp, exp_bits).value();
54✔
328
   }
54✔
329

330
   /*
331
   Support for even modulus is just a convenience and not considered
332
   cryptographically important, so this implementation is slow ...
333
   */
334
   BigInt accum = BigInt::one();
16✔
335
   BigInt g = ct_modulo(base, mod);
16✔
336
   BigInt t;
16✔
337

338
   for(size_t i = 0; i != exp_bits; ++i) {
3,907✔
339
      t = reduce_mod.multiply(g, accum);
3,891✔
340
      g = reduce_mod.square(g);
3,891✔
341
      accum.ct_cond_assign(exp.get_bit(i), t);
7,782✔
342
   }
343
   return accum;
16✔
344
}
86✔
345

346
BigInt is_perfect_square(const BigInt& C) {
705✔
347
   if(C < 1) {
705✔
348
      throw Invalid_Argument("is_perfect_square requires C >= 1");
×
349
   }
350
   if(C == 1) {
705✔
351
      return BigInt::one();
×
352
   }
353

354
   const size_t n = C.bits();
705✔
355
   const size_t m = (n + 1) / 2;
705✔
356
   const BigInt B = C + BigInt::power_of_2(m);
705✔
357

358
   BigInt X = BigInt::power_of_2(m) - 1;
1,410✔
359
   BigInt X2 = (X * X);
705✔
360

361
   for(;;) {
1,659✔
362
      X = (X2 + C) / (2 * X);
1,659✔
363
      X2 = (X * X);
1,659✔
364

365
      if(X2 < B) {
1,659✔
366
         break;
367
      }
368
   }
369

370
   if(X2 == C) {
705✔
371
      return X;
63✔
372
   } else {
373
      return BigInt::zero();
642✔
374
   }
375
}
705✔
376

377
/*
378
* Test for primality using Miller-Rabin
379
*/
380
bool is_prime(const BigInt& n, RandomNumberGenerator& rng, size_t prob, bool is_random) {
51,766✔
381
   if(n == 2) {
51,766✔
382
      return true;
383
   }
384
   if(n <= 1 || n.is_even()) {
103,526✔
385
      return false;
386
   }
387

388
   const size_t n_bits = n.bits();
51,695✔
389

390
   // Fast path testing for small numbers (<= 65521)
391
   if(n_bits <= 16) {
51,695✔
392
      const uint16_t num = static_cast<uint16_t>(n.word_at(0));
32,802✔
393

394
      return std::binary_search(PRIMES, PRIMES + PRIME_TABLE_SIZE, num);
32,802✔
395
   }
396

397
   auto mod_n = Barrett_Reduction::for_secret_modulus(n);
18,893✔
398

399
   if(rng.is_seeded()) {
18,893✔
400
      const size_t t = miller_rabin_test_iterations(n_bits, prob, is_random);
18,893✔
401

402
      if(!is_miller_rabin_probable_prime(n, mod_n, rng, t)) {
18,893✔
403
         return false;
404
      }
405

406
      if(is_random) {
3,357✔
407
         return true;
408
      } else {
409
         return is_lucas_probable_prime(n, mod_n);
3,162✔
410
      }
411
   } else {
412
      return is_bailie_psw_probable_prime(n, mod_n);
×
413
   }
414
}
18,893✔
415

416
}  // 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