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