Botan  2.7.0
Crypto and TLS for C++11
big_rand.cpp
Go to the documentation of this file.
1 /*
2 * BigInt Random Generation
3 * (C) 1999-2007 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/rng.h>
10 #include <botan/internal/rounding.h>
11 
12 namespace Botan {
13 
14 /*
15 * Randomize this number
16 */
18  size_t bitsize, bool set_high_bit)
19  {
21 
22  if(bitsize == 0)
23  {
24  clear();
25  }
26  else
27  {
28  secure_vector<uint8_t> array = rng.random_vec(round_up(bitsize, 8) / 8);
29 
30  // Always cut unwanted bits
31  if(bitsize % 8)
32  array[0] &= 0xFF >> (8 - (bitsize % 8));
33 
34  // Set the highest bit if wanted
35  if (set_high_bit)
36  array[0] |= 0x80 >> ((bitsize % 8) ? (8 - bitsize % 8) : 0);
37 
38  binary_decode(array);
39  }
40  }
41 
42 /*
43 * Generate a random integer within given range
44 */
46  const BigInt& min, const BigInt& max)
47  {
48  if(min.is_negative() || max.is_negative() || max <= min)
49  throw Invalid_Argument("BigInt::random_integer invalid range");
50 
51  BigInt r;
52 
53  const size_t bits = max.bits();
54 
55  do
56  {
57  r.randomize(rng, bits, false);
58  }
59  while(r < min || r >= max);
60 
61  return r;
62  }
63 
64 }
bool is_negative() const
Definition: bigint.h:460
secure_vector< uint8_t > random_vec(size_t bytes)
Definition: rng.h:132
size_t bits() const
Definition: bigint.cpp:228
void randomize(RandomNumberGenerator &rng, size_t bitsize, bool set_high_bit=true)
Definition: big_rand.cpp:17
static BigInt random_integer(RandomNumberGenerator &rng, const BigInt &min, const BigInt &max)
Definition: big_rand.cpp:45
Definition: alg_id.cpp:13
void clear()
Definition: bigint.h:314
void binary_decode(const uint8_t buf[], size_t length)
Definition: bigint.cpp:326
std::vector< T, secure_allocator< T > > secure_vector
Definition: secmem.h:88
size_t round_up(size_t n, size_t align_to)
Definition: rounding.h:21
void set_sign(Sign sign)
Definition: bigint.h:496