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