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

randombit / botan / 25650639339

10 May 2026 07:03PM UTC coverage: 89.326% (-0.002%) from 89.328%
25650639339

push

github

web-flow
Merge pull request #5592 from randombit/jack/bn-hardening

Various BigInt/mp related hardenings and bug fixes

107853 of 120741 relevant lines covered (89.33%)

11294230.95 hits per line

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

88.21
/src/lib/math/bigint/bigint.cpp
1
/*
2
* BigInt Base
3
* (C) 1999-2011,2012,2014,2019 Jack Lloyd
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include <botan/bigint.h>
9

10
#include <botan/exceptn.h>
11
#include <botan/internal/bit_ops.h>
12
#include <botan/internal/ct_utils.h>
13
#include <botan/internal/loadstor.h>
14
#include <botan/internal/mem_utils.h>
15
#include <botan/internal/mp_core.h>
16
#include <botan/internal/rounding.h>
17

18
namespace Botan {
19

20
BigInt::BigInt(uint64_t n) {
364,442✔
21
   if constexpr(sizeof(word) == 8) {
364,442✔
22
      m_data.set_word_at(0, static_cast<word>(n));
364,442✔
23
   } else {
24
      m_data.set_word_at(1, static_cast<word>(n >> 32));
25
      m_data.set_word_at(0, static_cast<word>(n));
26
   }
27
}
364,442✔
28

29
//static
30
BigInt BigInt::from_u64(uint64_t n) {
185,495✔
31
   return BigInt(n);
185,495✔
32
}
33

34
//static
35
BigInt BigInt::from_word(word n) {
476,546✔
36
   BigInt bn;
476,546✔
37
   bn.set_word_at(0, n);
476,546✔
38
   return bn;
476,546✔
39
}
×
40

41
//static
42
BigInt BigInt::from_s32(int32_t n) {
70,888✔
43
   if(n >= 0) {
70,888✔
44
      return BigInt::from_u64(static_cast<uint64_t>(n));
70,752✔
45
   } else {
46
      return -BigInt::from_u64(static_cast<uint64_t>(-static_cast<int64_t>(n)));
136✔
47
   }
48
}
49

50
//static
51
BigInt BigInt::with_capacity(size_t size) {
8,617,790✔
52
   BigInt bn;
8,617,790✔
53
   bn.grow_to(size);
8,617,790✔
54
   return bn;
8,617,790✔
55
}
×
56

57
BigInt BigInt::from_string(std::string_view str) {
43,920✔
58
   size_t prefix_bytes = 0;
43,920✔
59
   bool negative = false;
43,920✔
60
   size_t radix = 10;
43,920✔
61

62
   if(!str.empty() && str[0] == '-') {
43,920✔
63
      prefix_bytes += 1;
64
      negative = true;
65
   }
66

67
   if(str.length() > prefix_bytes + 2 && str[prefix_bytes] == '0' && str[prefix_bytes + 1] == 'x') {
43,920✔
68
      prefix_bytes += 2;
69
      radix = 16;
70
   }
71

72
   BigInt r = BigInt::from_radix_digits(str.substr(prefix_bytes), radix);
43,920✔
73

74
   if(negative) {
43,920✔
75
      r.set_sign(Negative);
928✔
76
   } else {
77
      r.set_sign(Positive);
43,456✔
78
   }
79

80
   return r;
43,920✔
81
}
×
82

83
BigInt BigInt::from_bytes(std::span<const uint8_t> input) {
150,027✔
84
   BigInt r;
150,027✔
85
   r.assign_from_bytes(input);
150,027✔
86
   return r;
150,027✔
87
}
×
88

89
/*
90
* Construct a BigInt from an encoded BigInt
91
*/
92
BigInt::BigInt(const uint8_t input[], size_t length, Base base) {
×
93
   *this = decode(input, length, base);
×
94
}
×
95

