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

randombit / botan / 16293079084

15 Jul 2025 12:20PM UTC coverage: 90.627% (+0.003%) from 90.624%
16293079084

push

github

web-flow
Merge pull request #4990 from randombit/jack/string-and-span

Improve string<->span conversions

99640 of 109945 relevant lines covered (90.63%)

12253617.72 hits per line

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

90.58
/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/mem_utils.h>
14
#include <botan/internal/mp_core.h>
15
#include <botan/internal/rounding.h>
16

17
namespace Botan {
18

19
BigInt::BigInt(uint64_t n) {
366,839✔
20
   if constexpr(sizeof(word) == 8) {
366,839✔
21
      m_data.set_word_at(0, static_cast<word>(n));
366,839✔
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
}
366,839✔
27

28
//static
29
BigInt BigInt::from_u64(uint64_t n) {
187,916✔
30
   return BigInt(n);
187,916✔
31
}
32

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

40
//static
41
BigInt BigInt::from_s32(int32_t n) {
70,843✔
42
   if(n >= 0) {
70,843✔
43
      return BigInt::from_u64(static_cast<uint64_t>(n));
70,695✔
44
   } else {
45
      return -BigInt::from_u64(static_cast<uint64_t>(-n));
148✔
46
   }
47
}
48

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

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

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

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

74
   *this = decode(as_span_of_bytes(str).subspan(markers), base);
46,623✔
75

76
   if(negative) {
46,623✔
77
      set_sign(Negative);
890✔
78
   } else {
79
      set_sign(Positive);
46,178✔
80
   }
81
}
46,623✔
82

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

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

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

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

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

106
   if(input_bits > max_bits) {
6,912✔
107
      const size_t bits_to_shift = input_bits - max_bits;
3,725✔
108

109
      bn >>= bits_to_shift;
3,725✔
110
   }
111

112
   return bn;
6,912✔
113
}
×
114

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

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

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

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

136
   return bigint_cmp(this->_data(), sw, &other, 1);
1,986,644✔
137
}
138

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

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

152
      if(other.is_negative() && this->is_negative()) {
959,966✔
153
         return (-bigint_cmp(this->_data(), this->size(), other._data(), other.size()));
74✔
154
      }
155
   }
156

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

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

165
   return bigint_ct_is_eq(this->_data(), this->sig_words(), other._data(), other.sig_words()).as_bool();
986,981✔
166
}
167

168
bool BigInt::is_less_than(const BigInt& other) const {
1,710,885✔
169
   if(this->is_negative() && other.is_positive()) {
1,710,885✔
170
      return true;
171
   }
172

173
   if(this->is_positive() && other.is_negative()) {
1,710,809✔
174
      return false;
175
   }
176

177
   if(other.is_negative() && this->is_negative()) {
1,710,735✔
178
      return bigint_ct_is_lt(other._data(), other.sig_words(), this->_data(), this->sig_words()).as_bool();
73✔
179
   }
180

181
   return bigint_ct_is_lt(this->_data(), this->sig_words(), other._data(), other.sig_words()).as_bool();
3,271,066✔
182
}
183

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

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

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

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

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

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

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

219
size_t BigInt::Data::calc_sig_words() const {
45,085,942✔
220
   const size_t sz = m_reg.size();
45,085,942✔
221
   size_t sig = sz;
45,085,942✔
222

223
   word sub = 1;
45,085,942✔
224

225
   for(size_t i = 0; i != sz; ++i) {
1,238,195,487✔
226
      const word w = m_reg[sz - i - 1];
1,193,109,545✔
227
      sub &= ct_is_zero(w);
1,193,109,545✔
228
      sig -= sub;
1,193,109,545✔
229
   }
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
   CT::unpoison(sig);
45,085,942✔
236

237
   return sig;
45,085,942✔
238
}
239

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

248
   const uint32_t mask = 0xFFFFFFFF >> (32 - length);
14,729,631✔
249

250
   const size_t word_offset = offset / WordInfo<word>::bits;
14,729,631✔
251
   const size_t wshift = (offset % WordInfo<word>::bits);
14,729,631✔
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
   const word w0 = word_at(word_offset);
14,729,631✔
259

260
   if(wshift == 0 || (offset + length) / WordInfo<word>::bits == word_offset) {
14,729,631✔
261
      return static_cast<uint32_t>(w0 >> wshift) & mask;
13,964,021✔
262
   } else {
263
      const word w1 = word_at(word_offset + 1);
765,610✔
264
      return static_cast<uint32_t>((w0 >> wshift) | (w1 << (WordInfo<word>::bits - wshift))) & mask;
765,610✔
265
   }
266
}
267

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

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

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

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

298
size_t BigInt::bytes() const {
348,997✔
299
   return round_up(bits(), 8) / 8;
348,997✔
300
}
301

