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

randombit / botan / 13212092742

08 Feb 2025 12:33AM UTC coverage: 91.658% (-0.004%) from 91.662%
13212092742

push

github

web-flow
Merge pull request #4642 from randombit/jack/target-info-header

Add internal target_info.h header

94839 of 103471 relevant lines covered (91.66%)

11295178.12 hits per line

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

95.0
/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) {
554,977✔
19
   if constexpr(sizeof(word) == 8) {
554,977✔
20
      m_data.set_word_at(0, static_cast<word>(n));
554,977✔
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
}
554,977✔
26

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

151
      if(other.is_negative() && this->is_negative()) {
1,427,438✔
152
         return (-bigint_cmp(this->_data(), this->size(), other._data(), other.size()));
52✔
153
      }
154
   }
155

156
   return bigint_cmp(this->_data(), this->size(), other._data(), other.size());
1,427,513✔
157
}
158

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

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

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

172
   if(this->is_positive() && other.is_negative()) {
2,275,073✔
173
      return false;
174
   }
175

176
   if(other.is_negative() && this->is_negative()) {
2,275,002✔
177
      return bigint_ct_is_lt(other._data(), other.sig_words(), this->_data(), this->sig_words()).as_bool();
51✔
178
   }
179

180
   return bigint_ct_is_lt(this->_data(), this->sig_words(), other._data(), other.sig_words()).as_bool();
4,315,434✔
181
}
182

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

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

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

194
size_t BigInt::Data::calc_sig_words() const {
116,346,675✔
195
   const size_t sz = m_reg.size();
116,346,675✔
196
   size_t sig = sz;
116,346,675✔
197

198
   word sub = 1;
116,346,675✔
199

200
   for(size_t i = 0; i != sz; ++i) {
2,147,483,647✔
201
      const word w = m_reg[sz - i - 1];
2,147,483,647✔
202
      sub &= ct_is_zero(w);
2,147,483,647✔
203
      sig -= sub;
2,147,483,647✔
204
   }
205

206
   /*
207
   * This depends on the data so is poisoned, but unpoison it here as
208
   * later conditionals are made on the size.
209
   */
210
   CT::unpoison(sig);
116,346,675✔
211

212
   return sig;
116,346,675✔
213
}
214

215
/*
216
* Return bits {offset...offset+length}
217
*/
218
uint32_t BigInt::get_substring(size_t offset, size_t length) const {
19,111,676✔
219
   if(length == 0 || length > 32) {
19,111,676✔
220
      throw Invalid_Argument("BigInt::get_substring invalid substring length");
×
221
   }
222

223
   const uint32_t mask = 0xFFFFFFFF >> (32 - length);
19,111,676✔
224

225
   const size_t word_offset = offset / WordInfo<word>::bits;
19,111,676✔
226
   const size_t wshift = (offset % WordInfo<word>::bits);
19,111,676✔
227

228
   /*
229
   * The substring is contained within one or at most two words. The
230
   * offset and length are not secret, so we can perform conditional
231
   * operations on those values.
232
   */
233
   const word w0 = word_at(word_offset);
19,111,676✔
234

235
   if(wshift == 0 || (offset + length) / WordInfo<word>::bits == word_offset) {
19,111,676✔
236
      return static_cast<uint32_t>(w0 >> wshift) & mask;
18,131,474✔
237
   } else {
238
      const word w1 = word_at(word_offset + 1);
980,202✔
239
      return static_cast<uint32_t>((w0 >> wshift) | (w1 << (WordInfo<word>::bits - wshift))) & mask;
980,202✔
240
   }
241
}
242

243
/*
244
* Convert this number to a uint32_t, if possible
245
*/
246
uint32_t BigInt::to_u32bit() const {
34,950✔
247
   if(is_negative()) {
34,950✔
248
      throw Encoding_Error("BigInt::to_u32bit: Number is negative");
×
249
   }
250
   if(bits() > 32) {
34,950✔
251
      throw Encoding_Error("BigInt::to_u32bit: Number is too big to convert");
15✔
252
   }
253

254
   uint32_t out = 0;
255
   for(size_t i = 0; i != 4; ++i) {
174,675✔
256
      out = (out << 8) | byte_at(3 - i);
139,740✔
257
   }
258
   return out;
34,935✔
259
}
260

