Botan 3.0.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#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(std::string_view 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 input[], size_t length, size_t max_bits)
111 {
112 const size_t input_bits = 8 * length;
113
114 BigInt bn;
115 bn.binary_decode(input, length);
116
117 if(input_bits > max_bits)
118 {
119 const size_t bits_to_shift = input_bits - max_bits;
120
121 bn >>= bits_to_shift;
122 }
123
124 return bn;
125 }
126
127/*
128* Construct a BigInt from an encoded BigInt
129*/
130BigInt::BigInt(RandomNumberGenerator& rng, size_t bits, bool set_high_bit)
131 {
132 randomize(rng, bits, set_high_bit);
133 }
134
135uint8_t BigInt::byte_at(size_t n) const
136 {
137 return get_byte_var(sizeof(word) - (n % sizeof(word)) - 1,
138 word_at(n / sizeof(word)));
139 }
140
141int32_t BigInt::cmp_word(word other) const
142 {
143 if(is_negative())
144 return -1; // other is positive ...
145
146 const size_t sw = this->sig_words();
147 if(sw > 1)
148 return 1; // must be larger since other is just one word ...
149
150 return bigint_cmp(this->data(), sw, &other, 1);
151 }
152
153/*
154* Comparison Function
155*/
156int32_t BigInt::cmp(const BigInt& other, bool check_signs) const
157 {
158 if(check_signs)
159 {
160 if(other.is_positive() && this->is_negative())
161 return -1;
162
163 if(other.is_negative() && this->is_positive())
164 return 1;
165
166 if(other.is_negative() && this->is_negative())
167 return (-bigint_cmp(this->data(), this->size(),
168 other.data(), other.size()));
169 }
170
171 return bigint_cmp(this->data(), this->size(),
172 other.data(), other.size());
173 }
174
175bool BigInt::is_equal(const BigInt& other) const
176 {
177 if(this->sign() != other.sign())
178 return false;
179
180 return bigint_ct_is_eq(this->data(), this->sig_words(),
181 other.data(), other.sig_words()).is_set();
182 }
183
184bool BigInt::is_less_than(const BigInt& other) const
185 {
186 if(this->is_negative() && other.is_positive())
187 return true;
188
189 if(this->is_positive() && other.is_negative())
190 return false;
191
192 if(other.is_negative() && this->is_negative())
193 {
194 return bigint_ct_is_lt(other.data(), other.sig_words(),
195 this->data(), this->sig_words()).is_set();
196 }
197
198 return bigint_ct_is_lt(this->data(), this->sig_words(),
199 other.data(), other.sig_words()).is_set();
200 }
201
202void BigInt::encode_words(word out[], size_t size) const
203 {
204 const size_t words = sig_words();
205
206 if(words > size)
207 throw Encoding_Error("BigInt::encode_words value too large to encode");
208
209 clear_mem(out, size);
210 copy_mem(out, data(), words);
211 }
212
213size_t BigInt::Data::calc_sig_words() const
214 {
215 const size_t sz = m_reg.size();
216 size_t sig = sz;
217
218 word sub = 1;
219
220 for(size_t i = 0; i != sz; ++i)
221 {
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 {
241 if(length == 0 || length > 32)
242 throw Invalid_Argument("BigInt::get_substring invalid substring length");
243
244 const uint32_t mask = 0xFFFFFFFF >> (32 - length);
245
246 const size_t word_offset = offset / BOTAN_MP_WORD_BITS;
247 const size_t wshift = (offset % BOTAN_MP_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) / BOTAN_MP_WORD_BITS == word_offset)
257 {
258 return static_cast<uint32_t>(w0 >> wshift) & mask;
259 }
260 else
261 {
262 const word w1 = word_at(word_offset + 1);
263 return static_cast<uint32_t>((w0 >> wshift) | (w1 << (BOTAN_MP_WORD_BITS - wshift))) & mask;
264 }
265 }
266
267/*
268* Convert this number to a uint32_t, if possible
269*/
270uint32_t BigInt::to_u32bit() const
271 {
272 if(is_negative())
273 throw Encoding_Error("BigInt::to_u32bit: Number is negative");
274 if(bits() > 32)
275 throw Encoding_Error("BigInt::to_u32bit: Number is too big to convert");
276
277 uint32_t out = 0;
278 for(size_t i = 0; i != 4; ++i)
279 out = (out << 8) | byte_at(3-i);
280 return out;
281 }
282
283/*
284* Clear bit number n
285*/
286void BigInt::clear_bit(size_t n)
287 {
288 const size_t which = n / BOTAN_MP_WORD_BITS;
289
290 if(which < size())
291 {
292 const word mask = ~(static_cast<word>(1) << (n % BOTAN_MP_WORD_BITS));
293 m_data.set_word_at(which, word_at(which) & mask);
294 }
295 }
296
297size_t BigInt::bytes() const
298 {
299 return round_up(bits(), 8) / 8;
300 }
301
303 {
304 const size_t words = sig_words();
305
306 const word top_word = word_at(words - 1);
307 const size_t bits_used = high_bit(top_word);
308 CT::unpoison(bits_used);
309 return BOTAN_MP_WORD_BITS - bits_used;
310 }
311
312size_t BigInt::bits() const
313 {
314 const size_t words = sig_words();
315
316 if(words == 0)
317 return 0;
318
319 const size_t full_words = (words - 1) * BOTAN_MP_WORD_BITS;
320 const size_t top_bits = BOTAN_MP_WORD_BITS - top_bits_free();
321
322 return full_words + top_bits;
323 }
324
325/*
326* Return the negation of this number
327*/
329 {
330 BigInt x = (*this);
331 x.flip_sign();
332 return x;
333 }
334
336 {
337 if(p.is_negative() || this->is_negative())
338 throw Invalid_Argument("BigInt::reduce_below both values must be positive");
339
340 const size_t p_words = p.sig_words();
341
342 if(size() < p_words + 1)
343 grow_to(p_words + 1);
344
345 if(ws.size() < p_words + 1)
346 ws.resize(p_words + 1);
347
348 clear_mem(ws.data(), ws.size());
349
350 size_t reductions = 0;
351
352 for(;;)
353 {
354 word borrow = bigint_sub3(ws.data(), data(), p_words + 1, p.data(), p_words);
355 if(borrow)
356 break;
357
358 ++reductions;
359 swap_reg(ws);
360 }
361
362 return reductions;
363 }
364
365void BigInt::ct_reduce_below(const BigInt& mod, secure_vector<word>& ws, size_t bound)
366 {
367 if(mod.is_negative() || this->is_negative())
368 throw Invalid_Argument("BigInt::ct_reduce_below both values must be positive");
369
370 const size_t mod_words = mod.sig_words();
371
372 grow_to(mod_words);
373
374 const size_t sz = size();
375
376 ws.resize(sz);
377
378 clear_mem(ws.data(), sz);
379
380 for(size_t i = 0; i != bound; ++i)
381 {
382 word borrow = bigint_sub3(ws.data(), data(), sz, mod.data(), mod_words);
383
384 CT::Mask<word>::is_zero(borrow).select_n(mutable_data(), ws.data(), data(), sz);
385 }
386 }
387
388/*
389* Return the absolute value of this number
390*/
392 {
393 BigInt x = (*this);
395 return x;
396 }
397
398void BigInt::binary_encode(uint8_t buf[]) const
399 {
400 this->binary_encode(buf, bytes());
401 }
402
403/*
404* Encode this number into bytes
405*/
406void BigInt::binary_encode(uint8_t output[], size_t len) const
407 {
408 const size_t full_words = len / sizeof(word);
409 const size_t extra_bytes = len % sizeof(word);
410
411 for(size_t i = 0; i != full_words; ++i)
412 {
413 const word w = word_at(i);
414 store_be(w, output + (len - (i+1)*sizeof(word)));
415 }
416
417 if(extra_bytes > 0)
418 {
419 const word w = word_at(full_words);
420
421 for(size_t i = 0; i != extra_bytes; ++i)
422 {
423 output[extra_bytes - i - 1] = get_byte_var(sizeof(word) - i - 1, w);
424 }
425 }
426 }
427
428/*
429* Set this number to the value in buf
430*/
431void BigInt::binary_decode(const uint8_t buf[], size_t length)
432 {
433 clear();
434
435 const size_t full_words = length / sizeof(word);
436 const size_t extra_bytes = length % sizeof(word);
437
438 secure_vector<word> reg((round_up(full_words + (extra_bytes > 0 ? 1 : 0), 8)));
439
440 for(size_t i = 0; i != full_words; ++i)
441 {
442 reg[i] = load_be<word>(buf + length - sizeof(word)*(i+1), 0);
443 }
444
445 if(extra_bytes > 0)
446 {
447 for(size_t i = 0; i != extra_bytes; ++i)
448 reg[full_words] = (reg[full_words] << 8) | buf[i];
449 }
450
451 m_data.swap(reg);
452 }
453
454void BigInt::ct_cond_add(bool predicate, const BigInt& value)
455 {
456 if(this->is_negative() || value.is_negative())
457 throw Invalid_Argument("BigInt::ct_cond_add requires both values to be positive");
458 this->grow_to(1 + value.sig_words());
459
460 bigint_cnd_add(static_cast<word>(predicate),
461 this->mutable_data(), this->size(),
462 value.data(), value.sig_words());
463 }
464
465void BigInt::ct_cond_swap(bool predicate, BigInt& other)
466 {
467 const size_t max_words = std::max(size(), other.size());
468 grow_to(max_words);
469 other.grow_to(max_words);
470
471 bigint_cnd_swap(predicate, this->mutable_data(), other.mutable_data(), max_words);
472 }
473
474void BigInt::cond_flip_sign(bool predicate)
475 {
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 {
489 const size_t t_words = size();
490 const size_t o_words = other.size();
491
492 if(o_words < t_words)
493 grow_to(o_words);
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 {
501 const word o_word = other.word_at(i);
502 const word t_word = this->word_at(i);
503 this->set_word_at(i, mask.select(o_word, t_word));
504 }
505
506 const bool different_sign = sign() != other.sign();
507 cond_flip_sign(predicate && different_sign);
508 }
509
510#if defined(BOTAN_HAS_VALGRIND)
511void BigInt::const_time_poison() const
512 {
513 CT::poison(m_data.const_data(), m_data.size());
514 }
515
517 {
518 CT::unpoison(m_data.const_data(), m_data.size());
519 }
520#endif
521
522}
void ct_cond_add(bool predicate, const BigInt &value)
Definition: bigint.cpp:454
size_t sig_words() const
Definition: bigint.h:615
void binary_decode(const uint8_t buf[], size_t length)
Definition: bigint.cpp:431
BigInt()=default
bool is_equal(const BigInt &n) const
Definition: bigint.cpp:175
static BigInt decode(const uint8_t buf[], size_t length)
Definition: bigint.h:805
@ Hexadecimal
Definition: bigint.h:30
void set_word_at(size_t i, word w)
Definition: bigint.h:542
word * mutable_data()
Definition: bigint.h:643
void ct_cond_assign(bool predicate, const BigInt &other)
Definition: bigint.cpp:487
size_t size() const
Definition: bigint.h:609
void grow_to(size_t n) const
Definition: bigint.h:665
uint32_t to_u32bit() const
Definition: bigint.cpp:270
void flip_sign()
Definition: bigint.h:583
size_t top_bits_free() const
Definition: bigint.cpp:302
void ct_reduce_below(const BigInt &mod, secure_vector< word > &ws, size_t bound)
Definition: bigint.cpp:365
bool is_less_than(const BigInt &n) const
Definition: bigint.cpp:184
int32_t cmp(const BigInt &n, bool check_signs=true) const
Definition: bigint.cpp:156
const word * data() const
Definition: bigint.h:649
void binary_encode(uint8_t buf[]) const
Definition: bigint.cpp:398
word word_at(size_t n) const
Definition: bigint.h:537
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:141
void cond_flip_sign(bool predicate)
Definition: bigint.cpp:474
size_t bits() const
Definition: bigint.cpp:312
BigInt operator-() const
Definition: bigint.cpp:328
uint8_t byte_at(size_t n) const
Definition: bigint.cpp:135
static BigInt from_u64(uint64_t n)
Definition: bigint.cpp:28
void clear()
Definition: bigint.h:379
void clear_bit(size_t n)
Definition: bigint.cpp:286
Sign sign() const
Definition: bigint.h:568
void const_time_poison() const
Definition: bigint.h:749
void encode_words(word out[], size_t size) const
Definition: bigint.cpp:202
static BigInt from_s32(int32_t n)
Definition: bigint.cpp:51
void ct_cond_swap(bool predicate, BigInt &other)
Definition: bigint.cpp:465
BigInt abs() const
Definition: bigint.cpp:391
static BigInt from_word(word n)
Definition: bigint.cpp:43
size_t reduce_below(const BigInt &mod, secure_vector< word > &ws)
Definition: bigint.cpp:335
bool is_negative() const
Definition: bigint.h:556
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:297
void const_time_unpoison() const
Definition: bigint.h:750
bool is_positive() const
Definition: bigint.h:562
static BigInt with_capacity(size_t n)
Definition: bigint.cpp:60
void swap_reg(secure_vector< word > &reg)
Definition: bigint.h:180
void set_sign(Sign sign)
Definition: bigint.h:592
uint32_t get_substring(size_t offset, size_t length) const
Definition: bigint.cpp:239
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:50
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:12
word bigint_cnd_add(word cnd, word x[], word x_size, const word y[], size_t y_size)
Definition: mp_core.h:42
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
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:580
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:529
constexpr T ct_is_zero(T x)
Definition: bit_ops.h:33
std::vector< T, secure_allocator< T > > secure_vector
Definition: secmem.h:64
word bigint_sub3(word z[], const word x[], size_t x_size, const word y[], size_t y_size)
Definition: mp_core.h:346
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:617
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