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

randombit / botan / 14644214898

24 Apr 2025 02:29PM UTC coverage: 91.324% (-0.02%) from 91.344%
14644214898

push

github

web-flow
Merge pull request #4835 from randombit/jack/reducer-api-work

New Barrett Reduction implementation

95930 of 105044 relevant lines covered (91.32%)

12800921.49 hits per line

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

91.67
/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/internal/bit_ops.h>
11
#include <botan/internal/ct_utils.h>
12
#include <botan/internal/loadstor.h>
13
#include <botan/internal/mp_core.h>
14
#include <botan/internal/rounding.h>
15

16
namespace Botan {
17

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

27
//static
28
BigInt BigInt::from_u64(uint64_t n) {
110,570✔
29
   return BigInt(n);
110,570✔
30
}
31

32
//static
33
BigInt BigInt::from_word(word n) {
410,473✔
34
   BigInt bn;
410,473✔
35
   bn.set_word_at(0, n);
410,473✔
36
   return bn;
410,473✔
37
}
×
38

39
//static
40
BigInt BigInt::from_s32(int32_t n) {
110✔
41
   if(n >= 0) {
110✔
42
      return BigInt::from_u64(static_cast<uint64_t>(n));
2✔
43
   } else {
44
      return -BigInt::from_u64(static_cast<uint64_t>(-n));
108✔
45
   }
46
}
47

48
//static
49
BigInt BigInt::with_capacity(size_t size) {
12,605,256✔
50
   BigInt bn;
12,605,256✔
51
   bn.grow_to(size);
12,605,256✔
52
   return bn;
12,605,256✔
53
}
×
54

55
/*
56
* Construct a BigInt from a string
57
*/
58
BigInt::BigInt(std::string_view str) {
46,601✔
59
   Base base = Decimal;
46,601✔
60
   size_t markers = 0;
46,601✔
61
   bool negative = false;
46,601✔
62

63
   if(!str.empty() && str[0] == '-') {
46,601✔
64
      markers += 1;
65
      negative = true;
66
   }
67

68
   if(str.length() > markers + 2 && str[markers] == '0' && str[markers + 1] == 'x') {
46,601✔
69
      markers += 2;
70
      base = Hexadecimal;
71
   }
72

73
   *this = decode(cast_char_ptr_to_uint8(str.data()) + markers, str.length() - markers, base);
46,601✔
74

75
   if(negative) {
46,601✔
76
      set_sign(Negative);
890✔
77
   } else {
78
      set_sign(Positive);
46,156✔
79
   }
80
}
46,601✔
81

82
BigInt BigInt::from_string(std::string_view str) {
6✔
83
   return BigInt(str);
6✔
84
}
85

86
BigInt BigInt::from_bytes(std::span<const uint8_t> input) {
110,472✔
87
   BigInt r;
110,472✔
88
   r.assign_from_bytes(input);
110,472✔
89
   return r;
110,472✔
90
}
×
91

92
/*
93
* Construct a BigInt from an encoded BigInt
94
*/
95
BigInt::BigInt(const uint8_t input[], size_t length, Base base) {
10✔
96
   *this = decode(input, length, base);
10✔
97
}
10✔
98

99
//static
100
BigInt BigInt::from_bytes_with_max_bits(const uint8_t input[], size_t length, size_t max_bits) {
6,896✔
101
   const size_t input_bits = 8 * length;
6,896✔
102

103
   auto bn = BigInt::from_bytes(std::span{input, length});
6,896✔
104

105
   if(input_bits > max_bits) {
6,896✔
106
      const size_t bits_to_shift = input_bits - max_bits;
3,722✔
107

108
      bn >>= bits_to_shift;
3,722✔
109
   }
110

111
   return bn;
6,896✔
112
}
×
113

114
/*
115
* Construct a BigInt from an encoded BigInt
116
*/
117
BigInt::BigInt(RandomNumberGenerator& rng, size_t bits, bool set_high_bit) {
96,269✔
118
   randomize(rng, bits, set_high_bit);
96,269✔
119
}
96,269✔
120

121
uint8_t BigInt::byte_at(size_t n) const {
319,818✔
122
   return get_byte_var(sizeof(word) - (n % sizeof(word)) - 1, word_at(n / sizeof(word)));
319,818✔
123
}
124

125
int32_t BigInt::cmp_word(word other) const {
2,635,371✔
126
   if(is_negative()) {
2,635,371✔
127
      return -1;  // other is positive ...
128
   }
129

130
   const size_t sw = this->sig_words();
2,604,226✔
131
   if(sw > 1) {
2,604,226✔
132
      return 1;  // must be larger since other is just one word ...
133
   }
134

135
   return bigint_cmp(this->_data(), sw, &other, 1);
2,000,226✔
136
}
137

138
/*
139
* Comparison Function
140
*/
141
int32_t BigInt::cmp(const BigInt& other, bool check_signs) const {
960,482✔
142
   if(check_signs) {
960,482✔
143
      if(other.is_positive() && this->is_negative()) {
960,355✔
144
         return -1;
145
      }
146

147
      if(other.is_negative() && this->is_positive()) {
960,297✔
148
         return 1;
149
      }
150

151
      if(other.is_negative() && this->is_negative()) {
960,225✔
152
         return (-bigint_cmp(this->_data(), this->size(), other._data(), other.size()));
70✔
153
      }
154
   }
155

156
   return bigint_cmp(this->_data(), this->size(), other._data(), other.size());
960,282✔
157
}
158

159
bool BigInt::is_equal(const BigInt& other) const {
539,193✔
160
   if(this->sign() != other.sign()) {
539,193✔
161
      return false;
162
   }
163

164
   return bigint_ct_is_eq(this->_data(), this->sig_words(), other._data(), other.sig_words()).as_bool();
978,822✔
165
}
166

167
bool BigInt::is_less_than(const BigInt& other) const {
10,453,656✔
168
   if(this->is_negative() && other.is_positive()) {
10,453,656✔
169
      return true;
170
   }
171

172
   if(this->is_positive() && other.is_negative()) {
10,453,591✔
173
      return false;
174
   }
175

176
   if(other.is_negative() && this->is_negative()) {
10,453,528✔
177
      return bigint_ct_is_lt(other._data(), other.sig_words(), this->_data(), this->sig_words()).as_bool();
69✔
178
   }
179

180
   return bigint_ct_is_lt(this->_data(), this->sig_words(), other._data(), other.sig_words()).as_bool();
15,329,230✔
181
}
182

183
void BigInt::encode_words(word out[], size_t size) const {
281,742✔
184
   const size_t words = sig_words();
281,742✔
185

186
   if(words > size) {
281,742✔
187
      throw Encoding_Error("BigInt::encode_words value too large to encode");
×
188
   }
189

190
   clear_mem(out, size);
281,742✔
191
   copy_mem(out, _data(), words);
281,742✔
192
}
281,742✔
193

194
void BigInt::Data::set_to_zero() {
861,338✔
195
   m_reg.resize(m_reg.capacity());
861,338✔
196
   clear_mem(m_reg.data(), m_reg.size());
861,338✔
197
   m_sig_words = 0;
861,338✔
198
}
861,338✔
199

200
void BigInt::Data::mask_bits(size_t n) {
45,280✔
201
   if(n == 0) {
45,280✔
202
      return set_to_zero();
×
203
   }
204

205
   const size_t top_word = n / WordInfo<word>::bits;
45,280✔
206

207
   if(top_word < size()) {
45,280✔
208
      const word mask = (static_cast<word>(1) << (n % WordInfo<word>::bits)) - 1;
43,230✔
209
      const size_t len = size() - (top_word + 1);
43,230✔
210
      if(len > 0) {
43,230✔
211
         clear_mem(&m_reg[top_word + 1], len);
43,230✔
212
      }
213
      m_reg[top_word] &= mask;
43,230✔
214
      invalidate_sig_words();
43,230✔
215
   }
216
}
217

218
size_t BigInt::Data::calc_sig_words() const {
48,479,065✔
219
   const size_t sz = m_reg.size();
48,479,065✔
220
   size_t sig = sz;
48,479,065✔
221

222
   word sub = 1;
48,479,065✔
223

224
   for(size_t i = 0; i != sz; ++i) {
1,306,884,638✔
225
      const word w = m_reg[sz - i - 1];
1,258,405,573✔
226
      sub &= ct_is_zero(w);
1,258,405,573✔
227
      sig -= sub;
1,258,405,573✔
228
   }
229

230
   /*
231
   * This depends on the data so is poisoned, but unpoison it here as
232
   * later conditionals are made on the size.
233
   */
234
   CT::unpoison(sig);
48,479,065✔
235

236
   return sig;
48,479,065✔
237
}
238

239
/*
240
* Return bits {offset...offset+length}
241
*/
242
uint32_t BigInt::get_substring(size_t offset, size_t length) const {
15,130,230✔
243
   if(length == 0 || length > 32) {
15,130,230✔
244
      throw Invalid_Argument("BigInt::get_substring invalid substring length");
×
245
   }
246

247
   const uint32_t mask = 0xFFFFFFFF >> (32 - length);
15,130,230✔
248

249
   const size_t word_offset = offset / WordInfo<word>::bits;
15,130,230✔
250
   const size_t wshift = (offset % WordInfo<word>::bits);
15,130,230✔
251

252
   /*
253
   * The substring is contained within one or at most two words. The
254
   * offset and length are not secret, so we can perform conditional
255
   * operations on those values.
256
   */
257
   const word w0 = word_at(word_offset);
15,130,230✔
258

259
   if(wshift == 0 || (offset + length) / WordInfo<word>::bits == word_offset) {
15,130,230✔
260
      return static_cast<uint32_t>(w0 >> wshift) & mask;
14,339,040✔
261
   } else {
262
      const word w1 = word_at(word_offset + 1);
791,190✔
263
      return static_cast<uint32_t>((w0 >> wshift) | (w1 << (WordInfo<word>::bits - wshift))) & mask;
791,190✔
264
   }
265
}
266

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

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

285
/*
286
* Clear bit number n
287
*/
288
void BigInt::clear_bit(size_t n) {
75✔
289
   const size_t which = n / WordInfo<word>::bits;
75✔
290

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

297
size_t BigInt::bytes() const {
311,199✔
298
   return round_up(bits(), 8) / 8;
311,199✔
299
}
300

301
size_t BigInt::top_bits_free() const {
2,087,941✔
302
   const size_t words = sig_words();
2,087,941✔
303

304
   const word top_word = word_at(words - 1);
2,087,941✔
305
   const size_t bits_used = high_bit(CT::value_barrier(top_word));
2,087,941✔
306
   CT::unpoison(bits_used);
2,087,941✔
307
   return WordInfo<word>::bits - bits_used;
2,087,941✔
308
}
309

310
size_t BigInt::bits() const {
1,803,580✔
311
   const size_t words = sig_words();
1,803,580✔
312

313
   if(words == 0) {
1,803,580✔
314
      return 0;
315
   }
316

317
   const size_t full_words = (words - 1) * WordInfo<word>::bits;
1,785,622✔
318
   const size_t top_bits = WordInfo<word>::bits - top_bits_free();
1,785,622✔
319

320
   return full_words + top_bits;
1,785,622✔
321
}
322

323
/*
324
* Return the negation of this number
325
*/
326
BigInt BigInt::operator-() const {
119✔
327
   BigInt x = (*this);
119✔
328
   x.flip_sign();
119✔
329
   return x;
119✔
330
}
×
331

332
size_t BigInt::reduce_below(const BigInt& p, secure_vector<word>& ws) {
7,218,523✔
333
   if(p.is_negative() || this->is_negative()) {
7,218,523✔
334
      throw Invalid_Argument("BigInt::reduce_below both values must be positive");
×
335
   }
336

337
   const size_t p_words = p.sig_words();
7,218,523✔
338

339
   if(size() < p_words + 1) {
7,218,523✔
340
      grow_to(p_words + 1);
21,213✔
341
   }
342

343
   if(ws.size() < p_words + 1) {
7,218,523✔
344
      ws.resize(p_words + 1);
302,319✔
345
   }
346

347
   clear_mem(ws.data(), ws.size());
7,218,523✔
348

349
   size_t reductions = 0;
7,218,523✔
350

351
   for(;;) {
11,241,523✔
352
      word borrow = bigint_sub3(ws.data(), _data(), p_words + 1, p._data(), p_words);
18,460,046✔
353
      if(borrow) {
18,460,046✔
354
         break;
355
      }
356

357
      ++reductions;
11,241,523✔
358
      swap_reg(ws);
11,241,523✔
359
   }
360

361
   return reductions;
7,218,523✔
362
}
363

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

369
   const size_t mod_words = mod.sig_words();
×
370

371
   grow_to(mod_words);
×
372

373
   const size_t sz = size();
×
374

375
   ws.resize(sz);
×
376

377
   clear_mem(ws.data(), sz);
×
378

379
   for(size_t i = 0; i != bound; ++i) {
×
380
      word borrow = bigint_sub3(ws.data(), _data(), sz, mod._data(), mod_words);
×
381

382
      CT::Mask<word>::is_zero(borrow).select_n(mutable_data(), ws.data(), _data(), sz);
×
383
   }
384
}
×
385

386
/*
387
* Return the absolute value of this number
388
*/
389
BigInt BigInt::abs() const {
1,209✔
390
   BigInt x = (*this);
1,209✔
391
   x.set_sign(Positive);
1,209✔
392
   return x;
1,209✔
393
}
394

395
/*
396
* Encode this number into bytes
397
*/
398
void BigInt::serialize_to(std::span<uint8_t> output) const {
193,906✔
399
   BOTAN_ARG_CHECK(this->bytes() <= output.size(), "Insufficient output space");
193,906✔
400

401
   this->binary_encode(output.data(), output.size());
193,682✔
402
}
193,682✔
403

404
/*
405
* Encode this number into bytes
406
*/
407
void BigInt::binary_encode(uint8_t output[], size_t len) const {
193,687✔
408
   const size_t full_words = len / sizeof(word);
193,687✔
409
   const size_t extra_bytes = len % sizeof(word);
193,687✔
410

411
   for(size_t i = 0; i != full_words; ++i) {
1,800,926✔
412
      const word w = word_at(i);
1,607,239✔
413
      store_be(w, output + (len - (i + 1) * sizeof(word)));
1,607,239✔
414
   }
415

416
   if(extra_bytes > 0) {
193,687✔
417
      const word w = word_at(full_words);
112,612✔
418

419
      for(size_t i = 0; i != extra_bytes; ++i) {
523,114✔
420
         output[extra_bytes - i - 1] = get_byte_var(sizeof(word) - i - 1, w);
410,502✔
421
      }
422
   }
423
}
193,687✔
424

425
/*
426
* Set this number to the value in buf
427
*/
428
void BigInt::assign_from_bytes(std::span<const uint8_t> bytes) {
858,631✔
429
   clear();
858,631✔
430

431
   const size_t length = bytes.size();
858,631✔
432
   const size_t full_words = length / sizeof(word);
858,631✔
433
   const size_t extra_bytes = length % sizeof(word);
858,631✔
434

435
   secure_vector<word> reg((round_up(full_words + (extra_bytes > 0 ? 1 : 0), 8)));
1,088,213✔
436

437
   for(size_t i = 0; i != full_words; ++i) {
8,969,168✔
438
      reg[i] = load_be<word>(bytes.last<sizeof(word)>());
8,110,537✔
439
      bytes = bytes.first(bytes.size() - sizeof(word));
8,110,537✔
440
   }
441

442
   if(!bytes.empty()) {
858,631✔
443
      BOTAN_ASSERT_NOMSG(extra_bytes == bytes.size());
629,049✔
444
      std::array<uint8_t, sizeof(word)> last_partial_word = {0};
629,049✔
445
      copy_mem(std::span{last_partial_word}.last(extra_bytes), bytes);
629,049✔
446
      reg[full_words] = load_be<word>(last_partial_word);
629,049✔
447
   }
448

449
   m_data.swap(reg);
858,631✔
450
}
858,631✔
451

452
void BigInt::ct_cond_add(bool predicate, const BigInt& value) {
3,102,427✔
453
   if(this->is_negative() || value.is_negative()) {
3,102,427✔
454
      throw Invalid_Argument("BigInt::ct_cond_add requires both values to be positive");
×
455
   }
456
   this->grow_to(1 + value.sig_words());
3,102,427✔
457

458
   bigint_cnd_add(static_cast<word>(predicate), this->mutable_data(), this->size(), value._data(), value.sig_words());
3,102,427✔
459
}
3,102,427✔
460

461
void BigInt::ct_shift_left(size_t shift) {
30,725✔
462
   auto shl_bit = [](const BigInt& a, BigInt& result) {
3,834,176✔
463
      BOTAN_DEBUG_ASSERT(a.size() + 1 == result.size());
3,803,451✔
464
      bigint_shl2(result.mutable_data(), a._data(), a.size(), 1);
3,803,451✔
465
      // shl2 may have shifted a bit into the next word, which must be dropped
466
      clear_mem(result.mutable_data() + result.size() - 1, 1);
3,803,451✔
467
   };
3,803,451✔
468

469
   auto shl_word = [](const BigInt& a, BigInt& result) {
3,834,176✔
470
      // the most significant word is not copied, aka. shifted out
471
      bigint_shl2(result.mutable_data(), a._data(), a.size() - 1 /* ignore msw */, WordInfo<word>::bits);
3,803,451✔
472
      // we left-shifted by a full word, the least significant word must be zero'ed
473
      clear_mem(result.mutable_data(), 1);
3,803,451✔
474
   };
3,803,451✔
475

476
   BOTAN_ASSERT_NOMSG(size() > 0);
30,725✔
477

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

483
   // In every iteration, shift one bit and one word to the left and use the
484
   // shift results only when they are within the shift range.
485
   BigInt tmp;
30,725✔
486
   tmp.resize(size() + 1 /* to hold the shifted-out word */);
30,725✔
487
   for(size_t i = 0; i < iterations; ++i) {
3,834,176✔
488
      shl_bit(*this, tmp);
3,803,451✔
489
      ct_cond_assign(i < bit_shift, tmp);
3,803,451✔
490
      shl_word(*this, tmp);
3,803,451✔
491
      ct_cond_assign(i < word_shift, tmp);
3,803,451✔
492
   }
493
}
30,725✔
494

495
void BigInt::ct_cond_swap(bool predicate, BigInt& other) {
11,442,146✔
496
   const size_t max_words = std::max(size(), other.size());
11,442,146✔
497
   grow_to(max_words);
11,442,146✔
498
   other.grow_to(max_words);
11,442,146✔
499

500
   bigint_cnd_swap(static_cast<word>(predicate), this->mutable_data(), other.mutable_data(), max_words);
11,442,146✔
501
}
11,442,146✔
502

503
void BigInt::cond_flip_sign(bool predicate) {
32,876,649✔
504
   // This code is assuming Negative == 0, Positive == 1
505

506
   const auto mask = CT::Mask<uint8_t>::expand(predicate);
32,876,649✔
507

508
   const uint8_t current_sign = static_cast<uint8_t>(sign());
32,876,649✔
509

510
   const uint8_t new_sign = mask.select(current_sign ^ 1, current_sign);
32,876,649✔
511

512
   set_sign(static_cast<Sign>(new_sign));
32,876,649✔
513
}
32,876,649✔
514

515
void BigInt::ct_cond_assign(bool predicate, const BigInt& other) {
32,515,122✔
516
   const size_t t_words = size();
32,515,122✔
517
   const size_t o_words = other.size();
32,515,122✔
518

519
   if(o_words < t_words) {
32,515,122✔
520
      grow_to(o_words);
388✔
521
   }
522

523
   const size_t r_words = std::max(t_words, o_words);
32,515,122✔
524

525
   const auto mask = CT::Mask<word>::expand(predicate);
32,515,122✔
526

527
   for(size_t i = 0; i != r_words; ++i) {
2,147,483,647✔
528
      const word o_word = other.word_at(i);
2,147,483,647✔
529
      const word t_word = this->word_at(i);
2,147,483,647✔
530
      this->set_word_at(i, mask.select(o_word, t_word));
2,147,483,647✔
531
   }
532

533
   const auto same_sign = CT::Mask<word>::is_equal(sign(), other.sign()).as_choice();
32,515,122✔
534
   cond_flip_sign((mask.as_choice() && !same_sign).as_bool());
32,515,122✔
535
}
32,515,122✔
536

537
void BigInt::_const_time_poison() const {
3,096,154✔
538
   CT::poison(m_data.const_data(), m_data.size());
3,096,154✔
539
}
3,096,154✔
540

541
void BigInt::_const_time_unpoison() const {
37,502,691✔
542
   CT::unpoison(m_data.const_data(), m_data.size());
37,502,691✔
543
}
37,502,691✔
544

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