96
//static
97
BigInt BigInt::from_bytes_with_max_bits(const uint8_t input[], size_t length, size_t max_bits) {
14,791✔
98
   const size_t input_bits = 8 * length;
14,791✔
99

100
   auto bn = BigInt::from_bytes(std::span{input, length});
14,791✔
101

102
   if(input_bits > max_bits) {
14,791✔
103
      const size_t bits_to_shift = input_bits - max_bits;
8,052✔
104

105
      bn >>= bits_to_shift;
8,052✔
106
   }
107

108
   return bn;
14,791✔
109
}
×
110

111
/*
112
* Construct a BigInt from an encoded BigInt
113
*/
114
BigInt::BigInt(RandomNumberGenerator& rng, size_t bits, bool set_high_bit) {
97,557✔
115
   randomize(rng, bits, set_high_bit);
97,557✔
116
}
97,557✔
117

118
uint8_t BigInt::byte_at(size_t n) const {
339,682✔
119
   return get_byte_var(sizeof(word) - (n % sizeof(word)) - 1, word_at(n / sizeof(word)));
339,682✔
120
}
121

122
int32_t BigInt::cmp_word(word other) const {
3,250,463✔
123
   if(signum() < 0) {
3,250,463✔
124
      return -1;  // other is positive ...
125
   }
126

127
   const size_t sw = this->sig_words();
3,187,176✔
128
   if(sw > 1) {
3,187,176✔
129
      return 1;  // must be larger since other is just one word ...
130
   }
131

132
   return bigint_cmp(this->_data(), sw, &other, 1);
2,422,665✔
133
}
134

135
/*
136
* Comparison Function
137
*/
138
int32_t BigInt::cmp(const BigInt& other, bool check_signs) const {
1,081,298✔
139
   if(check_signs) {
1,081,298✔
140
      if(other.signum() >= 0 && this->signum() < 0) {
1,081,171✔
141
         return -1;
142
      }
143

144
      if(other.signum() < 0 && this->signum() >= 0) {
1,081,099✔
145
         return 1;
146
      }
147

148
      if(other.signum() < 0 && this->signum() < 0) {
1,081,037✔
149
         return (-bigint_cmp(this->_data(), this->size(), other._data(), other.size()));
72✔
150
      }
151
   }
152

153
   return bigint_cmp(this->_data(), this->size(), other._data(), other.size());
1,081,092✔
154
}
155

156
bool BigInt::is_equal(const BigInt& other) const {
602,863✔
157
   if(this->sign() != other.sign()) {
602,863✔
158
      return false;
159
   }
160

161
   return bigint_ct_is_eq(this->_data(), this->size(), other._data(), other.size()).as_bool();
602,797✔
162
}
163

164
bool BigInt::is_less_than(const BigInt& other) const {
1,700,744✔
165
   if(this->signum() < 0 && other.signum() >= 0) {
1,700,744✔
166
      return true;
167
   }
168

169
   if(this->signum() >= 0 && other.signum() < 0) {
1,700,677✔
170
      return false;
171
   }
172

173
   if(other.signum() < 0 && this->signum() < 0) {
1,700,612✔
174
      return bigint_ct_is_lt(other._data(), other.size(), this->_data(), this->size()).as_bool();
71✔
175
   }
176

177
   return bigint_ct_is_lt(this->_data(), this->size(), other._data(), other.size()).as_bool();
1,700,541✔
178
}
179

180
void BigInt::encode_words(word out[], size_t size) const {
151,458✔
181
   const size_t words = sig_words();
151,458✔
182

183
   if(words > size) {
151,458✔
184
      throw Encoding_Error("BigInt::encode_words value too large to encode");
×
185
   }
186

187
   clear_mem(out, size);
151,458✔
188
   copy_mem(out, _data(), words);
151,458✔
189
}
151,458✔
190

191
void BigInt::Data::set_to_zero() {
887,322✔
192
   m_reg.resize(m_reg.capacity());
887,322✔
193
   clear_mem(m_reg.data(), m_reg.size());
887,322✔
194
   m_sig_words = 0;
887,322✔
195
}
887,322✔
196

