Coverage Report

Created: 2026-08-14 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/botan/src/lib/math/bigint/bigint.cpp
Line
Count
Source
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/mem_utils.h>
14
#include <botan/internal/mp_core.h>
15
#include <botan/internal/rounding.h>
16
17
namespace Botan {
18
19
641
BigInt::BigInt(uint64_t n) {
20
641
   if constexpr(sizeof(word) == 8) {
21
641
      m_data.set_word_at(0, static_cast<word>(n));
22
   } else {
23
      m_data.set_word_at(1, static_cast<word>(n >> 32));
24
      m_data.set_word_at(0, static_cast<word>(n));
25
   }
26
641
}
27
28
//static
29
176
BigInt BigInt::from_u64(uint64_t n) {
30
176
   return BigInt(n);
31
176
}
32
33
//static
34
9.69k
BigInt BigInt::from_word(word n) {
35
9.69k
   BigInt bn;
36
9.69k
   bn.set_word_at(0, n);
37
9.69k
   return bn;
38
9.69k
}
39
40
//static
41
172
BigInt BigInt::from_s32(int32_t n) {
42
172
   if(n >= 0) {
43
0
      return BigInt::from_u64(static_cast<uint64_t>(n));
44
172
   } else {
45
172
      return -BigInt::from_u64(static_cast<uint64_t>(-n));
46
172
   }
47
172
}
48
49
//static
50
102k
BigInt BigInt::with_capacity(size_t size) {
51
102k
   BigInt bn;
52
102k
   bn.grow_to(size);
53
102k
   return bn;
54
102k
}
55
56
/*
57
* Construct a BigInt from a string
58
*/
59
14.0k
BigInt::BigInt(std::string_view str) {
60
14.0k
   Base base = Decimal;
61
14.0k
   size_t markers = 0;
62
14.0k
   bool negative = false;
63
64
14.0k
   if(!str.empty() && str[0] == '-') {
65
0
      markers += 1;
66
0
      negative = true;
67
0
   }
68
69
14.0k
   if(str.length() > markers + 2 && str[markers] == '0' && str[markers + 1] == 'x') {
70
6
      markers += 2;
71
6
      base = Hexadecimal;
72
6
   }
73
74
14.0k
   *this = decode(as_span_of_bytes(str).subspan(markers), base);
75
76
14.0k
   if(negative) {
77
0
      set_sign(Negative);
78
14.0k
   } else {
79
14.0k
      set_sign(Positive);
80
14.0k
   }
81
14.0k
}
82
83
1.18k
BigInt BigInt::from_string(std::string_view str) {
84
1.18k
   return BigInt(str);
85
1.18k
}
86
87
1.95k
BigInt BigInt::from_bytes(std::span<const uint8_t> input) {
88
1.95k
   BigInt r;
89
1.95k
   r.assign_from_bytes(input);
90
1.95k
   return r;
91
1.95k
}
92
93
/*
94
* Construct a BigInt from an encoded BigInt
95
*/
96
0
BigInt::BigInt(const uint8_t input[], size_t length, Base base) {
97
0
   *this = decode(input, length, base);
98
0
}
99
100
//static
101
0
BigInt BigInt::from_bytes_with_max_bits(const uint8_t input[], size_t length, size_t max_bits) {
102
0
   const size_t input_bits = 8 * length;
103
104
0
   auto bn = BigInt::from_bytes(std::span{input, length});
105
106
0
   if(input_bits > max_bits) {
107
0
      const size_t bits_to_shift = input_bits - max_bits;
108
109
0
      bn >>= bits_to_shift;
110
0
   }
111
112
0
   return bn;
113
0
}
114
115
/*
116
* Construct a BigInt from an encoded BigInt
117
*/
118
0
BigInt::BigInt(RandomNumberGenerator& rng, size_t bits, bool set_high_bit) {
119
0
   randomize(rng, bits, set_high_bit);
120
0
}
121
122
1.86k
uint8_t BigInt::byte_at(size_t n) const {
123
1.86k
   return get_byte_var(sizeof(word) - (n % sizeof(word)) - 1, word_at(n / sizeof(word)));
124
1.86k
}
125
126
96.5k
int32_t BigInt::cmp_word(word other) const {
127
96.5k
   if(is_negative()) {
128
172
      return -1;  // other is positive ...
129
172
   }
130
131
96.4k
   const size_t sw = this->sig_words();
132
96.4k
   if(sw > 1) {
133
81.3k
      return 1;  // must be larger since other is just one word ...
134
81.3k
   }
135
136
15.0k
   return bigint_cmp(this->_data(), sw, &other, 1);
137
96.4k
}
138
139
/*
140
* Comparison Function
141
*/
142
2.15k
int32_t BigInt::cmp(const BigInt& other, bool check_signs) const {
143
2.15k
   if(check_signs) {
144
2.15k
      if(other.is_positive() && this->is_negative()) {
145
0
         return -1;
146
0
      }
147
148
2.15k
      if(other.is_negative() && this->is_positive()) {
149
0
         return 1;
150
0
      }
151
152
2.15k
      if(other.is_negative() && this->is_negative()) {
153
0
         return (-bigint_cmp(this->_data(), this->size(), other._data(), other.size()));
154
0
      }
155
2.15k
   }
156
157
2.15k
   return bigint_cmp(this->_data(), this->size(), other._data(), other.size());
158
2.15k
}
159
160
205
bool BigInt::is_equal(const BigInt& other) const {
161
205
   if(this->sign() != other.sign()) {
162
0
      return false;
163
0
   }
164
165
205
   return bigint_ct_is_eq(this->_data(), this->sig_words(), other._data(), other.sig_words()).as_bool();
166
205
}
167
168
60.1k
bool BigInt::is_less_than(const BigInt& other) const {
169
60.1k
   if(this->is_negative() && other.is_positive()) {
170
0
      return true;
171
0
   }
172
173
60.1k
   if(this->is_positive() && other.is_negative()) {
174
0
      return false;
175
0
   }
176
177
60.1k
   if(other.is_negative() && this->is_negative()) {
178
0
      return bigint_ct_is_lt(other._data(), other.sig_words(), this->_data(), this->sig_words()).as_bool();
179
0
   }
180
181
60.1k
   return bigint_ct_is_lt(this->_data(), this->sig_words(), other._data(), other.sig_words()).as_bool();
182
60.1k
}
183
184
4.87k
void BigInt::encode_words(word out[], size_t size) const {
185
4.87k
   const size_t words = sig_words();
186
187
4.87k
   if(words > size) {
188
0
      throw Encoding_Error("BigInt::encode_words value too large to encode");
189
0
   }
190
191
4.87k
   clear_mem(out, size);
192
4.87k
   copy_mem(out, _data(), words);
193
4.87k
}
194
195
1.96k
void BigInt::Data::set_to_zero() {
196
1.96k
   m_reg.resize(m_reg.capacity());
197
1.96k
   clear_mem(m_reg.data(), m_reg.size());
198
1.96k
   m_sig_words = 0;
199
1.96k
}
200
201
0
void BigInt::Data::mask_bits(size_t n) {
202
0
   if(n == 0) {
203
0
      return set_to_zero();
204
0
   }
205
206
0
   const size_t top_word = n / WordInfo<word>::bits;
207
208
0
   if(top_word < size()) {
209
0
      const word mask = (static_cast<word>(1) << (n % WordInfo<word>::bits)) - 1;
210
0
      const size_t len = size() - (top_word + 1);
211
0
      if(len > 0) {
212
0
         clear_mem(&m_reg[top_word + 1], len);
213
0
      }
214
0
      m_reg[top_word] &= mask;
215
0
      invalidate_sig_words();
216
0
   }
217
0
}
218
219
2.23M
size_t BigInt::Data::calc_sig_words() const {
220
2.23M
   const size_t sz = m_reg.size();
221
2.23M
   size_t sig = sz;
222
223
2.23M
   word sub = 1;
224
225
2.00G
   for(size_t i = 0; i != sz; ++i) {
226
2.00G
      const word w = m_reg[sz - i - 1];
227
2.00G
      sub &= ct_is_zero(w);
228
2.00G
      sig -= sub;
229
2.00G
   }
230
231
   /*
232
   * This depends on the data so is poisoned, but unpoison it here as
233
   * later conditionals are made on the size.
234
   */
235
2.23M
   CT::unpoison(sig);
236
237
2.23M
   return sig;
238
2.23M
}
239
240
/*
241
* Return bits {offset...offset+length}
242
*/
243
41.6k
uint32_t BigInt::get_substring(size_t offset, size_t length) const {
244
41.6k
   if(length == 0 || length > 32) {
245
0
      throw Invalid_Argument("BigInt::get_substring invalid substring length");
246
0
   }
247
248
41.6k
   const uint32_t mask = 0xFFFFFFFF >> (32 - length);
249
250
41.6k
   const size_t word_offset = offset / WordInfo<word>::bits;
251
41.6k
   const size_t wshift = (offset % WordInfo<word>::bits);
252
253
   /*
254
   * The substring is contained within one or at most two words. The
255
   * offset and length are not secret, so we can perform conditional
256
   * operations on those values.
257
   */
258
41.6k
   const word w0 = word_at(word_offset);
259
260
41.6k
   if(wshift == 0 || (offset + length) / WordInfo<word>::bits == word_offset) {
261
39.6k
      return static_cast<uint32_t>(w0 >> wshift) & mask;
262
39.6k
   } else {
263
2.01k
      const word w1 = word_at(word_offset + 1);
264
2.01k
      return static_cast<uint32_t>((w0 >> wshift) | (w1 << (WordInfo<word>::bits - wshift))) & mask;
265
2.01k
   }
266
41.6k
}
267
268
/*
269
* Convert this number to a uint32_t, if possible
270
*/
271
0
uint32_t BigInt::to_u32bit() const {
272
0
   if(is_negative()) {
273
0
      throw Encoding_Error("BigInt::to_u32bit: Number is negative");
274
0
   }
275
0
   if(bits() > 32) {
276
0
      throw Encoding_Error("BigInt::to_u32bit: Number is too big to convert");
277
0
   }
278
279
0
   uint32_t out = 0;
280
0
   for(size_t i = 0; i != 4; ++i) {
281
0
      out = (out << 8) | byte_at(3 - i);
282
0
   }
283
0
   return out;
284
0
}
285
286
/*
287
* Clear bit number n
288
*/
289
0
void BigInt::clear_bit(size_t n) {
290
0
   const size_t which = n / WordInfo<word>::bits;
291
292
0
   if(which < size()) {
293
0
      const word mask = ~(static_cast<word>(1) << (n % WordInfo<word>::bits));
294
0
      m_data.set_word_at(which, word_at(which) & mask);
295
0
   }
296
0
}
297
298
5.79k
size_t BigInt::bytes() const {
299
5.79k
   return round_up(bits(), 8) / 8;
300
5.79k
}
301
302
49.9k
size_t BigInt::top_bits_free() const {
303
49.9k
   const size_t words = sig_words();
304
305
49.9k
   const word top_word = word_at(words - 1);
306
49.9k
   const size_t bits_used = high_bit(CT::value_barrier(top_word));
307
49.9k
   CT::unpoison(bits_used);
308
49.9k
   return WordInfo<word>::bits - bits_used;
309
49.9k
}
310
311
37.3k
size_t BigInt::bits() const {
312
37.3k
   const size_t words = sig_words();
313
314
37.3k
   if(words == 0) {
315
739
      return 0;
316
739
   }
317
318
36.6k
   const size_t full_words = (words - 1) * WordInfo<word>::bits;
319
36.6k
   const size_t top_bits = WordInfo<word>::bits - top_bits_free();
320
321
36.6k
   return full_words + top_bits;
322
37.3k
}
323
324
/*
325
* Return the negation of this number
326
*/
327
172
BigInt BigInt::operator-() const {
328
172
   BigInt x = (*this);
329
172
   x.flip_sign();
330
172
   return x;
331
172
}
332
333
17.4k
size_t BigInt::reduce_below(const BigInt& p, secure_vector<word>& ws) {
334
17.4k
   if(p.is_negative() || this->is_negative()) {
335
0
      throw Invalid_Argument("BigInt::reduce_below both values must be positive");
336
0
   }
337
338
17.4k
   const size_t p_words = p.sig_words();
339
340
17.4k
   if(size() < p_words + 1) {
341
8
      grow_to(p_words + 1);
342
8
   }
343
344
17.4k
   if(ws.size() < p_words + 1) {
345
13.2k
      ws.resize(p_words + 1);
346
13.2k
   }
347
348
17.4k
   clear_mem(ws.data(), ws.size());
349
350
17.4k
   size_t reductions = 0;
351
352
24.4k
   for(;;) {
353
24.4k
      word borrow = bigint_sub3(ws.data(), _data(), p_words + 1, p._data(), p_words);
354
24.4k
      if(borrow > 0) {
355
17.4k
         break;
356
17.4k
      }
357
358
6.94k
      ++reductions;
359
6.94k
      swap_reg(ws);
360
6.94k
   }
361
362
17.4k
   return reductions;
363
17.4k
}
364
365
0
void BigInt::ct_reduce_below(const BigInt& mod, secure_vector<word>& ws, size_t bound) {
366
0
   if(mod.is_negative() || this->is_negative()) {
367
0
      throw Invalid_Argument("BigInt::ct_reduce_below both values must be positive");
368
0
   }
369
370
0
   const size_t mod_words = mod.sig_words();
371
372
0
   grow_to(mod_words);
373
374
0
   const size_t sz = size();
375
376
0
   ws.resize(sz);
377
378
0
   clear_mem(ws.data(), sz);
379
380
0
   for(size_t i = 0; i != bound; ++i) {
381
0
      word borrow = bigint_sub3(ws.data(), _data(), sz, mod._data(), mod_words);
382
383
0
      CT::Mask<word>::is_zero(borrow).select_n(mutable_data(), ws.data(), _data(), sz);
384
0
   }
385
0
}
386
387
/*
388
* Return the absolute value of this number
389
*/
390
185
BigInt BigInt::abs() const {
391
185
   BigInt x = (*this);
392
185
   x.set_sign(Positive);
393
185
   return x;
394
185
}
395
396
/*
397
* Encode this number into bytes
398
*/
399
3.24k
void BigInt::serialize_to(std::span<uint8_t> output) const {
400
3.24k
   BOTAN_ARG_CHECK(this->bytes() <= output.size(), "Insufficient output space");
401
402
3.24k
   this->binary_encode(output.data(), output.size());
403
3.24k
}
404
405
/*
406
* Encode this number into bytes
407
*/
408
3.24k
void BigInt::binary_encode(uint8_t output[], size_t len) const {
409
3.24k
   const size_t full_words = len / sizeof(word);
410
3.24k
   const size_t extra_bytes = len % sizeof(word);
411
412
24.9k
   for(size_t i = 0; i != full_words; ++i) {
413
21.6k
      const word w = word_at(i);
414
21.6k
      store_be(w, output + (len - (i + 1) * sizeof(word)));
415
21.6k
   }
416
417
3.24k
   if(extra_bytes > 0) {
418
711
      const word w = word_at(full_words);
419
420
2.68k
      for(size_t i = 0; i != extra_bytes; ++i) {
421
1.97k
         output[extra_bytes - i - 1] = get_byte_var(sizeof(word) - i - 1, w);
422
1.97k
      }
423
711
   }
424
3.24k
}
425
426
/*
427
* Set this number to the value in buf
428
*/
429
1.96k
void BigInt::assign_from_bytes(std::span<const uint8_t> bytes) {
430
1.96k
   clear();
431
432
1.96k
   const size_t length = bytes.size();
433
1.96k
   const size_t full_words = length / sizeof(word);
434
1.96k
   const size_t extra_bytes = length % sizeof(word);
435
436
1.96k
   secure_vector<word> reg((round_up(full_words + (extra_bytes > 0 ? 1 : 0), 8)));
437
438
13.7k
   for(size_t i = 0; i != full_words; ++i) {
439
11.7k
      reg[i] = load_be<word>(bytes.last<sizeof(word)>());
440
11.7k
      bytes = bytes.first(bytes.size() - sizeof(word));
441
11.7k
   }
442
443
1.96k
   if(!bytes.empty()) {
444
0
      BOTAN_ASSERT_NOMSG(extra_bytes == bytes.size());
445
0
      std::array<uint8_t, sizeof(word)> last_partial_word = {0};
446
0
      copy_mem(std::span{last_partial_word}.last(extra_bytes), bytes);
447
0
      reg[full_words] = load_be<word>(last_partial_word);
448
0
   }
449
450
1.96k
   m_data.swap(reg);
451
1.96k
}
452
453
0
void BigInt::ct_cond_add(bool predicate, const BigInt& value) {
454
0
   if(this->is_negative() || value.is_negative()) {
455
0
      throw Invalid_Argument("BigInt::ct_cond_add requires both values to be positive");
456
0
   }
457
0
   const size_t v_words = value.sig_words();
458
459
0
   this->grow_to(1 + v_words);
460
461
0
   const auto mask = CT::Mask<word>::expand(static_cast<word>(predicate)).value();
462
463
0
   word carry = 0;
464
465
0
   word* x = this->mutable_data();
466
0
   const word* y = value._data();
467
468
0
   for(size_t i = 0; i != v_words; ++i) {
469
0
      x[i] = word_add(x[i], y[i] & mask, &carry);
470
0
   }
471
472
0
   for(size_t i = v_words; i != size(); ++i) {
473
0
      x[i] = word_add(x[i], static_cast<word>(0), &carry);
474
0
   }
475
0
}
476
477
0
void BigInt::ct_shift_left(size_t shift) {
478
0
   auto shl_bit = [](const BigInt& a, BigInt& result) {
479
0
      BOTAN_DEBUG_ASSERT(a.size() + 1 == result.size());
480
0
      bigint_shl2(result.mutable_data(), a._data(), a.size(), 1);
481
      // shl2 may have shifted a bit into the next word, which must be dropped
482
0
      clear_mem(result.mutable_data() + result.size() - 1, 1);
483
0
   };
484
485
0
   auto shl_word = [](const BigInt& a, BigInt& result) {
486
      // the most significant word is not copied, aka. shifted out
487
0
      bigint_shl2(result.mutable_data(), a._data(), a.size() - 1 /* ignore msw */, WordInfo<word>::bits);
488
      // we left-shifted by a full word, the least significant word must be zero'ed
489
0
      clear_mem(result.mutable_data(), 1);
490
0
   };
491
492
0
   BOTAN_ASSERT_NOMSG(size() > 0);
493
494
0
   constexpr size_t bits_in_word = sizeof(word) * 8;
495
0
   const size_t word_shift = shift >> ceil_log2(bits_in_word);             // shift / bits_in_word
496
0
   const size_t bit_shift = shift & ((1 << ceil_log2(bits_in_word)) - 1);  // shift % bits_in_word
497
0
   const size_t iterations = std::max(size(), bits_in_word) - 1;           // uint64_t i; i << 64 is undefined behaviour
498
499
   // In every iteration, shift one bit and one word to the left and use the
500
   // shift results only when they are within the shift range.
501
0
   BigInt tmp;
502
0
   tmp.resize(size() + 1 /* to hold the shifted-out word */);
503
0
   for(size_t i = 0; i < iterations; ++i) {
504
0
      shl_bit(*this, tmp);
505
0
      ct_cond_assign(i < bit_shift, tmp);
506
0
      shl_word(*this, tmp);
507
0
      ct_cond_assign(i < word_shift, tmp);
508
0
   }
509
0
}
510
511
27.4k
void BigInt::ct_cond_swap(bool predicate, BigInt& other) {
512
27.4k
   const size_t max_words = std::max(size(), other.size());
513
27.4k
   grow_to(max_words);
514
27.4k
   other.grow_to(max_words);
515
516
27.4k
   bigint_cnd_swap(static_cast<word>(predicate), this->mutable_data(), other.mutable_data(), max_words);
517
27.4k
}
518
519
13.8k
void BigInt::cond_flip_sign(bool predicate) {
520
   // This code is assuming Negative == 0, Positive == 1
521
522
13.8k
   const auto mask = CT::Mask<uint8_t>::expand_bool(predicate);
523
524
13.8k
   const uint8_t current_sign = static_cast<uint8_t>(sign());
525
526
13.8k
   const uint8_t new_sign = mask.select(current_sign ^ 1, current_sign);
527
528
13.8k
   set_sign(static_cast<Sign>(new_sign));
529
13.8k
}
530
531
139
void BigInt::ct_cond_assign(bool predicate, const BigInt& other) {
532
139
   const size_t t_words = size();
533
139
   const size_t o_words = other.size();
534
535
139
   if(o_words < t_words) {
536
0
      grow_to(o_words);
537
0
   }
538
539
139
   const size_t r_words = std::max(t_words, o_words);
540
541
139
   const auto mask = CT::Mask<word>::expand_bool(predicate);
542
543
8.16k
   for(size_t i = 0; i != r_words; ++i) {
544
8.02k
      const word o_word = other.word_at(i);
545
8.02k
      const word t_word = this->word_at(i);
546
8.02k
      this->set_word_at(i, mask.select(o_word, t_word));
547
8.02k
   }
548
549
139
   const auto same_sign = CT::Mask<word>::is_equal(sign(), other.sign()).as_choice();
550
139
   cond_flip_sign((mask.as_choice() && !same_sign).as_bool());
551
139
}
552
553
0
void BigInt::_const_time_poison() const {
554
0
   CT::poison(m_data.const_data(), m_data.size());
555
0
}
556
557
372k
void BigInt::_const_time_unpoison() const {
558
372k
   CT::unpoison(m_data.const_data(), m_data.size());
559
372k
}
560
561
}  // namespace Botan