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