Coverage Report

Created: 2026-10-28 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/botan/src/lib/math/bigint/big_rand.cpp
Line
Count
Source
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
15.1k
void BigInt::randomize(RandomNumberGenerator& rng, size_t bitsize, bool set_high_bit) {
19
15.1k
   set_sign(Positive);
20
21
15.1k
   if(bitsize == 0) {
22
0
      clear();
23
15.1k
   } else {
24
15.1k
      secure_vector<uint8_t> array = rng.random_vec(round_up(bitsize, 8) / 8);
25
26
      // Always cut unwanted bits
27
15.1k
      if(bitsize % 8 > 0) {
28
2.52k
         array[0] &= 0xFF >> (8 - (bitsize % 8));
29
2.52k
      }
30
31
      // Set the highest bit if wanted
32
15.1k
      if(set_high_bit) {
33
534
         array[0] |= 0x80 >> ((bitsize % 8) > 0 ? (8 - bitsize % 8) : 0);
34
534
      }
35
36
15.1k
      assign_from_bytes(array);
37
15.1k
   }
38
15.1k
}
39
40
/*
41
* Generate a random integer within given range
42
*/
43
27.0k
BigInt BigInt::random_integer(RandomNumberGenerator& rng, const BigInt& min, const BigInt& max) {
44
27.0k
   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 reasonably chosen for min == 1, but
53
   that breaks certain tests which expect stability of this function
54
   when generating within [1,n)
55
   */
56
27.0k
   if(min > 1) {
57
13.2k
      const BigInt diff = max - min;
58
      // This call is recursive, but will not recurse further
59
13.2k
      return min + BigInt::random_integer(rng, BigInt::zero(), diff);
60
13.2k
   }
61
62
13.7k
   BOTAN_DEBUG_ASSERT(min <= 1);
63
64
13.7k
   const size_t bits = max.bits();
65
66
14.4k
   for(;;) {
67
14.4k
      BigInt r;
68
14.4k
      r.randomize(rng, bits, false);
69
14.4k
      if(r >= min && r < max) {
70
13.3k
         return r;
71
13.3k
      }
72
14.4k
   }
73
13.7k
}
74
75
}  // namespace Botan