monotone

monotone Mtn Source Tree

Root/botan/big_rand.cpp

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

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status