197
void BigInt::Data::mask_bits(size_t n) {
44,465✔
198
   if(n == 0) {
44,465✔
199
      return set_to_zero();
×
200
   }
201

202
   const size_t top_word = n / WordInfo<word>::bits;
44,465✔
203

204
   if(top_word < size()) {
44,465✔
205
      const word mask = (static_cast<word>(1) << (n % WordInfo<word>::bits)) - 1;
42,415✔
206
      const size_t len = size() - (top_word + 1);
42,415✔
207
      if(len > 0) {
42,415✔
208
         clear_mem(&m_reg[top_word + 1], len);
42,415✔
209
      }
210
      m_reg[top_word] &= mask;
42,415✔
211
      invalidate_sig_words();
42,415✔
212
   }
213
}
214

215
size_t BigInt::Data::calc_sig_words() const {
75,296,216✔
216
   const size_t sz = m_reg.size();
75,296,216✔
217
   size_t sig = sz;
75,296,216✔
218

219
   word sub = 1;
75,296,216✔
220

221
   for(size_t i = 0; i != sz; ++i) {
1,374,355,467✔
222
      const word w = m_reg[sz - i - 1];
1,299,059,251✔
223
      sub &= ct_is_zero(w);
1,299,059,251✔
224
      sig -= sub;
1,299,059,251✔
225
   }
226

227
   /*
228
   * This depends on the data so is poisoned, but unpoison it here as
229
   * later conditionals are made on the size.
230
   */
231
   CT::unpoison(sig);
75,296,216✔
232

233
   return sig;
75,296,216✔
234
}
235

236
/*
237
* Return bits {offset...offset+length}
238
*/
239
uint32_t BigInt::get_substring(size_t offset, size_t length) const {
14,816,992✔
240
   if(length == 0 || length > 32) {
14,816,992✔
241
      throw Invalid_Argument("BigInt::get_substring invalid substring length");
×
242
   }
243

244
   const uint32_t mask = 0xFFFFFFFF >> (32 - length);
14,816,992✔
245

246
   const size_t word_offset = offset / WordInfo<word>::bits;
14,816,992✔
247
   const size_t wshift = (offset % WordInfo<word>::bits);
14,816,992✔
248

249
   /*
250
   * The substring is contained within one or at most two words. The
251
   * offset and length are not secret, so we can perform conditional
252
   * operations on those values.
253
   */
254
   const word w0 = word_at(word_offset);
14,816,992✔
255

256
   if(wshift == 0 || (offset + length) / WordInfo<word>::bits == word_offset) {
14,816,992✔
257
      return static_cast<uint32_t>(w0 >> wshift) & mask;
14,124,607✔
258
   } else {
259
      const word w1 = word_at(word_offset + 1);
692,385✔
260
      return static_cast<uint32_t>((w0 >> wshift) | (w1 << (WordInfo<word>::bits - wshift))) & mask;
692,385✔
261
   }
262
}
263

264
/*
265
* Convert this number to a uint32_t, if possible
266
*/
267
uint32_t BigInt::to_u32bit() const {
34,950✔
268
   if(signum() < 0) {
34,950✔
269
      throw Encoding_Error("BigInt::to_u32bit: Number is negative");
×
270
   }
271
   if(bits() > 32) {
34,950✔
272
      throw Encoding_Error("BigInt::to_u32bit: Number is too big to convert");
15✔
273
   }
274

275
   uint32_t out = 0;
276
   for(size_t i = 0; i != 4; ++i) {
174,675✔
277
      out = (out << 8) | byte_at(3 - i);
139,740✔
278
   }
279
   return out;
34,935✔
280
}
281

282
/*
283
* Clear bit number n
284
*/
285
void BigInt::clear_bit(size_t n) {
69✔
286
   const size_t which = n / WordInfo<word>::bits;
69✔
287

288
   if(which < size()) {
69✔
289
      const word mask = ~(static_cast<word>(1) << (n % WordInfo<word>::bits));
69✔
290
      m_data.set_word_at(which, word_at(which) & mask);
69✔
291
   }
292
}
69✔
293

294
size_t BigInt::bytes() const {
365,695✔
295
   return round_up(bits(), 8) / 8;
365,695✔
296
}
297

