/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  |  | #include <botan/rng.h>  | 
10  |  | #include <botan/internal/rounding.h>  | 
11  |  |  | 
12  |  | namespace Botan { | 
13  |  |  | 
14  |  | /*  | 
15  |  | * Randomize this number  | 
16  |  | */  | 
17  |  | void BigInt::randomize(RandomNumberGenerator& rng,  | 
18  |  |                        size_t bitsize, bool set_high_bit)  | 
19  | 2.35k  |    { | 
20  | 2.35k  |    set_sign(Positive);  | 
21  |  |  | 
22  | 2.35k  |    if(bitsize == 0)  | 
23  | 0  |       { | 
24  | 0  |       clear();  | 
25  | 0  |       }  | 
26  | 2.35k  |    else  | 
27  | 2.35k  |       { | 
28  | 2.35k  |       secure_vector<uint8_t> array = rng.random_vec(round_up(bitsize, 8) / 8);  | 
29  |  |  | 
30  |  |       // Always cut unwanted bits  | 
31  | 2.35k  |       if(bitsize % 8)  | 
32  | 868  |          array[0] &= 0xFF >> (8 - (bitsize % 8));  | 
33  |  |  | 
34  |  |       // Set the highest bit if wanted  | 
35  | 2.35k  |       if (set_high_bit)  | 
36  | 625  |          array[0] |= 0x80 >> ((bitsize % 8) ? (8 - bitsize % 8) : 0);  | 
37  |  |  | 
38  | 2.35k  |       binary_decode(array);  | 
39  | 2.35k  |       }  | 
40  | 2.35k  |    }  | 
41  |  |  | 
42  |  | /*  | 
43  |  | * Generate a random integer within given range  | 
44  |  | */  | 
45  |  | BigInt BigInt::random_integer(RandomNumberGenerator& rng,  | 
46  |  |                               const BigInt& min, const BigInt& max)  | 
47  | 800  |    { | 
48  | 800  |    if(min.is_negative() || max.is_negative() || max <= min)  | 
49  | 0  |       throw Invalid_Argument("BigInt::random_integer invalid range"); | 
50  |  |  | 
51  | 800  |    BigInt r;  | 
52  |  |  | 
53  | 800  |    const size_t bits = max.bits();  | 
54  |  |  | 
55  | 800  |    do  | 
56  | 1.03k  |       { | 
57  | 1.03k  |       r.randomize(rng, bits, false);  | 
58  | 1.03k  |       }  | 
59  | 1.03k  |    while(r < min || r >= max);  | 
60  |  |  | 
61  | 800  |    return r;  | 
62  | 800  |    }  | 
63  |  |  | 
64  |  | }  |