Coverage Report

Created: 2024-11-29 06:10

/src/botan/src/lib/math/bigint/big_rand.cpp
Line
Count
Source (jump to first uncovered line)
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
13
namespace Botan {
14
15
/*
16
* Randomize this number
17
*/
18
53
void BigInt::randomize(RandomNumberGenerator& rng, size_t bitsize, bool set_high_bit) {
19
53
   set_sign(Positive);
20
21
53
   if(bitsize == 0) {
22
0
      clear();
23
53
   } else {
24
53
      secure_vector<uint8_t> array = rng.random_vec(round_up(bitsize, 8) / 8);
25
26
      // Always cut unwanted bits
27
53
      if(bitsize % 8) {
28
0
         array[0] &= 0xFF >> (8 - (bitsize % 8));
29
0
      }
30
31
      // Set the highest bit if wanted
32
53
      if(set_high_bit) {
33
1
         array[0] |= 0x80 >> ((bitsize % 8) ? (8 - bitsize % 8) : 0);
34
1
      }
35
36
53
      assign_from_bytes(array);
37
53
   }
38
53
}
39
40
/*
41
* Generate a random integer within given range
42
*/
43
86
BigInt BigInt::random_integer(RandomNumberGenerator& rng, const BigInt& min, const BigInt& max) {
44
86
   if(min.is_negative() || max.is_negative() || max <= min) {
45
0
      throw Invalid_Argument("BigInt::random_integer invalid range");
46
0
   }
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
86
   if(min > 1) {
57
43
      const BigInt diff = max - min;
58
      // This call is recursive, but will not recurse further
59
43
      return min + BigInt::random_integer(rng, BigInt::zero(), diff);
60
43
   }
61
62
43
   BOTAN_DEBUG_ASSERT(min <= 1);
63
64
43
   const size_t bits = max.bits();
65
66
43
   BigInt r;
67
68
52
   do {
69
52
      r.randomize(rng, bits, false);
70
52
   } while(r < min || r >= max);
71
72
43
   return r;
73
86
}
74
75
}  // namespace Botan