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