Botan  1.10.9
big_rand.cpp
Go to the documentation of this file.
1 /*
2 * BigInt Random Generation
3 * (C) 1999-2007 Jack Lloyd
4 *
5 * Distributed under the terms of the Botan license
6 */
7 
8 #include <botan/bigint.h>
9 #include <botan/parsing.h>
10 
11 namespace Botan {
12 
13 /*
14 * Construct a BigInt of a specific form
15 */
16 BigInt::BigInt(NumberType type, size_t bits)
17  {
19 
20  if(type == Power2)
21  set_bit(bits);
22  else
23  throw Invalid_Argument("BigInt(NumberType): Unknown type");
24  }
25 
26 /*
27 * Randomize this number
28 */
30  size_t bitsize)
31  {
33 
34  if(bitsize == 0)
35  clear();
36  else
37  {
38  SecureVector<byte> array = rng.random_vec((bitsize + 7) / 8);
39 
40  if(bitsize % 8)
41  array[0] &= 0xFF >> (8 - (bitsize % 8));
42  array[0] |= 0x80 >> ((bitsize % 8) ? (8 - bitsize % 8) : 0);
43  binary_decode(&array[0], array.size());
44  }
45  }
46 
47 /*
48 * Generate a random integer within given range
49 */
51  const BigInt& min, const BigInt& max)
52  {
53  BigInt range = max - min;
54 
55  if(range <= 0)
56  throw Invalid_Argument("random_integer: invalid min/max values");
57 
58  return (min + (BigInt(rng, range.bits() + 2) % range));
59  }
60 
61 }
SecureVector< byte > random_vec(size_t bytes)
Definition: rng.h:40
void binary_decode(const byte buf[], size_t length)
Definition: bigint.cpp:350
void set_bit(size_t n)
Definition: bigint.cpp:205
std::invalid_argument Invalid_Argument
Definition: exceptn.h:20
static BigInt random_integer(RandomNumberGenerator &rng, const BigInt &min, const BigInt &max)
Definition: big_rand.cpp:50
size_t bits() const
Definition: bigint.cpp:253
RandomNumberGenerator * rng
Definition: global_rng.cpp:165
void randomize(RandomNumberGenerator &rng, size_t bitsize=0)
Definition: big_rand.cpp:29
size_t size() const
Definition: secmem.h:29
void clear()
Definition: bigint.h:143
void set_sign(Sign sign)
Definition: bigint.cpp:291