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