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