261
/*
262
* Clear bit number n
263
*/
264
void BigInt::clear_bit(size_t n) {
81✔
265
   const size_t which = n / WordInfo<word>::bits;
81✔
266

267
   if(which < size()) {
81✔
268
      const word mask = ~(static_cast<word>(1) << (n % WordInfo<word>::bits));
81✔
269
      m_data.set_word_at(which, word_at(which) & mask);
81✔
270
   }
271
}
81✔
272

273
size_t BigInt::bytes() const {
430,095✔
274
   return round_up(bits(), 8) / 8;
430,095✔
275
}
276

277
size_t BigInt::top_bits_free() const {
2,563,801✔
278
   const size_t words = sig_words();
2,563,801✔
279

280
   const word top_word = word_at(words - 1);
2,563,801✔
281
   const size_t bits_used = high_bit(CT::value_barrier(top_word));
2,563,801✔
282
   CT::unpoison(bits_used);
2,563,801✔
283
   return WordInfo<word>::bits - bits_used;
2,563,801✔
284
}
285

286
size_t BigInt::bits() const {
2,236,044✔
287
   const size_t words = sig_words();
2,236,044✔
288

289
   if(words == 0) {
2,236,044✔
290
      return 0;
291
   }
292

293
   const size_t full_words = (words - 1) * WordInfo<word>::bits;
2,216,131✔
294
   const size_t top_bits = WordInfo<word>::bits - top_bits_free();
2,216,131✔
295

296
   return full_words + top_bits;
2,216,131✔
297
}
298

299
/*
300
* Return the negation of this number
301
*/
302
BigInt BigInt::operator-() const {
7,512✔
303
   BigInt x = (*this);
7,512✔
304
   x.flip_sign();
7,512✔
305
   return x;
7,512✔
306
}
×
307

308
size_t BigInt::reduce_below(const BigInt& p, secure_vector<word>& ws) {
21,604,878✔
309
   if(p.is_negative() || this->is_negative()) {
21,604,878✔
310
      throw Invalid_Argument("BigInt::reduce_below both values must be positive");
×
311
   }
312

313
   const size_t p_words = p.sig_words();
21,604,878✔
314

315
   if(size() < p_words + 1) {
21,604,878✔
316
      grow_to(p_words + 1);
9,453✔
317
   }
318

319
   if(ws.size() < p_words + 1) {
21,604,878✔
320
      ws.resize(p_words + 1);
347,670✔
321
   }
322

323
   clear_mem(ws.data(), ws.size());
21,604,878✔
324

325
   size_t reductions = 0;
21,604,878✔
326

327
   for(;;) {
34,532,294✔
328
      word borrow = bigint_sub3(ws.data(), _data(), p_words + 1, p._data(), p_words);
56,137,172✔
329
      if(borrow) {
56,137,172✔
330
         break;
331
      }
332

333
      ++reductions;
34,532,294✔
334
      swap_reg(ws);
34,532,294✔
335
   }
336

337
   return reductions;
21,604,878✔
338
}
339

340
void BigInt::ct_reduce_below(const BigInt& mod, secure_vector<word>& ws, size_t bound) {
9,806,143✔
341
   if(mod.is_negative() || this->is_negative()) {
9,806,143✔
342
      throw Invalid_Argument("BigInt::ct_reduce_below both values must be positive");
×
343
   }
344

345
   const size_t mod_words = mod.sig_words();
9,806,143✔
346

347
   grow_to(mod_words);
9,806,143✔
348

349
   const size_t sz = size();
9,806,143✔
350

351
   ws.resize(sz);
9,806,143✔
352

353
   clear_mem(ws.data(), sz);
9,806,143✔
354

355
   for(size_t i = 0; i != bound; ++i) {
29,418,429✔
356
      word borrow = bigint_sub3(ws.data(), _data(), sz, mod._data(), mod_words);
19,612,286✔
357

358
      CT::Mask<word>::is_zero(borrow).select_n(mutable_data(), ws.data(), _data(), sz);
39,224,572✔
359
   }
360
}
9,806,143✔
361

