Botan 2.1.0 Crypto and TLS for C++11

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

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/parsing.h>
10 #include <botan/internal/rounding.h>
11
12 namespace Botan {
13
14 /*
15 * Randomize this number
16 */
17 void BigInt::randomize(RandomNumberGenerator& rng,
18 size_t bitsize, bool set_high_bit)
19 {
20 set_sign(Positive);
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 */
45 BigInt BigInt::random_integer(RandomNumberGenerator& rng,
46 const BigInt& min, const BigInt& max)
47 {
48 BigInt r;
49
50 const size_t bits = max.bits();
51
52 do
53 {
54 r.randomize(rng, bits, false);
55 }
56 while(r < min || r >= max);
57
58 return r;
59 }
60
61 }
Botan::BigInt
Definition: bigint.h:23
Botan::RandomNumberGenerator::random_vec
secure_vector< uint8_t > random_vec(size_t bytes)
Definition: rng.h:133
Botan::BigInt::Positive
Definition: bigint.h:34
Botan::RandomNumberGenerator
Definition: rng.h:25
Botan::BigInt::randomize
void randomize(RandomNumberGenerator &rng, size_t bitsize, bool set_high_bit=true)
Definition: big_rand.cpp:17
Botan::BigInt::random_integer
static BigInt random_integer(RandomNumberGenerator &rng, const BigInt &min, const BigInt &max)
Definition: big_rand.cpp:45
Botan::BigInt::bits
size_t bits() const
Definition: bigint.cpp:184
Botan::secure_vector
std::vector< T, secure_allocator< T >> secure_vector
Definition: secmem.h:121
Botan
Definition: alg_id.cpp:13
Botan::CT::max
T max(T a, T b)
Definition: ct_utils.h:173
Botan::BigInt::clear
void clear()
Definition: bigint.h:217
Botan::CT::min
T min(T a, T b)
Definition: ct_utils.h:180
Botan::BigInt::binary_decode
void binary_decode(const uint8_t buf[], size_t length)
Definition: bigint.cpp:280
Botan::round_up
size_t round_up(size_t n, size_t align_to)
Definition: rounding.h:22
Botan::BigInt::set_sign
void set_sign(Sign sign)
Definition: bigint.cpp:215