Botan 3.4.0
Crypto and TLS for C&
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
10#include <botan/rng.h>
11#include <botan/internal/rounding.h>
12
13namespace Botan {
14
15/*
16* Randomize this number
17*/
18void BigInt::randomize(RandomNumberGenerator& rng, size_t bitsize, bool set_high_bit) {
20
21 if(bitsize == 0) {
22 clear();
23 } else {
24 secure_vector<uint8_t> array = rng.random_vec(round_up(bitsize, 8) / 8);
25
26 // Always cut unwanted bits
27 if(bitsize % 8) {
28 array[0] &= 0xFF >> (8 - (bitsize % 8));
29 }
30
31 // Set the highest bit if wanted
32 if(set_high_bit) {
33 array[0] |= 0x80 >> ((bitsize % 8) ? (8 - bitsize % 8) : 0);
34 }
35
36 binary_decode(array);
37 }
38}
39
40/*
41* Generate a random integer within given range
42*/
44 if(min.is_negative() || max.is_negative() || max <= min) {
45 throw Invalid_Argument("BigInt::random_integer invalid range");
46 }
47
48 /*
49 If min is > 1 then we generate a random number `r` in [0,max-min)
50 and return min + r.
51
52 This same logic could also be reasonbly chosen for min == 1, but
53 that breaks certain tests which expect stability of this function
54 when generating within [1,n)
55 */
56 if(min > 1) {
57 const BigInt diff = max - min;
58 // This call is recursive, but will not recurse further
59 return min + BigInt::random_integer(rng, BigInt::zero(), diff);
60 }
61
62 BOTAN_DEBUG_ASSERT(min <= 1);
63
64 const size_t bits = max.bits();
65
66 BigInt r;
67
68 do {
69 r.randomize(rng, bits, false);
70 } while(r < min || r >= max);
71
72 return r;
73}
74
75} // namespace Botan
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:98
static BigInt zero()
Definition bigint.h:46
void binary_decode(const uint8_t buf[], size_t length)
Definition bigint.cpp:403
static BigInt random_integer(RandomNumberGenerator &rng, const BigInt &min, const BigInt &max)
Definition big_rand.cpp:43
void randomize(RandomNumberGenerator &rng, size_t bitsize, bool set_high_bit=true)
Definition big_rand.cpp:18
size_t bits() const
Definition bigint.cpp:290
void clear()
Definition bigint.h:370
bool is_negative() const
Definition bigint.h:528
void set_sign(Sign sign)
Definition bigint.h:561
void random_vec(std::span< uint8_t > v)
Definition rng.h:179
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:61
size_t round_up(size_t n, size_t align_to)
Definition rounding.h:21