Botan 1.10.17

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 {
18 set_sign(Positive);
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 */
29 void BigInt::randomize(RandomNumberGenerator& rng,
30 size_t bitsize)
31 {
32 set_sign(Positive);
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 */
50 BigInt BigInt::random_integer(RandomNumberGenerator& rng,
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 }
Botan::BigInt
Definition: bigint.h:22
Botan::BigInt::Positive
Definition: bigint.h:33
Botan::RandomNumberGenerator
Definition: rng.h:20
Botan::BigInt::bits
size_t bits() const
Definition: bigint.cpp:254
Botan::BigInt::binary_decode
void binary_decode(const byte buf[], size_t length)
Definition: bigint.cpp:351
Botan::BigInt::set_bit
void set_bit(size_t n)
Definition: bigint.cpp:206
Botan::BigInt::NumberType
NumberType
Definition: bigint.h:38
Botan::Invalid_Argument
std::invalid_argument Invalid_Argument
Definition: exceptn.h:20
Botan::BigInt::random_integer
static BigInt random_integer(RandomNumberGenerator &rng, const BigInt &min, const BigInt &max)
Definition: big_rand.cpp:50
Botan::BigInt::randomize
void randomize(RandomNumberGenerator &rng, size_t bitsize=0)
Definition: big_rand.cpp:29
Botan
Definition: algo_base.h:14
Botan::CT::max
T max(T a, T b)
Definition: ct_utils.h:120
Botan::BigInt::clear
void clear()
Definition: bigint.h:143
Botan::MemoryRegion::size
size_t size() const
Definition: secmem.h:29
Botan::BigInt::BigInt
BigInt()
Definition: bigint.h:446
Botan::CT::min
T min(T a, T b)
Definition: ct_utils.h:127
Botan::SecureVector< byte >
Botan::BigInt::Power2
Definition: bigint.h:38
Botan::BigInt::set_sign
void set_sign(Sign sign)
Definition: bigint.cpp:292