monotone

monotone Mtn Source Tree

Root/botan/make_prm.cpp

1/*************************************************
2* Prime Generation Source File *
3* (C) 1999-2007 The Botan Project *
4*************************************************/
5
6#include <botan/numthry.h>
7#include <botan/parsing.h>
8#include <botan/libstate.h>
9#include <algorithm>
10
11namespace Botan {
12
13/*************************************************
14* Generate a random prime *
15*************************************************/
16BigInt random_prime(u32bit bits, const BigInt& coprime,
17 u32bit equiv, u32bit modulo)
18 {
19 if(bits < 48)
20 throw Invalid_Argument("random_prime: Can't make a prime of " +
21 to_string(bits) + " bits");
22
23 if(coprime <= 0)
24 throw Invalid_Argument("random_prime: coprime must be > 0");
25 if(modulo % 2 == 1 || modulo == 0)
26 throw Invalid_Argument("random_prime: Invalid modulo value");
27 if(equiv >= modulo || equiv % 2 == 0)
28 throw Invalid_Argument("random_prime: equiv must be < modulo, and odd");
29
30 while(true)
31 {
32 global_state().pulse(PRIME_SEARCHING);
33
34 BigInt p = random_integer(bits);
35 p.set_bit(bits - 2);
36 p.set_bit(0);
37
38 if(p % modulo != equiv)
39 p += (modulo - p % modulo) + equiv;
40
41 const u32bit sieve_size = std::min(bits / 2, PRIME_TABLE_SIZE);
42 SecureVector<u32bit> sieve(sieve_size);
43
44 for(u32bit j = 0; j != sieve.size(); ++j)
45 {
46 sieve[j] = p % PRIMES[j];
47 global_state().pulse(PRIME_SIEVING);
48 }
49
50 u32bit counter = 0;
51 while(true)
52 {
53 if(counter == 4096 || p.bits() > bits)
54 break;
55
56 global_state().pulse(PRIME_SEARCHING);
57
58 bool passes_sieve = true;
59 ++counter;
60 p += modulo;
61
62 for(u32bit j = 0; j != sieve.size(); ++j)
63 {
64 sieve[j] = (sieve[j] + modulo) % PRIMES[j];
65 global_state().pulse(PRIME_SIEVING);
66 if(sieve[j] == 0)
67 passes_sieve = false;
68 }
69
70 if(!passes_sieve || gcd(p - 1, coprime) != 1)
71 continue;
72 global_state().pulse(PRIME_PASSED_SIEVE);
73 if(passes_mr_tests(p))
74 {
75 global_state().pulse(PRIME_FOUND);
76 return p;
77 }
78 }
79 }
80 }
81
82}

Archive Download this file

Branches

Tags

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