Coverage Report

Created: 2026-04-01 07:07

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