298
size_t BigInt::top_bits_free() const {
2,258,253✔
299
   const size_t words = sig_words();
2,258,253✔
300

301
   const word top_word = word_at(words - 1);
2,258,253✔
302
   const size_t bits_used = high_bit(CT::value_barrier(top_word));
2,258,253✔
303
   CT::unpoison(bits_used);
2,258,253✔
304
   return WordInfo<word>::bits - bits_used;
2,258,253✔
305
}
306

307
size_t BigInt::bits() const {
1,764,704✔
308
   const size_t words = sig_words();
1,764,704✔
309

310
   if(words == 0) {
1,764,704✔
311
      return 0;
312
   }
313

314
   const size_t full_words = (words - 1) * WordInfo<word>::bits;
1,747,733✔
315
   const size_t top_bits = WordInfo<word>::bits - top_bits_free();
1,747,733✔
316

317
   return full_words + top_bits;
1,747,733✔
318
}
319

320
/*
321
* Return the negation of this number
322
*/
323
BigInt BigInt::operator-() const {
147✔
324
   BigInt x = (*this);
147✔
325
   x.flip_sign();
147✔
326
   return x;
147✔
327
}
×
328

329
size_t BigInt::reduce_below(const BigInt& p, secure_vector<word>& ws) {
7,485,608✔
330
   if(p.signum() < 0 || this->signum() < 0) {
7,485,608✔
331
      throw Invalid_Argument("BigInt::reduce_below both values must be positive");
×
332
   }
333

334
   const size_t p_words = p.sig_words();
7,485,608✔
335

336
   if(size() < p_words + 1) {
7,485,608✔
337
      grow_to(p_words + 1);
39,158✔
338
   }
339

340
   if(ws.size() < p_words + 1) {
7,485,608✔
341
      ws.resize(p_words + 1);
510,520✔
342
   }
343

344
   clear_mem(ws.data(), ws.size());
7,485,608✔
345

346
   size_t reductions = 0;
7,485,608✔
347

348
   for(;;) {
11,369,867✔
349
      const word borrow = bigint_sub3(ws.data(), _data(), p_words + 1, p._data(), p_words);
18,855,475✔
350
      if(borrow > 0) {
18,855,475✔
351
         break;
352
      }
353

354
      ++reductions;
11,369,867✔
355
      swap_reg(ws);
11,369,867✔
356
   }
357

358
   return reductions;
7,485,608✔
359
}
360

361
void BigInt::ct_reduce_below(const BigInt& mod, secure_vector<word>& ws, size_t bound) {
×
362
   if(mod.signum() < 0 || this->signum() < 0) {
×
363
      throw Invalid_Argument("BigInt::ct_reduce_below both values must be positive");
×
364
   }
365

366
   const size_t mod_words = mod.sig_words();
×
367

368
   grow_to(mod_words);
×
369

370
   const size_t sz = size();
×
371

372
   ws.resize(sz);
×
373

374
   clear_mem(ws.data(), sz);
×
375

376
   for(size_t i = 0; i != bound; ++i) {
×
377
      const word borrow = bigint_sub3(ws.data(), _data(), sz, mod._data(), mod_words);
×
378

379
      CT::Mask<word>::is_zero(borrow).select_n(mutable_data(), ws.data(), _data(), sz);
×
380
   }
381
}
×
382

383
/*
384
* Return the absolute value of this number
385
*/
386
BigInt BigInt::abs() const {
808✔
387
   BigInt x = (*this);
808✔
388
   x.set_sign(Positive);
808✔
389
   return x;
808✔
390
}
391

392
/*
393
* Encode this number into bytes
394
*/
395
void BigInt::serialize_to(std::span<uint8_t> output) const {
216,337✔
396
   BOTAN_ARG_CHECK(this->bytes() <= output.size(), "Insufficient output space");
216,337✔
397

398
   this->binary_encode(output.data(), output.size());
216,336✔
399
}
216,336✔
400