362
/*
363
* Return the absolute value of this number
364
*/
365
BigInt BigInt::abs() const {
1,782✔
366
   BigInt x = (*this);
1,782✔
367
   x.set_sign(Positive);
1,782✔
368
   return x;
1,782✔
369
}
370

371
/*
372
* Encode this number into bytes
373
*/
374
void BigInt::serialize_to(std::span<uint8_t> output) const {
296,309✔
375
   BOTAN_ARG_CHECK(this->bytes() <= output.size(), "Insufficient output space");
296,309✔
376

377
   this->binary_encode(output.data(), output.size());
296,083✔
378
}
296,083✔
379

380
/*
381
* Encode this number into bytes
382
*/
383
void BigInt::binary_encode(uint8_t output[], size_t len) const {
296,088✔
384
   const size_t full_words = len / sizeof(word);
296,088✔
385
   const size_t extra_bytes = len % sizeof(word);
296,088✔
386

387
   for(size_t i = 0; i != full_words; ++i) {
2,240,088✔
388
      const word w = word_at(i);
1,944,000✔
389
      store_be(w, output + (len - (i + 1) * sizeof(word)));
1,944,000✔
390
   }
391

392
   if(extra_bytes > 0) {
296,088✔
393
      const word w = word_at(full_words);
159,250✔
394

395
      for(size_t i = 0; i != extra_bytes; ++i) {
775,514✔
396
         output[extra_bytes - i - 1] = get_byte_var(sizeof(word) - i - 1, w);
616,264✔
397
      }
398
   }
399
}
296,088✔
400

401
/*
402
* Set this number to the value in buf
403
*/
404
void BigInt::assign_from_bytes(std::span<const uint8_t> bytes) {
957,572✔
405
   clear();
957,572✔
406

407
   const size_t length = bytes.size();
957,572✔
408
   const size_t full_words = length / sizeof(word);
957,572✔
409
   const size_t extra_bytes = length % sizeof(word);
957,572✔
410

411
   secure_vector<word> reg((round_up(full_words + (extra_bytes > 0 ? 1 : 0), 8)));
1,285,520✔
412

413
   for(size_t i = 0; i != full_words; ++i) {
5,862,241✔
414
      reg[i] = load_be<word>(bytes.last<sizeof(word)>());
4,904,669✔
415
      bytes = bytes.first(bytes.size() - sizeof(word));
4,904,669✔
416
   }
417

418
   if(!bytes.empty()) {
957,572✔
419
      BOTAN_ASSERT_NOMSG(extra_bytes == bytes.size());
629,624✔
420
      std::array<uint8_t, sizeof(word)> last_partial_word = {0};
629,624✔
421
      copy_mem(std::span{last_partial_word}.last(extra_bytes), bytes);
629,624✔
422
      reg[full_words] = load_be<word>(last_partial_word);
629,624✔
423
   }
424

425
   m_data.swap(reg);
957,572✔
426
}
957,572✔
427

428
void BigInt::ct_cond_add(bool predicate, const BigInt& value) {
3,472,282✔
429
   if(this->is_negative() || value.is_negative()) {
3,472,282✔
430
      throw Invalid_Argument("BigInt::ct_cond_add requires both values to be positive");
×
431
   }
432
   this->grow_to(1 + value.sig_words());
3,472,282✔
433

434
   bigint_cnd_add(static_cast<word>(predicate), this->mutable_data(), this->size(), value._data(), value.sig_words());
3,472,282✔
435
}
3,472,282✔
436

