File Coverage

blib/lib/Math/Prime/Util/RandomPrimes.pm
Criterion Covered Total %
statement 264 339 77.8
branch 104 206 50.4
condition 44 80 55.0
subroutine 24 28 85.7
pod 9 9 100.0
total 445 662 67.2


line stmt bran cond sub pod time code
1             package Math::Prime::Util::RandomPrimes;
2 4     4   25 use strict;
  4         9  
  4         107  
3 4     4   18 use warnings;
  4         8  
  4         102  
4 4     4   17 use Carp qw/carp croak confess/;
  4         9  
  4         245  
5 4         25 use Math::Prime::Util qw/ prime_get_config
6             verify_prime
7             is_provable_prime_with_cert
8             primorial prime_count nth_prime
9             is_prob_prime is_strong_pseudoprime
10             next_prime prev_prime
11             urandomb urandomm random_bytes
12 4     4   21 /;
  4         6  
13              
14             BEGIN {
15 4     4   14 $Math::Prime::Util::RandomPrimes::AUTHORITY = 'cpan:DANAJ';
16 4         200 $Math::Prime::Util::RandomPrimes::VERSION = '0.68';
17             }
18              
19             BEGIN {
20 4 50   4   25 do { require Math::BigInt; Math::BigInt->import(try=>"GMP,Pari"); }
  0         0  
  0         0  
21             unless defined $Math::BigInt::VERSION;
22              
23 4     4   22 use constant OLD_PERL_VERSION=> $] < 5.008;
  4         6  
  4         284  
24 4     4   20 use constant MPU_MAXBITS => (~0 == 4294967295) ? 32 : 64;
  4         8  
  4         174  
25 4     4   20 use constant MPU_64BIT => MPU_MAXBITS == 64;
  4         7  
  4         166  
26 4     4   20 use constant MPU_32BIT => MPU_MAXBITS == 32;
  4         8  
  4         161  
27 4     4   19 use constant MPU_MAXPARAM => MPU_32BIT ? 4294967295 : 18446744073709551615;
  4         7  
  4         169  
28 4     4   21 use constant MPU_MAXDIGITS => MPU_32BIT ? 10 : 20;
  4         6  
  4         196  
29 4     4   21 use constant MPU_USE_XS => prime_get_config->{'xs'};
  4         7  
  4         13  
30 4     4   19 use constant MPU_USE_GMP => prime_get_config->{'gmp'};
  4         8  
  4         13  
