/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  | 576k  | void BigInt::randomize(RandomNumberGenerator& rng, size_t bitsize, bool set_high_bit) { | 
19  | 576k  |    set_sign(Positive);  | 
20  |  |  | 
21  | 576k  |    if(bitsize == 0) { | 
22  | 0  |       clear();  | 
23  | 576k  |    } else { | 
24  | 576k  |       secure_vector<uint8_t> array = rng.random_vec(round_up(bitsize, 8) / 8);  | 
25  |  |  | 
26  |  |       // Always cut unwanted bits  | 
27  | 576k  |       if(bitsize % 8) { | 
28  | 339k  |          array[0] &= 0xFF >> (8 - (bitsize % 8));  | 
29  | 339k  |       }  | 
30  |  |  | 
31  |  |       // Set the highest bit if wanted  | 
32  | 576k  |       if(set_high_bit) { | 
33  | 34.4k  |          array[0] |= 0x80 >> ((bitsize % 8) ? (8 - bitsize % 8) : 0);  | 
34  | 34.4k  |       }  | 
35  |  |  | 
36  | 576k  |       binary_decode(array);  | 
37  | 576k  |    }  | 
38  | 576k  | }  | 
39  |  |  | 
40  |  | /*  | 
41  |  | * Generate a random integer within given range  | 
42  |  | */  | 
43  | 159k  | BigInt BigInt::random_integer(RandomNumberGenerator& rng, const BigInt& min, const BigInt& max) { | 
44  | 159k  |    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  | 159k  |    if(min > 1) { | 
57  | 70.3k  |       const BigInt diff = max - min;  | 
58  |  |       // This call is recursive, but will not recurse further  | 
59  | 70.3k  |       return min + BigInt::random_integer(rng, BigInt::zero(), diff);  | 
60  | 70.3k  |    }  | 
61  |  |  | 
62  | 89.1k  |    BOTAN_DEBUG_ASSERT(min <= 1);  | 
63  |  |  | 
64  | 89.1k  |    const size_t bits = max.bits();  | 
65  |  |  | 
66  | 89.1k  |    BigInt r;  | 
67  |  |  | 
68  | 104k  |    do { | 
69  | 104k  |       r.randomize(rng, bits, false);  | 
70  | 104k  |    } while(r < min || r >= max);  | 
71  |  |  | 
72  | 89.1k  |    return r;  | 
73  | 159k  | }  | 
74  |  |  | 
75  |  | }  // namespace Botan  |