437
void BigInt::ct_shift_left(size_t shift) {
30,722✔
438
   auto shl_bit = [](const BigInt& a, BigInt& result) {
3,833,984✔
439
      BOTAN_DEBUG_ASSERT(a.size() + 1 == result.size());
3,803,262✔
440
      bigint_shl2(result.mutable_data(), a._data(), a.size(), 1);
3,803,262✔
441
      // shl2 may have shifted a bit into the next word, which must be dropped
442
      clear_mem(result.mutable_data() + result.size() - 1, 1);
3,803,262✔
443
   };
3,803,262✔
444

445
   auto shl_word = [](const BigInt& a, BigInt& result) {
3,833,984✔
446
      // the most significant word is not copied, aka. shifted out
447
      bigint_shl2(result.mutable_data(), a._data(), a.size() - 1 /* ignore msw */, WordInfo<word>::bits);
3,803,262✔
448
      // we left-shifted by a full word, the least significant word must be zero'ed
449
      clear_mem(result.mutable_data(), 1);
3,803,262✔
450
   };
3,803,262✔
451

452
   BOTAN_ASSERT_NOMSG(size() > 0);
30,722✔
453

454
   constexpr size_t bits_in_word = sizeof(word) * 8;
30,722✔
455
   const size_t word_shift = shift >> ceil_log2(bits_in_word);             // shift / bits_in_word
30,722✔
456
   const size_t bit_shift = shift & ((1 << ceil_log2(bits_in_word)) - 1);  // shift % bits_in_word
30,722✔
457
   const size_t iterations = std::max(size(), bits_in_word) - 1;           // uint64_t i; i << 64 is undefined behaviour
30,722✔
458

459
   // In every iteration, shift one bit and one word to the left and use the
460
   // shift results only when they are within the shift range.
461
   BigInt tmp;
30,722✔
462
   tmp.resize(size() + 1 /* to hold the shifted-out word */);
30,722✔
463
   for(size_t i = 0; i < iterations; ++i) {
3,833,984✔
464
      shl_bit(*this, tmp);
3,803,262✔
465
      ct_cond_assign(i < bit_shift, tmp);
3,803,262✔
466
      shl_word(*this, tmp);
3,803,262✔
467
      ct_cond_assign(i < word_shift, tmp);
3,803,262✔
468
   }
469
}
30,722✔
470

471
void BigInt::ct_cond_swap(bool predicate, BigInt& other) {
13,435,673✔
472
   const size_t max_words = std::max(size(), other.size());
13,435,673✔
473
   grow_to(max_words);
13,435,673✔
474
   other.grow_to(max_words);
13,435,673✔
475

476
   bigint_cnd_swap(static_cast<word>(predicate), this->mutable_data(), other.mutable_data(), max_words);
13,435,673✔
477
}
13,435,673✔
478

479
void BigInt::cond_flip_sign(bool predicate) {
56,517,375✔
480
   // This code is assuming Negative == 0, Positive == 1
481

482
   const auto mask = CT::Mask<uint8_t>::expand(predicate);
56,517,375✔
483

484
   const uint8_t current_sign = static_cast<uint8_t>(sign());
56,517,375✔
485

486
   const uint8_t new_sign = mask.select(current_sign ^ 1, current_sign);
56,517,375✔
487

488
   set_sign(static_cast<Sign>(new_sign));
56,517,375✔
489
}
56,517,375✔
490

491
void BigInt::ct_cond_assign(bool predicate, const BigInt& other) {
32,841,807✔
492
   const size_t t_words = size();
32,841,807✔
493
   const size_t o_words = other.size();
32,841,807✔
494

495
   if(o_words < t_words) {
32,841,807✔
496
      grow_to(o_words);
55,634✔
497
   }
498

499
   const size_t r_words = std::max(t_words, o_words);
32,841,807✔
500

501
   const auto mask = CT::Mask<word>::expand(predicate);
32,841,807✔
502

503
   for(size_t i = 0; i != r_words; ++i) {
2,147,483,647✔
504
      const word o_word = other.word_at(i);
2,147,483,647✔
505
      const word t_word = this->word_at(i);
2,147,483,647✔
506
      this->set_word_at(i, mask.select(o_word, t_word));
2,147,483,647✔
507
   }
508

509
   const auto same_sign = CT::Mask<word>::is_equal(sign(), other.sign()).as_choice();
32,841,807✔
510
   cond_flip_sign((mask.as_choice() && !same_sign).as_bool());
32,841,807✔
511
}
32,841,807✔
512

513
void BigInt::_const_time_poison() const {
3,176,452✔
514
   CT::poison(m_data.const_data(), m_data.size());
3,176,452✔
515
}
3,176,452✔
516

517
void BigInt::_const_time_unpoison() const {
49,465,223✔
518
   CT::unpoison(m_data.const_data(), m_data.size());
49,465,223✔
519
}
49,465,223✔
520

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