401
/*
402
* Encode this number into bytes
403
*/
404
void BigInt::binary_encode(uint8_t output[], size_t len) const {
216,341✔
405
   const size_t full_words = len / sizeof(word);
216,341✔
406
   const size_t extra_bytes = len % sizeof(word);
216,341✔
407

408
   for(size_t i = 0; i != full_words; ++i) {
1,975,615✔
409
      const word w = word_at(i);
1,759,274✔
410
      store_be(w, output + (len - (i + 1) * sizeof(word)));
1,759,274✔
411
   }
412

413
   if(extra_bytes > 0) {
216,341✔
414
      const word w = word_at(full_words);
126,395✔
415

416
      for(size_t i = 0; i != extra_bytes; ++i) {
578,831✔
417
         output[extra_bytes - i - 1] = get_byte_var(sizeof(word) - i - 1, w);
452,436✔
418
      }
419
   }
420
}
216,341✔
421

422
/*
423
* Set this number to the value in buf
424
*/
425
void BigInt::assign_from_bytes(std::span<const uint8_t> bytes) {
886,285✔
426
   clear();
886,285✔
427

428
   const size_t length = bytes.size();
886,285✔
429
   const size_t full_words = length / sizeof(word);
886,285✔
430
   const size_t extra_bytes = length % sizeof(word);
886,285✔
431

432
   secure_vector<word> reg((round_up(full_words + (extra_bytes > 0 ? 1 : 0), 8)));
1,119,049✔
433

434
   for(size_t i = 0; i != full_words; ++i) {
8,805,917✔
435
      reg[i] = load_be<word>(bytes.last<sizeof(word)>());
7,919,632✔
436
      bytes = bytes.first(bytes.size() - sizeof(word));
7,919,632✔
437
   }
438

439
   if(!bytes.empty()) {
886,285✔
440
      BOTAN_ASSERT_NOMSG(extra_bytes == bytes.size());
653,521✔
441
      std::array<uint8_t, sizeof(word)> last_partial_word = {0};
653,521✔
442
      copy_mem(std::span{last_partial_word}.last(extra_bytes), bytes);
653,521✔
443
      reg[full_words] = load_be<word>(last_partial_word);
653,521✔
444
   }
445

446
   m_data.swap(reg);
886,285✔
447
}
886,285✔
448

449
void BigInt::ct_cond_add(bool predicate, const BigInt& value) {
2,433,747✔
450
   if(this->signum() < 0 || value.signum() < 0) {
2,433,747✔
451
      throw Invalid_Argument("BigInt::ct_cond_add requires both values to be positive");
×
452
   }
453
   const size_t v_words = value.sig_words();
2,433,747✔
454

455
   // The carry can propagate through every existing word of *this, so the
456
   // output needs one slot above whichever input is wider.
457
   this->grow_to(std::max(this->size(), v_words) + 1);
2,433,747✔
458

459
   const auto mask = CT::Mask<word>::expand(static_cast<word>(predicate)).value();
2,433,747✔
460

461
   word carry = 0;
2,433,747✔
462

463
   word* x = this->mutable_data();
2,433,747✔
464
   const word* y = value._data();
2,433,747✔
465

466
   for(size_t i = 0; i != v_words; ++i) {
11,735,225✔
467
      x[i] = word_add(x[i], y[i] & mask, &carry);
9,301,478✔
468
   }
469

470
   for(size_t i = v_words; i != size(); ++i) {
28,415,621✔
471
      x[i] = word_add(x[i], static_cast<word>(0), &carry);
25,981,874✔
472
   }
473
}
2,433,747✔
474

