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