blob: 5e6ec594bd1199ad7fdfadd455e2d90de862c6a7 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
/*************************************************
* BigInt Random Generation Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/bigint.h>
#include <botan/parsing.h>
#include <botan/numthry.h>
namespace Botan {
/*************************************************
* Construct a BigInt of a specific form *
*************************************************/
BigInt::BigInt(NumberType type, u32bit bits)
{
set_sign(Positive);
if(type == Power2)
set_bit(bits);
else
throw Invalid_Argument("BigInt(NumberType): Unknown type");
}
/*************************************************
* Randomize this number *
*************************************************/
void BigInt::randomize(RandomNumberGenerator& rng,
u32bit bitsize)
{
set_sign(Positive);
if(bitsize == 0)
clear();
else
{
SecureVector<byte> array((bitsize + 7) / 8);
rng.randomize(array, array.size());
if(bitsize % 8)
array[0] &= 0xFF >> (8 - (bitsize % 8));
array[0] |= 0x80 >> ((bitsize % 8) ? (8 - bitsize % 8) : 0);
binary_decode(array, array.size());
}
}
/*************************************************
* Generate a random integer *
*************************************************/
BigInt random_integer(RandomNumberGenerator& rng,
u32bit bits)
{
BigInt x;
x.randomize(rng, bits);
return x;
}
/*************************************************
* Generate a random integer within given range *
*************************************************/
BigInt random_integer(RandomNumberGenerator& rng,
const BigInt& min, const BigInt& max)
{
BigInt range = max - min;
if(range <= 0)
throw Invalid_Argument("random_integer: invalid min/max values");
return (min + (random_integer(rng, range.bits() + 2) % range));
}
/*************************************************
* Generate a random safe prime *
*************************************************/
BigInt random_safe_prime(RandomNumberGenerator& rng, u32bit bits)
{
if(bits <= 64)
throw Invalid_Argument("random_safe_prime: Can't make a prime of " +
to_string(bits) + " bits");
BigInt p;
do
p = (random_prime(rng, bits - 1) << 1) + 1;
while(!is_prime(p, rng));
return p;
}
}
|