475
void BigInt::ct_shift_left(size_t shift) {
30,733✔
476
   BOTAN_ASSERT_NOMSG(size() > 0);
30,733✔
477

478
   constexpr size_t bits_in_word = sizeof(word) * 8;
30,733✔
479
   const size_t word_shift = shift >> ceil_log2(bits_in_word);             // shift / bits_in_word
30,733✔
480
   const size_t bit_shift = shift & ((1 << ceil_log2(bits_in_word)) - 1);  // shift % bits_in_word
30,733✔
481
   const size_t iterations = std::max(size(), bits_in_word) - 1;           // uint64_t i; i << 64 is undefined behaviour
30,733✔
482

483
   const size_t n = size();
30,733✔
484

485
   // Workspace 1 word larger to catch overflow from bigint_shl2
486
   secure_vector<word> ws(n + 1);
30,733✔
487

488
   // In every iteration, shift one bit and one word to the left and use the
489
   // shift results only when they are within the shift range.
490
   for(size_t i = 0; i < iterations; ++i) {
3,834,688✔
491
      // Shift left by 1 bit, dropping overflow
492
      bigint_shl2(ws.data(), n + 1, _data(), n, 1);
3,803,955✔
493
      ws[n] = 0;
3,803,955✔
494

495
      // Conditionally assign the bit-shift result
496
      const auto bmask = CT::Mask<word>::expand_bool(i < bit_shift);
3,803,955✔
497
      for(size_t j = 0; j != n; ++j) {
1,124,152,347✔
498
         m_data.set_word_at(j, bmask.select(ws[j], word_at(j)));
2,147,483,647✔
499
      }
500

501
      // Shift left by 1 word, dropping the most significant word
502
      bigint_shl2(ws.data(), n + 1, _data(), n - 1 /* ignore msw */, WordInfo<word>::bits);
3,803,955✔
503
      ws[0] = 0;
3,803,955✔
504

505
      // Conditionally assign the word-shift result
506
      const auto wmask = CT::Mask<word>::expand_bool(i < word_shift);
3,803,955✔
507
      for(size_t j = 0; j != n; ++j) {
1,124,152,347✔
508
         m_data.set_word_at(j, wmask.select(ws[j], word_at(j)));
2,147,483,647✔
509
      }
510
   }
511
}
30,733✔
512

513
void BigInt::ct_cond_swap(bool predicate, BigInt& other) {
×
514
   const size_t max_words = std::max(size(), other.size());
×
515
   grow_to(max_words);
×
516
   other.grow_to(max_words);
×
517

518
   bigint_cnd_swap(static_cast<word>(predicate), this->mutable_data(), other.mutable_data(), max_words);
×
519
}
×
520

521
void BigInt::cond_flip_sign(bool predicate) {
24,927,654✔
522
   // This code is assuming Negative == 0, Positive == 1
523

524
   const auto mask = CT::Mask<uint8_t>::expand_bool(predicate);
24,927,654✔
525

526
   const uint8_t current_sign = static_cast<uint8_t>(sign());
24,927,654✔
527

528
   const uint8_t new_sign = mask.select(current_sign ^ 1, current_sign);
24,927,654✔
529

530
   set_sign(static_cast<Sign>(new_sign));
24,927,654✔
531
}
24,927,654✔
532

533
void BigInt::ct_cond_assign(bool predicate, const BigInt& other) {
24,513,973✔
534
   const size_t t_words = size();
24,513,973✔
535
   const size_t o_words = other.size();
24,513,973✔
536

537
   if(t_words < o_words) {
24,513,973✔
538
      grow_to(o_words);
1,622,473✔
539
   }
540

541
   const size_t r_words = std::max(t_words, o_words);
24,513,973✔
542

543
   const auto mask = CT::Mask<word>::expand_bool(predicate);
24,513,973✔
544

545
   for(size_t i = 0; i != r_words; ++i) {
351,633,049✔
546
      const word o_word = other.word_at(i);
327,119,076✔
547
      const word t_word = this->word_at(i);
327,119,076✔
548
      this->set_word_at(i, mask.select(o_word, t_word));
327,119,076✔
549
   }
550

551
   const auto same_sign = CT::Mask<word>::is_equal(sign(), other.sign()).as_choice();
24,513,973✔
552
   cond_flip_sign((mask.as_choice() && !same_sign).as_bool());
24,513,973✔
553
}
24,513,973✔
554

555
void BigInt::_const_time_poison() const {
57,532✔
556
   CT::poison(m_data.const_data(), m_data.size());
57,532✔
557
}
57,532✔
558

559
void BigInt::_const_time_unpoison() const {
24,827,240✔
560
   CT::unpoison(m_data.const_data(), m_data.size());
24,827,240✔
561
}
24,827,240✔
562

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