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