302
size_t BigInt::top_bits_free() const {
2,140,170✔
303
   const size_t words = sig_words();
2,140,170✔
304

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

311
size_t BigInt::bits() const {
1,855,971✔
312
   const size_t words = sig_words();
1,855,971✔
313

314
   if(words == 0) {
1,855,971✔
315
      return 0;
316
   }
317

318
   const size_t full_words = (words - 1) * WordInfo<word>::bits;
1,836,505✔
319
   const size_t top_bits = WordInfo<word>::bits - top_bits_free();
1,836,505✔
320

321
   return full_words + top_bits;
1,836,505✔
322
}
323

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

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

338
   const size_t p_words = p.sig_words();
7,218,073✔
339

340
   if(size() < p_words + 1) {
7,218,073✔
341
      grow_to(p_words + 1);
21,146✔
342
   }
343

344
   if(ws.size() < p_words + 1) {
7,218,073✔
345
      ws.resize(p_words + 1);
303,665✔
346
   }
347

348
   clear_mem(ws.data(), ws.size());
7,218,073✔
349

350
   size_t reductions = 0;
7,218,073✔
351

352
   for(;;) {
11,236,135✔
353
      word borrow = bigint_sub3(ws.data(), _data(), p_words + 1, p._data(), p_words);
18,454,208✔
354
      if(borrow > 0) {
18,454,208✔
355
         break;
356
      }
357

358
      ++reductions;
11,236,135✔
359
      swap_reg(ws);
11,236,135✔
360
   }
361

362
   return reductions;
7,218,073✔
363
}
364

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

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

372
   grow_to(mod_words);
×
373

374
   const size_t sz = size();
×
375

376
   ws.resize(sz);
×
377

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

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

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

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

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

402
   this->binary_encode(output.data(), output.size());
214,183✔
403
}
214,183✔
404

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

412
   for(size_t i = 0; i != full_words; ++i) {
1,867,806✔
413
      const word w = word_at(i);
1,653,618✔
414
      store_be(w, output + (len - (i + 1) * sizeof(word)));
1,653,618✔
415
   }
416

417
   if(extra_bytes > 0) {
214,188✔
418
      const word w = word_at(full_words);
123,272✔
419

420
      for(size_t i = 0; i != extra_bytes; ++i) {
547,172✔
421
         output[extra_bytes - i - 1] = get_byte_var(sizeof(word) - i - 1, w);
423,900✔
422
      }
423
   }
424
}
214,188✔
425

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

432
   const size_t length = bytes.size();
885,927✔
433
   const size_t full_words = length / sizeof(word);
885,927✔
434
   const size_t extra_bytes = length % sizeof(word);
885,927✔
435

436
   secure_vector<word> reg((round_up(full_words + (extra_bytes > 0 ? 1 : 0), 8)));
1,130,939✔
437

438
   for(size_t i = 0; i != full_words; ++i) {
9,009,788✔
439
      reg[i] = load_be<word>(bytes.last<sizeof(word)>());
8,123,861✔
440
      bytes = bytes.first(bytes.size() - sizeof(word));
8,123,861✔
441
   }
442

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

450
   m_data.swap(reg);
885,927✔
451
}
885,927✔
452

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

459
   bigint_cnd_add(static_cast<word>(predicate), this->mutable_data(), this->size(), value._data(), value.sig_words());
3,084,025✔
460
}
3,084,025✔
461

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

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

477
   BOTAN_ASSERT_NOMSG(size() > 0);
30,724✔
478

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

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

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

501
   bigint_cnd_swap(static_cast<word>(predicate), this->mutable_data(), other.mutable_data(), max_words);
11,462,096✔
502
}
11,462,096✔
503

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

507
   const auto mask = CT::Mask<uint8_t>::expand_bool(predicate);
32,965,937✔
508

509
   const uint8_t current_sign = static_cast<uint8_t>(sign());
32,965,937✔
510

511
   const uint8_t new_sign = mask.select(current_sign ^ 1, current_sign);
32,965,937✔
512

513
   set_sign(static_cast<Sign>(new_sign));
32,965,937✔
514
}
32,965,937✔
515

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

520
   if(o_words < t_words) {
32,609,061✔
521
      grow_to(o_words);
363✔
522
   }
523

524
   const size_t r_words = std::max(t_words, o_words);
32,609,061✔
525

526
   const auto mask = CT::Mask<word>::expand_bool(predicate);
32,609,061✔
527

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

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

538
void BigInt::_const_time_poison() const {
3,066,792✔
539
   CT::poison(m_data.const_data(), m_data.size());
3,066,792✔
540
}
3,066,792✔
541

542
void BigInt::_const_time_unpoison() const {
37,445,242✔
543
   CT::unpoison(m_data.const_data(), m_data.size());
37,445,242✔
544
}
37,445,242✔
545

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