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