31              
32 4         14952 *_bigint_to_int = \&Math::Prime::Util::_bigint_to_int;
33             }
34              
35             ################################################################################
36              
37             # These are much faster than straightforward trial division when n is big.
38             # You'll want to first do a test up to and including 23.
39             my @_big_gcd;
40             my $_big_gcd_top = 20046;
41             my $_big_gcd_use = -1;
42             sub _make_big_gcds {
43 3 50   3   17 return if $_big_gcd_use >= 0;
44 3 50       14 if (prime_get_config->{'gmp'}) {
45 0         0 $_big_gcd_use = 0;
46 0         0 return;
47             }
48 3 50       20 if (Math::BigInt->config()->{lib} !~ /^Math::BigInt::(GMP|Pari)/) {
49 3         154 $_big_gcd_use = 0;
50 3         7 return;
51             }
52 0         0 $_big_gcd_use = 1;
53 0         0 my $p0 = primorial(Math::BigInt->new( 520));
54 0         0 my $p1 = primorial(Math::BigInt->new(2052));
55 0         0 my $p2 = primorial(Math::BigInt->new(6028));
56 0         0 my $p3 = primorial(Math::BigInt->new($_big_gcd_top));
57 0         0 $_big_gcd[0] = $p0->bdiv(223092870)->bfloor->as_int;
58 0         0 $_big_gcd[1] = $p1->bdiv($p0)->bfloor->as_int;
59 0         0 $_big_gcd[2] = $p2->bdiv($p1)->bfloor->as_int;
60 0         0 $_big_gcd[3] = $p3->bdiv($p2)->bfloor->as_int;
61             }
62              
63             ################################################################################
64              
65              
66             ################################################################################
67              
68              
69              
70             # For random primes, there are two good papers that should be examined:
71             #
72             # "Fast Generation of Prime Numbers and Secure Public-Key
73             # Cryptographic Parameters" by Ueli M. Maurer, 1995
74             # http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.26.2151
75             # related discussions:
76             # http://www.daimi.au.dk/~ivan/provableprimesproject.pdf
77             # Handbook of Applied Cryptography by Menezes, et al.
78             #
79             # "Close to Uniform Prime Number Generation With Fewer Random Bits"
80             # by Pierre-Alain Fouque and Mehdi Tibouchi, 2011
81             # http://eprint.iacr.org/2011/481
82             #
83             # Some things to note:
84             #
85             # 1) Joye and Paillier have patents on their methods. Never use them.
86             #
87             # 2) The easy method of next_prime(random number), known as PRIMEINC, is
88             # fast but gives a terrible distribution. It has a positive bias and
89             # most importantly the probability for a prime is proportional to its
90             # gap, meaning some numbers in the range will be thousands of times
91             # more likely than others). On the contrary however, nobody has a way
92             # to exploit this, and it's not-uncommon to see used.
93             #
94             # We use:
95             # TRIVIAL range within native integer size (2^32 or 2^64)
96             # FTA1 random_nbit_prime with 65+ bits
97             # INVA1 other ranges with 65+ bit range
98             # where
99             # TRIVIAL = monte-carlo method or equivalent, perfect uniformity.
100             # FTA1 = Fouque/Tibouchi A1, very close to uniform
101             # INVA1 = inverted FTA1, less uniform but works with arbitrary ranges
102             #
103             # The random_maurer_prime function uses Maurer's FastPrime algorithm.
104             #
105             # If Math::Prime::Util::GMP is installed, these functions will be many times
106             # faster than other methods (e.g. Math::Pari monte-carlo or Crypt::Primes).
107             #
108             # Timings on Macbook.
109             # The "with GMP" numbers use Math::Prime::Util::GMP 0.44.
110             # The "no GMP" numbers are with no Math::BigInt backend, so very slow in comparison.
111             # If another backend was used (GMP, Pari, LTM) it would be more comparable.
112             #
113             # random_nbit_prime random_maurer_prime
114             # n-bits no GMP w/ MPU::GMP no GMP w/ MPU::GMP
115             # ---------- -------- ----------- -------- -----------
116             # 24-bit 1uS same same same
117             # 64-bit 5uS same same same
118             # 128-bit 0.12s 70uS 0.29s 166uS
119             # 256-bit 0.66s 379uS 1.82s 800uS
120             # 512-bit 7.8s 0.0022s 16.2s 0.0044s
121             # 1024-bit ---- 0.019s ---- 0.037s
122             # 2048-bit ---- 0.23s ---- 0.35s
123             # 4096-bit ---- 2.4s ---- 5.2s
124             #
125             # Random timings for 10M calls on i4770K:
126             # 0.39 Math::Random::MTwist 0.13
127             # 0.41 ntheory <==== us
128             # 0.89 system rand
129             # 1.76 Math::Random::MT::Auto
130             # 5.35 Bytes::Random::Secure OO w/ISAAC::XS
131             # 7.43 Math::Random::Secure w/ISAAC::XS
132             # 12.40 Math::Random::Secure
133             # 12.78 Bytes::Random::Secure OO
134             # 13.86 Bytes::Random::Secure function w/ISAAC::XS
135             # 21.95 Bytes::Random::Secure function
136             # 822.1 Crypt::Random
137             #
138             # time perl -E 'use Math::Random::MTwist "irand32"; irand32() for 1..10000000;'
139             # time perl -E 'sub irand {int(rand(4294967296));} irand() for 1..10000000;'
140             # time perl -E 'use Math::Random::MT::Auto; sub irand { Math::Random::MT::Auto::irand() & 0xFFFFFFFF } irand() for 1..10000000;'
141             # time perl -E 'use Math::Random::Secure qw/irand/; irand() for 1..10000000;'
142             # time perl -E 'use Bytes::Random::Secure qw/random_bytes/; sub irand {return unpack("L",random_bytes(4));} irand() for 1..10000000;'
143             # time perl -E 'use Bytes::Random::Secure; my $rng = Bytes::Random::Secure->new(); sub irand {return $rng->irand;} irand() for 1..10000000;'
144             # time perl -E 'use Crypt::Random qw/makerandom/; sub irand {makerandom(Size=>32, Uniform=>1, Strength=>0)} irand() for 1..100_000;'
145             # > haveged daemon running to stop /dev/random blocking
146             # > Both BRS and CR have more features that this isn't measuring.
147             #
148             # To verify distribution:
149             # perl -Iblib/lib -Iblib/arch -MMath::Prime::Util=:all -E 'my %freq; $n=1000000; $freq{random_nbit_prime(6)}++ for (1..$n); printf("%4d %6.3f%%\n", $_, 100.0*$freq{$_}/$n) for sort {$a<=>$b} keys %freq;'
150             # perl -Iblib/lib -Iblib/arch -MMath::Prime::Util=:all -E 'my %freq; $n=1000000; $freq{random_prime(1260437,1260733)}++ for (1..$n); printf("%4d %6.3f%%\n", $_, 100.0*$freq{$_}/$n) for sort {$a<=>$b} keys %freq;'
151              
152             # Sub to call with low and high already primes and verified range.
153             my $_random_prime = sub {
154             my($low,$high) = @_;
155             my $prime;
156              
157             #{ my $bsize = 100; my @bins; my $counts = 10000000;
158             # for my $c (1..$counts) { $bins[ $_IRANDF->($bsize-1) ]++; }
159             # for my $b (0..$bsize) {printf("%4d %8.5f%%\n", $b, $bins[$b]/$counts);} }
160              
161             # low and high are both odds, and low < high.
162              
163             # This is fast for small values, low memory, perfectly uniform, and
164             # consumes the minimum amount of randomness needed. But it isn't feasible
165             # with large values. Also note that low must be a prime.
166             if ($high <= 262144 && MPU_USE_XS) {
167             my $li = prime_count(2, $low);
168             my $irange = prime_count($low, $high);
169             my $rand = urandomm($irange);
170             return nth_prime($li + $rand);
171             }
172              
173             $low-- if $low == 2; # Low of 2 becomes 1 for our program.
174             # Math::BigInt::GMP's RT 71548 will wreak havoc if we don't do this.
175             $low = Math::BigInt->new("$low") if ref($high) eq 'Math::BigInt';
176             confess "Invalid _random_prime parameters: $low, $high" if ($low % 2) == 0 || ($high % 2) == 0;
177              
178             # We're going to look at the odd numbers only.
179             my $oddrange = (($high - $low) >> 1) + 1;
180              
181             croak "Large random primes not supported on old Perl"
182             if OLD_PERL_VERSION && MPU_64BIT && $oddrange > 4294967295;
183              
184             # If $low is large (e.g. >10 digits) and $range is small (say ~10k), it
185             # would be fastest to call primes in the range and randomly pick one. I'm
186             # not implementing it now because it seems like a rare case.
187              
188             # If the range is reasonably small, generate using simple Monte Carlo
189             # method (aka the 'trivial' method). Completely uniform.
190             if ($oddrange < MPU_MAXPARAM) {
191             my $loop_limit = 2000 * 1000; # To protect against broken rand
192             if ($low > 11) {
193             while ($loop_limit-- > 0) {
194             $prime = $low + 2 * urandomm($oddrange);
195             next if !($prime % 3) || !($prime % 5) || !($prime % 7) || !($prime % 11);
196             return $prime if is_prob_prime($prime);
197             }
198             } else {
199             while ($loop_limit-- > 0) {
200             $prime = $low + 2 * urandomm($oddrange);
201             next if $prime > 11 && (!($prime % 3) || !($prime % 5) || !($prime % 7) || !($prime % 11));
202             return 2 if $prime == 1; # Remember the special case for 2.
203             return $prime if is_prob_prime($prime);
204             }
205             }
206             croak "Random function broken?";
207             }
208              
209             # We have an ocean of range, and a teaspoon to hold randomness.
210              
211             # Since we have an arbitrary range and not a power of two, I don't see how
212             # Fouque's algorithm A1 could be used (where we generate lower bits and
213             # generate random sets of upper). Similarly trying to simply generate
214             # upper bits is full of ways to trip up and get non-uniform results.
215             #
216             # What I'm doing here is:
217             #
218             # 1) divide the range into semi-evenly sized partitions, where each part
219             # is as close to $rand_max_val as we can.
220             # 2) randomly select one of the partitions.
221             # 3) iterate choosing random values within the partition.
222             #
223             # The downside is that we're skewing a _lot_ farther from uniformity than
224             # we'd like. Imagine we started at 0 with 1e18 partitions of size 100k
225             # each.
226             # Probability of '5' being returned =
227             # 1.04e-22 = 1e-18 (chose first partition) * 1/9592 (chose '5')
228             # Probability of '100003' being returned =
229             # 1.19e-22 = 1e-18 (chose second partition) * 1/8392 (chose '100003')
230             # Probability of '99999999999999999999977' being returned =
231             # 5.20e-22 = 1e-18 (chose last partition) * 1/1922 (chose '99...77')
232             # So the primes in the last partition will show up 5x more often.
233             # The partitions are selected uniformly, and the primes within are selected
234             # uniformly, but the number of primes in each bucket is _not_ uniform.
235             # Their individual probability of being selected is the probability of the
236             # partition (uniform) times the probability of being selected inside the
237             # partition (uniform with respect to all other primes in the same
238             # partition, but each partition is different and skewed).
239             #
240             # Partitions are typically much larger than 100k, but with a huge range
241             # we still see this (e.g. ~3x from 0-10^30, ~10x from 0-10^100).
242             #
243             # When selecting n-bit or n-digit primes, this effect is MUCH smaller, as
244             # the skew becomes approx lg(2^n) / lg(2^(n-1)) which is pretty close to 1.
245             #
246             #
247             # Another idea I'd like to try sometime is:
248             # pclo = prime_count_lower(low);
249             # pchi = prime_count_upper(high);
250             # do {
251             # $nth = random selection between pclo and pchi
252             # $prguess = nth_prime_approx($nth);
253             # } while ($prguess >= low) && ($prguess <= high);
254             # monte carlo select a prime in $prguess-2**24 to $prguess+2**24
255             # which accounts for the prime distribution.
256              
257             my($binsize, $nparts);
258             my $rand_part_size = 1 << (MPU_64BIT ? 32 : 31);
259             if (ref($oddrange) eq 'Math::BigInt') {
260             # Go to some trouble here because some systems are wonky, such as
261             # giving us +a/+b = -r. Also note the quotes for the bigint argument.
262             # Without that, Math::BigInt::GMP can return garbage.
263             my($nbins, $rem);
264             ($nbins, $rem) = $oddrange->copy->bdiv( "$rand_part_size" );
265             $nbins++ if $rem > 0;
266             $nbins = $nbins->as_int();
267             ($binsize,$rem) = $oddrange->copy->bdiv($nbins);
268             $binsize++ if $rem > 0;
269             $binsize = $binsize->as_int();
270             $nparts = $oddrange->copy->bdiv($binsize)->as_int();
271             $low = $high->copy->bzero->badd($low) if ref($low) ne 'Math::BigInt';
272             } else {
273             my $nbins = int($oddrange / $rand_part_size);
274             $nbins++ if $nbins * $rand_part_size != $oddrange;
275             $binsize = int($oddrange / $nbins);
276             $binsize++ if $binsize * $nbins != $oddrange;
277             $nparts = int($oddrange/$binsize);
278             }
279             $nparts-- if ($nparts * $binsize) == $oddrange;
280              
281             my $rpart = urandomm($nparts+1);
282              
283             my $primelow = $low + 2 * $binsize * $rpart;
284             my $partsize = ($rpart < $nparts) ? $binsize
285             : $oddrange - ($nparts * $binsize);
286             $partsize = _bigint_to_int($partsize) if ref($partsize) eq 'Math::BigInt';
287             #warn "range $oddrange = $nparts * $binsize + ", $oddrange - ($nparts * $binsize), "\n";
288             #warn " chose part $rpart size $partsize\n";
289             #warn " primelow is $low + 2 * $binsize * $rpart = $primelow\n";
290             #die "Result could be too large" if ($primelow + 2*($partsize-1)) > $high;
291              
292             # Generate random numbers in the interval until one is prime.
293             my $loop_limit = 2000 * 1000; # To protect against broken rand
294              
295             # Simply things for non-bigints.
296             if (ref($low) ne 'Math::BigInt') {
297             while ($loop_limit-- > 0) {
298             my $rand = urandomm($partsize);
299             $prime = $primelow + $rand + $rand;
300             croak "random prime failure, $prime > $high" if $prime > $high;
301             if ($prime <= 23) {
302             $prime = 2 if $prime == 1; # special case for low = 2
303             next unless (0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1)[$prime];
304             return $prime;
305             }
306             next if !($prime % 3) || !($prime % 5) || !($prime % 7) || !($prime % 11);
307             # It looks promising. Check it.
308             next unless is_prob_prime($prime);
309             return $prime;
310             }
311             croak "Random function broken?";
312             }
313              
314             # By checking a wheel 30 mod, we can skip anything that would be a multiple
315             # of 2, 3, or 5, without even having to create the bigint prime.
316             my @w30 = (1,0,5,4,3,2,1,0,3,2,1,0,1,0,3,2,1,0,1,0,3,2,1,0,5,4,3,2,1,0);
317             my $primelow30 = $primelow % 30;
318             $primelow30 = _bigint_to_int($primelow30) if ref($primelow30) eq 'Math::BigInt';
319              
320             # Big GCD's are hugely fast with GMP or Pari, but super slow with Calc.
321             _make_big_gcds() if $_big_gcd_use < 0;
322              
323             while ($loop_limit-- > 0) {
324             my $rand = urandomm($partsize);
325             # Check wheel-30 mod
326             my $rand30 = $rand % 30;
327             next if $w30[($primelow30 + 2*$rand30) % 30]
328             && ($rand > 3 || $primelow > 5);
329             # Construct prime
330             $prime = $primelow + $rand + $rand;
331             croak "random prime failure, $prime > $high" if $prime > $high;
332             if ($prime <= 23) {
333             $prime = 2 if $prime == 1; # special case for low = 2
334             next unless (0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1)[$prime];
335             return $prime;
336             }
337             # With GMP, the fastest thing to do is check primality.
338             if (MPU_USE_GMP) {
339             next unless Math::Prime::Util::GMP::is_prime($prime);
340             return $prime;
341             }
342             # No MPU:GMP, so primality checking is slow. Skip some composites here.
343             next unless Math::BigInt::bgcd($prime, 7436429) == 1;
344             if ($_big_gcd_use && $prime > $_big_gcd_top) {
345             next unless Math::BigInt::bgcd($prime, $_big_gcd[0]) == 1;
346             next unless Math::BigInt::bgcd($prime, $_big_gcd[1]) == 1;
347             next unless Math::BigInt::bgcd($prime, $_big_gcd[2]) == 1;
348             next unless Math::BigInt::bgcd($prime, $_big_gcd[3]) == 1;
349             }
350             # It looks promising. Check it.
351             next unless is_prob_prime($prime);
352             return $prime;
353             }
354             croak "Random function broken?";
355             };
356              
357             # Cache of tight bounds for each digit. Helps performance a lot.
358             my @_random_ndigit_ranges = (undef, [2,7], [11,97] );
359             my @_random_nbit_ranges = (undef, undef, [2,3],[5,7] );
360             my %_random_cache_small;
361              
362             # For fixed small ranges with XS, e.g. 6-digit, 18-bit
363             sub _random_xscount_prime {
364 0     0   0 my($low,$high) = @_;
365 0         0 my($istart, $irange);
366 0         0 my $cachearef = $_random_cache_small{$low,$high};
367 0 0       0 if (defined $cachearef) {
368 0         0 ($istart, $irange) = @$cachearef;
369             } else {
370 0 0       0 my $beg = ($low <= 2) ? 2 : next_prime($low-1);
371 0 0       0 my $end = ($high < ~0) ? prev_prime($high + 1) : prev_prime($high);
372 0         0 ($istart, $irange) = ( prime_count(2, $beg), prime_count($beg, $end) );
373 0         0 $_random_cache_small{$low,$high} = [$istart, $irange];
374             }
375 0         0 my $rand = urandomm($irange);
376 0         0 return nth_prime($istart + $rand);
377             }
378              
379             sub random_prime {
380 2     2 1 6 my($low,$high) = @_;
381 2 50 33     12 return if $high < 2 || $low > $high;
382              
383             # Tighten the range to the nearest prime.
384 2 50       199 $low = ($low <= 2) ? 2 : next_prime($low-1);
385 2 50       16 $high = ($high == ~0) ? prev_prime($high) : prev_prime($high + 1);
386 2 50 33     11 return $low if ($low == $high) && is_prob_prime($low);
387 2 50       33 return if $low >= $high;
388              
389             # At this point low and high are both primes, and low < high.
390 2         37 return $_random_prime->($low, $high);
391             }
392              
393             sub random_ndigit_prime {
394 3     3 1 7 my($digits) = @_;
395 3 50       9 croak "random_ndigit_prime, digits must be >= 1" unless $digits >= 1;
396              
397 3 50 50     13 return _random_xscount_prime( int(10 ** ($digits-1)), int(10 ** $digits) )
398             if $digits <= 6 && MPU_USE_XS;
399              
400 3         7 my $bigdigits = $digits >= MPU_MAXDIGITS;
401 3 100 66     20 if ($bigdigits && prime_get_config->{'nobigint'}) {
402 1 50       3 croak "random_ndigit_prime with -nobigint, digits out of range"
403             if $digits > MPU_MAXDIGITS;
404             # Special case for nobigint and threshold digits
405 1 50       4 if (!defined $_random_ndigit_ranges[$digits]) {
406 1         4 my $low = int(10 ** ($digits-1));
407 1         2 my $high = ~0;
408 1         35 $_random_ndigit_ranges[$digits] = [next_prime($low),prev_prime($high)];
409             }
410             }
411              
412 3 100       14 if (!defined $_random_ndigit_ranges[$digits]) {
413 2 50       7 if ($bigdigits) {
414 2         20 my $low = Math::BigInt->new('10')->bpow($digits-1);
415 2         519 my $high = Math::BigInt->new('10')->bpow($digits);
416             # Just pull the range in to the nearest odd.
417 2         495 $_random_ndigit_ranges[$digits] = [$low+1, $high-1];
418             } else {
419 0         0 my $low = int(10 ** ($digits-1));
420 0         0 my $high = int(10 ** $digits);
421             # Note: Perl 5.6.2 cannot represent 10**15 as an integer, so things
422             # will crash all over the place if you try. We can stringify it, but
423             # will just fail tests later.
424 0         0 $_random_ndigit_ranges[$digits] = [next_prime($low),prev_prime($high)];
425             }
426             }
427 3         615 my ($low, $high) = @{$_random_ndigit_ranges[$digits]};
  3         10  
428 3         11 return $_random_prime->($low, $high);
429             }
430              
431             my @_random_nbit_m;
432             my @_random_nbit_lambda;
433             my @_random_nbit_arange;
434              
435             sub random_nbit_prime {
436 15     15 1 38 my($bits) = @_;
437 15 50       45 croak "random_nbit_prime, bits must be >= 2" unless $bits >= 2;
438 15         40 $bits = int("$bits");
439              
440             # Very small size, use the nth-prime method
441 15 50 50     51 if ($bits <= 20 && MPU_USE_XS) {
442 0 0       0 if ($bits <= 4) {
443 0 0       0 return (2,3)[urandomb(1)] if $bits == 2;
444 0 0       0 return (5,7)[urandomb(1)] if $bits == 3;
445 0 0       0 return (11,13)[urandomb(1)] if $bits == 4;
446             }
447 0         0 return _random_xscount_prime( 1 << ($bits-1), 1 << $bits );
448             }
449              
450 15         26 croak "Mid-size random primes not supported on broken old Perl"
451             if OLD_PERL_VERSION && MPU_64BIT && $bits > 49 && $bits <= 64;
452              
453             # Fouque and Tibouchi (2011) Algorithm 1 (basic)
454             # Modified to make sure the nth bit is always set.
455             #
456             # Example for random_nbit_prime(512) on 64-bit Perl:
457             # p: 1aaaaaaaabbbbbbbbbbbbbbbbbbbb1
458             # ^^ ^ ^--- Trailing 1 so p is odd
459             # || +--- 512-63-2 = 447 lower bits selected before loop
460             # |+--- 63 upper bits selected in loop, repeated until p is prime
461             # +--- upper bit is 1 so we generate an n-bit prime
462             # total: 1 + 63 + 447 + 1 = 512 bits
463             #
464             # Algorithm 2 is implemented in a previous commit on github. The problem
465             # is that it doesn't set the nth bit, and making that change requires a
466             # modification of the algorithm. It was not a lot faster than this A1
467             # with the native int trial division. If the irandf function was very
468             # slow, then A2 would look more promising.
469             #
470 15 100       42 if (1 && $bits > 64) {
471 6 100       19 my $l = (MPU_64BIT && $bits > 79) ? 63 : 31;
472 6 50 100     28 $l = 49 if $l == 63 && OLD_PERL_VERSION; # Fix for broken Perl 5.6
473 6 50       19 $l = $bits-2 if $bits-2 < $l;
474              
475 6         35 my $brand = urandomb($bits-$l-2);
476 6 50       46 $brand = Math::BigInt->new("$brand") unless ref($brand) eq 'Math::BigInt';
477 6         316 my $b = $brand->blsft(1)->binc();
478              
479             # Precalculate some modulii so we can do trial division on native int
480             # 9699690 = 2*3*5*7*11*13*17*19, so later operations can be native ints
481 6         1268 my @premod;
482 6         23 my $bpremod = _bigint_to_int($b->copy->bmod(9699690));
483 6         123 my $twopremod = _bigint_to_int(Math::BigInt->new(2)->bmodpow($bits-$l-1, 9699690));
484 6         101 foreach my $zi (0 .. 19-1) {
485 114         146 foreach my $pm (3, 5, 7, 11, 13, 17, 19) {
486 798 100 100     1507 next if $zi >= $pm || defined $premod[$pm];
487 218 100       357 $premod[$pm] = $zi if ( ($twopremod*$zi+$bpremod) % $pm) == 0;
488             }
489             }
490 6 100       21 _make_big_gcds() if $_big_gcd_use < 0;
491 6         13 if (!MPU_USE_GMP) { require Math::Prime::Util::PP; }
  6         37  
492              
493 6         13 my $loop_limit = 1_000_000;
494 6         18 while ($loop_limit-- > 0) {
495 56         3620 my $a = (1 << $l) + urandomb($l);
496             # $a % s == $premod[s] => $p % s == 0 => p will be composite
497 56 100 100     451 next if $a % 3 == $premod[ 3] || $a % 5 == $premod[ 5]
      100        
      100        
      100        
      66        
      100        
498             || $a % 7 == $premod[ 7] || $a % 11 == $premod[11]
499             || $a % 13 == $premod[13] || $a % 17 == $premod[17]
500             || $a % 19 == $premod[19];
501 28         145 my $p = Math::BigInt->new("$a")->blsft($bits-$l-1)->badd($b);
502             #die " $a $b $p" if $a % 11 == $premod[11] && $p % 11 != 0;
503             #die "!$a $b $p" if $a % 11 != $premod[11] && $p % 11 == 0;
504 28         10135 if (MPU_USE_GMP) {
505             next unless Math::Prime::Util::GMP::is_prime($p);
506             } else {
507 28 100       86 next unless Math::BigInt::bgcd($p, 1348781387) == 1; # 23-43
508 22 50 33     13178 if ($_big_gcd_use && $p > $_big_gcd_top) {
509 0 0       0 next unless Math::BigInt::bgcd($p, $_big_gcd[0]) == 1;
510 0 0       0 next unless Math::BigInt::bgcd($p, $_big_gcd[1]) == 1;
511 0 0       0 next unless Math::BigInt::bgcd($p, $_big_gcd[2]) == 1;
512 0 0       0 next unless Math::BigInt::bgcd($p, $_big_gcd[3]) == 1;
513             }
514             # We know we don't have GMP and are > 2^64, so go directly to this.
515 22 100       74 next unless Math::Prime::Util::PP::is_bpsw_prime($p);
516             }
517 6         1611 return $p;
518             }
519 0         0 croak "Random function broken?";
520             }
521              
522             # The Trivial method. Great uniformity, and fine for small sizes. It
523             # gets very slow as the bit size increases, but that is why we have the
524             # method above for bigints.
525 9         15 if (1) {
526              
527 9         18 my $loop_limit = 2_000_000;
528 9 50       28 if ($bits > MPU_MAXBITS) {
529 0         0 my $p = Math::BigInt->bone->blsft($bits-1)->binc();
530 0         0 while ($loop_limit-- > 0) {
531 0         0 my $n = Math::BigInt->new(''.urandomb($bits-2))->blsft(1)->badd($p);
532 0 0       0 return $n if is_prob_prime($n);
533             }
534             } else {
535 9         24 my $p = (1 << ($bits-1)) + 1;
536 9         30 while ($loop_limit-- > 0) {
537 167         340 my $n = $p + (urandomb($bits-2) << 1);
538 167 100       501 return $n if is_prob_prime($n);
539             }
540             }
541 0         0 croak "Random function broken?";
542              
543             } else {
544              
545             # Send through the generic random_prime function. Decently fast, but
546             # quite a bit slower than the F&T A1 method above.
547             if (!defined $_random_nbit_ranges[$bits]) {
548             if ($bits > MPU_MAXBITS) {
549             my $low = Math::BigInt->new('2')->bpow($bits-1);
550             my $high = Math::BigInt->new('2')->bpow($bits);
551             # Don't pull the range in to primes, just odds
552             $_random_nbit_ranges[$bits] = [$low+1, $high-1];
553             } else {
554             my $low = 1 << ($bits-1);
555             my $high = ($bits == MPU_MAXBITS)
556             ? ~0-1
557             : ~0 >> (MPU_MAXBITS - $bits);
558             $_random_nbit_ranges[$bits] = [next_prime($low-1),prev_prime($high+1)];
559             # Example: bits = 7.
560             # low = 1<<6 = 64. next_prime(64-1) = 67
561             # high = ~0 >> (64-7) = 127. prev_prime(127+1) = 127
562             }
563             }
564             my ($low, $high) = @{$_random_nbit_ranges[$bits]};
565             return $_random_prime->($low, $high);
566              
567             }
568             }
569              
570              
571             # For stripping off the header on certificates so they can be combined.
572             sub _strip_proof_header {
573 0     0   0 my $proof = shift;
574 0         0 $proof =~ s/^\[MPU - Primality Certificate\]\nVersion \S+\n+Proof for:\nN (\d+)\n+//ms;
575 0         0 return $proof;
576             }
577              
578              
579             sub random_maurer_prime {
580 0     0 1 0 my $k = shift;
581 0 0       0 croak "random_maurer_prime, bits must be >= 2" unless $k >= 2;
582 0         0 $k = int("$k");
583              
584 0 0 0     0 return random_nbit_prime($k) if $k <= MPU_MAXBITS && !OLD_PERL_VERSION;
585              
586 0         0 my ($n, $cert) = random_maurer_prime_with_cert($k);
587 0 0       0 croak "maurer prime $n failed certificate verification!"
588             unless verify_prime($cert);
589 0         0 return $n;
590             }
591              
592             sub random_maurer_prime_with_cert {
593 10     10 1 36 my $k = shift;
594 10 50       40 croak "random_maurer_prime, bits must be >= 2" unless $k >= 2;
595 10         30 $k = int("$k");
596              
597             # This should never happen. Trap now to prevent infinite loop.
598 10 50       37 croak "number of bits must not be a bigint" if ref($k) eq 'Math::BigInt';
599              
600             # Results for random_nbit_prime are proven for all native bit sizes.
601 10         20 my $p0 = MPU_MAXBITS;
602 10         225 $p0 = 49 if OLD_PERL_VERSION && MPU_MAXBITS > 49;
603              
604 10 100       48 if ($k <= $p0) {
605 5         26 my $n = random_nbit_prime($k);
606 5         30 my ($isp, $cert) = is_provable_prime_with_cert($n);
607 5 50       19 croak "small nbit prime could not be proven" if $isp != 2;
608 5         16 return ($n, $cert);
609             }
610              
611             # Set verbose to 3 to get pretty output like Crypt::Primes
612 5         24 my $verbose = prime_get_config->{'verbose'};
613 5 50       30 local $| = 1 if $verbose > 2;
614              
615 5 100       18 do { require Math::BigFloat; Math::BigFloat->import(); }
  2         1473  
  2         39685  
616             if !defined $Math::BigFloat::VERSION;
617              
618             # Ignore Maurer's g and c that controls how much trial division is done.
619 5         1312 my $r = Math::BigFloat->new("0.5"); # relative size of the prime q
620 5         1392 my $m = 20; # makes sure R is big enough
621              
622             # Generate a random prime q of size $r*$k, where $r >= 0.5. Try to
623             # cleverly select r to match the size of a typical random factor.
624 5 50       24 if ($k > 2*$m) {
625 5         12 do {
626 10         303354 my $s = Math::Prime::Util::drand();
627 10         36 $r = Math::BigFloat->new(2)->bpow($s-1);
628             } while ($k*$r >= $k-$m);
629             }
630              
631             # I've seen +0, +1, and +2 here. Maurer uses +0. Menezes uses +1.
632             # We can use +1 because we're using BLS75 theorem 3 later.
633 5         350479 my $smallk = int(($r * $k)->bfloor->bstr) + 1;
634 5         2350 my ($q, $qcert) = random_maurer_prime_with_cert($smallk);
635 5 50       40 $q = Math::BigInt->new("$q") unless ref($q) eq 'Math::BigInt';
636 5         318 my $I = Math::BigInt->new(2)->bpow($k-2)->bdiv($q)->bfloor->as_int();
637 5 50 33     2995 print "r = $r k = $k q = $q I = $I\n" if $verbose && $verbose != 3;
638 5 50       20 $qcert = ($q < Math::BigInt->new("18446744073709551615"))
639             ? "" : _strip_proof_header($qcert);
640              
641             # Big GCD's are hugely fast with GMP or Pari, but super slow with Calc.
642 5 100       458 _make_big_gcds() if $_big_gcd_use < 0;
643 5         24 my $ONE = Math::BigInt->bone;
644 5         162 my $TWO = $ONE->copy->binc;
645              
646 5         269 my $loop_limit = 1_000_000 + $k * 1_000;
647 5         20 while ($loop_limit-- > 0) {
648             # R is a random number between $I+1 and 2*$I
649             #my $R = $I + 1 + urandomm( $I );
650 81         17619 my $R = $I->copy->binc->badd( urandomm($I) );
651             #my $n = 2 * $R * $q + 1;
652 81         19592 my $nm1 = $TWO->copy->bmul($R)->bmul($q);
653 81         13405 my $n = $nm1->copy->binc;
654             # We constructed a promising looking $n. Now test it.
655 81 50       3658 print "." if $verbose > 2;
656 81         122 if (MPU_USE_GMP) {
657             # MPU::GMP::is_prob_prime has fast tests built in.
658             next unless Math::Prime::Util::GMP::is_prob_prime($n);
659             } else {
660             # No GMP, so first do trial divisions, then a SPSP test.
661 81 100       213 next unless Math::BigInt::bgcd($n, 111546435)->is_one;
662 30 50 33     10952 if ($_big_gcd_use && $n > $_big_gcd_top) {
663 0 0       0 next unless Math::BigInt::bgcd($n, $_big_gcd[0])->is_one;
664 0 0       0 next unless Math::BigInt::bgcd($n, $_big_gcd[1])->is_one;
665 0 0       0 next unless Math::BigInt::bgcd($n, $_big_gcd[2])->is_one;
666 0 0       0 next unless Math::BigInt::bgcd($n, $_big_gcd[3])->is_one;
667             }
668 30 50       90 print "+" if $verbose > 2;
669 30 100       148 next unless is_strong_pseudoprime($n, 3);
670             }
671 5 50       29 print "*" if $verbose > 2;
672              
673             # We could pick a random generator by doing:
674             # Step 1: pick a random r
675             # Step 2: compute g = r^((n-1)/q) mod p
676             # Step 3: if g == 1, goto Step 1.
677             # Note that n = 2*R*q+1, hence the exponent is 2*R.
678              
679             # We could set r = 0.3333 earlier, then use BLS75 theorem 5 here.
680             # The chain would be shorter, requiring less overall work for
681             # large inputs. Maurer's paper discusses the idea.
682              
683             # Use BLS75 theorem 3. This is easier and possibly faster than
684             # BLS75 theorem 4 (Pocklington) used by Maurer's paper.
685              
686             # Check conditions -- these should be redundant.
687 5         24 my $m = $TWO * $R;
688 5 50 33     590 if (! ($q->is_odd && $q > 2 && $m > 0 &&
      33        
      33        
      33        
689             $m * $q + $ONE == $n && $TWO*$q+$ONE > $n->copy->bsqrt()) ) {
690 0         0 carp "Maurer prime failed BLS75 theorem 3 conditions. Retry.";
691 0         0 next;
692             }
693             # Find a suitable a. Move on if one isn't found quickly.
694 5         7380 foreach my $trya (2, 3, 5, 7, 11, 13) {
695 11         132324 my $a = Math::BigInt->new($trya);
696             # m/2 = R (n-1)/2 = (2*R*q)/2 = R*q
697 11 50       541 next unless $a->copy->bmodpow($R, $n) != $nm1;
698 11 100       97801 next unless $a->copy->bmodpow($R*$q, $n) == $nm1;
699 5 50       118967 print "($k)" if $verbose > 2;
700 5 50       47 croak "Maurer prime $n=2*$R*$q+1 failed BPSW" unless is_prob_prime($n);
701 5         739 my $cert = "[MPU - Primality Certificate]\nVersion 1.0\n\n" .
702             "Proof for:\nN $n\n\n" .
703             "Type BLS3\nN $n\nQ $q\nA $a\n" .
704             $qcert;
705 5         546 return ($n, $cert);
706             }
707             # Didn't pass the selected a values. Try another R.
708             }
709 0         0 croak "Failure in random_maurer_prime, could not find a prime\n";
710             } # End of random_maurer_prime
711              
712              
713             sub random_shawe_taylor_prime_with_cert {
714 2     2 1 6 my $k = shift;
715              
716 2         18 my $seed = random_bytes(512/8);
717              
718 2         9 my($status,$prime,$prime_seed,$prime_gen_counter,$cert)
719             = _ST_Random_prime($k, $seed);
720 2 50       15 croak "Shawe-Taylor random prime failure" unless $status;
721 2 50       15 croak "Shawe-Taylor random prime failure: prime $prime failed certificate verification!" unless verify_prime($cert);
722              
723 2         19 return ($prime,$cert);
724             }
725              
726             sub _seed_plus_one {
727 98     98   156 my($s) = @_;
728 98         494 for (my $i = length($s)-1; $i >= 0; $i--) {
729 98         265 vec($s, $i, 8)++;
730 98 50       228 last unless vec($s, $i, 8) == 0;
731             }
732 98         191 return $s;
733             }
734              
735             sub _ST_Random_prime { # From FIPS 186-4
736 6     6   17 my($k, $input_seed) = @_;
737 6 50       14 croak "Shawe-Taylor random prime must have length >= 2" if $k < 2;
738 6         17 $k = int("$k");
739              
740 6 50 33     33 croak "Shawe-Taylor random prime, invalid input seed"
741             unless defined $input_seed && length($input_seed) >= 32;
742              
743 6 50       15 if (!defined $Digest::SHA::VERSION) {
744 0         0 eval { require Digest::SHA;
745 0         0 my $version = $Digest::SHA::VERSION;
746 0         0 $version =~ s/[^\d.]//g;
747 0         0 $version >= 4.00; }
748 0 0       0 or do { croak "Must have Digest::SHA 4.00 or later"; };
  0         0  
749             }
750              
751 6         18 my $k2 = Math::BigInt->new(2)->bpow($k-1);
752              
753 6 100       1572 if ($k < 33) {
754 2         6 my $seed = $input_seed;
755 2         5 my $prime_gen_counter = 0;
756 2         6 my $kmask = 0xFFFFFFFF >> (32-$k); # Does the mod operation
757 2         6 my $kstencil = (1 << ($k-1)) | 1; # Sets high and low bits
758 2         4 while (1) {
759 32         52 my $seedp1 = _seed_plus_one($seed);
760 32         247 my $cvec = Digest::SHA::sha256($seed) ^ Digest::SHA::sha256($seedp1);
761             # my $c = Math::BigInt->from_hex('0x' . unpack("H*", $cvec));
762             # $c = $k2 + ($c % $k2);
763             # $c = (2 * ($c >> 1)) + 1;
764 32         85 my($c) = unpack("N*", substr($cvec,-4,4));
765 32         50 $c = ($c & $kmask) | $kstencil;
766 32         44 $prime_gen_counter++;
767 32         51 $seed = _seed_plus_one($seedp1);
768 32         65 my ($isp, $cert) = is_provable_prime_with_cert($c);
769 32 100       70 return (1,$c,$seed,$prime_gen_counter,$cert) if $isp;
770 30 50       61 return (0,0,0,0) if $prime_gen_counter > 10000 + 16*$k;
771             }
772             }
773 4         59 my($status,$c0,$seed,$prime_gen_counter,$cert)
774             = _ST_Random_prime( (($k+1)>>1)+1, $input_seed);
775 4 50       19 return (0,0,0,0) unless $status;
776 4 50       17 $cert = ($c0 < Math::BigInt->new("18446744073709551615"))
777             ? "" : _strip_proof_header($cert);
778 4         461 my $iterations = int(($k + 255) / 256) - 1; # SHA256 generates 256 bits
779 4         7 my $old_counter = $prime_gen_counter;
780 4         9 my $xstr = '';
781 4         13 for my $i (0 .. $iterations) {
782 4         32 $xstr = Digest::SHA::sha256_hex($seed) . $xstr;
783 4         12 $seed = _seed_plus_one($seed);
784             }
785 4         19 my $x = Math::BigInt->from_hex('0x'.$xstr);
786 4         3735 $x = $k2 + ($x % $k2);
787 4         1698 my $t = ($x + 2*$c0 - 1) / (2*$c0);
788 4 50       2665 _make_big_gcds() if $_big_gcd_use < 0;
789 4         7 while (1) {
790 30 50       1077 if (2*$t*$c0 + 1 > 2*$k2) { $t = ($k2 + 2*$c0 - 1) / (2*$c0); }
  0         0  
791 30         16799 my $c = 2*$t*$c0 + 1;
792 30         11290 $prime_gen_counter++;
793              
794             # Don't do the Pocklington check unless the candidate looks prime
795 30         51 my $looks_prime = 0;
796 30         44 if (MPU_USE_GMP) {
797             # MPU::GMP::is_prob_prime has fast tests built in.
798             $looks_prime = Math::Prime::Util::GMP::is_prob_prime($c);
799             } else {
800             # No GMP, so first do trial divisions, then a SPSP test.
801 30         74 $looks_prime = Math::BigInt::bgcd($c, 111546435)->is_one;
802 30 50 66     10480 if ($looks_prime && $_big_gcd_use && $c > $_big_gcd_top) {
      33        
803 0   0     0 $looks_prime = Math::BigInt::bgcd($c, $_big_gcd[0])->is_one &&
804             Math::BigInt::bgcd($c, $_big_gcd[1])->is_one &&
805             Math::BigInt::bgcd($c, $_big_gcd[2])->is_one &&
806             Math::BigInt::bgcd($c, $_big_gcd[3])->is_one;
807             }
808 30 100 100     111 $looks_prime = 0 if $looks_prime && !is_strong_pseudoprime($c, 3);
809             }
810              
811 30 100       392 if ($looks_prime) {
812             # We could use a in (2,3,5,7,11,13), but pedantically use FIPS 186-4.
813 4         11 my $astr = '';
814 4         11 for my $i (0 .. $iterations) {
815 4         44 $astr = Digest::SHA::sha256_hex($seed) . $astr;
816 4         12 $seed = _seed_plus_one($seed);
817             }
818 4         20 my $a = Math::BigInt->from_hex('0x'.$astr);
819 4         3686 $a = ($a % ($c-3)) + 2;
820 4         2699 my $z = $a->copy->bmodpow(2*$t,$c);
821 4 50 33     37349 if (Math::BigInt::bgcd($z-1,$c)->is_one && $z->copy->bmodpow($c0,$c)->is_one) {
822 4 50       46015 croak "Shawe-Taylor random prime failure at ($k): $c not prime"
823             unless is_prob_prime($c);
824 4         439 $cert = "[MPU - Primality Certificate]\nVersion 1.0\n\n" .
825             "Proof for:\nN $c\n\n" .
826             "Type Pocklington\nN $c\nQ $c0\nA $a\n" .
827             $cert;
828 4         342 return (1, $c, $seed, $prime_gen_counter, $cert);
829             }
830             } else {
831             # Update seed "as if" we performed the Pocklington check from FIPS 186-4
832 26         51 for my $i (0 .. $iterations) {
833 26         56 $seed = _seed_plus_one($seed);
834             }
835             }
836 26 50       66 return (0,0,0,0) if $prime_gen_counter > 10000 + 16*$k + $old_counter;
837 26         68 $t++;
838             }
839             }
840              
841              
842             # Gordon's algorithm for generating a strong prime.
843             sub random_strong_prime {
844 1     1 1 3 my $t = shift;
845 1 50       3 croak "random_strong_prime, bits must be >= 128" unless $t >= 128;
846 1         3 $t = int("$t");
847              
848 1         2 croak "Random strong primes must be >= 173 bits on old Perl"
849             if OLD_PERL_VERSION && MPU_64BIT && $t < 173;
850              
851 1         3 my $l = (($t+1) >> 1) - 2;
852 1         4 my $lp = int($t/2) - 20;
853 1         3 my $lpp = $l - 20;
854 1         2 while (1) {
855 1         4 my $qp = random_nbit_prime($lp);
856 1         5 my $qpp = random_nbit_prime($lpp);
857 1 50       6 $qp = Math::BigInt->new("$qp") unless ref($qp) eq 'Math::BigInt';
858 1 50       4 $qpp = Math::BigInt->new("$qpp") unless ref($qpp) eq 'Math::BigInt';
859 1         5 my ($il, $rem) = Math::BigInt->new(2)->bpow($l-1)->bdec()->bdiv(2*$qpp);
860 1 50       754 $il++ if $rem > 0;
861 1         184 $il = $il->as_int();
862 1         21 my $iu = Math::BigInt->new(2)->bpow($l)->bsub(2)->bdiv(2*$qpp)->as_int();
863 1         752 my $istart = $il + urandomm($iu - $il + 1);
864 1         408 for (my $i = $istart; $i <= $iu; $i++) { # Search for q
865 37         31815 my $q = 2 * $i * $qpp + 1;
866 37 100       13320 next unless is_prob_prime($q);
867 1         139 my $pp = $qp->copy->bmodpow($q-2, $q)->bmul(2)->bmul($qp)->bdec();
868 1         28141 my ($jl, $rem) = Math::BigInt->new(2)->bpow($t-1)->bsub($pp)->bdiv(2*$q*$qp);
869 1 50       1143 $jl++ if $rem > 0;
870 1         213 $jl = $jl->as_int();
871 1         21 my $ju = Math::BigInt->new(2)->bpow($t)->bdec()->bsub($pp)->bdiv(2*$q*$qp)->as_int();
872 1         1059 my $jstart = $jl + urandomm($ju - $jl + 1);
873 1         407 for (my $j = $jstart; $j <= $ju; $j++) { # Search for p
874 14         19595 my $p = $pp + 2 * $j * $q * $qp;
875 14 100       5976 return $p if is_prob_prime($p);
876             }
877             }
878             }
879             }
880              
881             sub random_proven_prime {
882 0     0 1 0 my $k = shift;
883 0         0 my ($n, $cert) = random_proven_prime_with_cert($k);
884 0 0       0 croak "random_proven_prime $n failed certificate verification!"
885             unless verify_prime($cert);
886 0         0 return $n;
887             }
888              
889             sub random_proven_prime_with_cert {
890 1     1 1 3 my $k = shift;
891              
892 1 50 33     7 if (prime_get_config->{'gmp'} && $k <= 450) {
893 0         0 my $n = random_nbit_prime($k);
894 0         0 my ($isp, $cert) = is_provable_prime_with_cert($n);
895 0 0       0 croak "small nbit prime could not be proven" if $isp != 2;
896 0         0 return ($n, $cert);
897             }
898 1         8 return random_maurer_prime_with_cert($k);
899             }
900              
901             1;
902              
903             __END__