Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating exactly prime number with Java

I'm aware of the function BigInteger.probablePrime(int bitLength, Random rnd) that outputs probably prime number of any bit length. I want a REAL prime number in Java. Is there any FOSS library to do so with acceptable performance? Thanks in advance!

EDIT:

I'm looking at 1024 & 2048 bit primes.

like image 395
Viet Avatar asked May 21 '10 12:05

Viet


Video Answer


2 Answers

  • use probable prime to generate a candidate
  • use a fast deterministic test such as the AKS primality test to check whether the candidate is indeed prime.

edit: Or, if you don't trust the isProbablePrime to be large enough certainty, use the BigInteger constructor BigInteger(int bitLength, int certainty, Random rnd) that lets you tune your certainty threshold:

certainty - a measure of the uncertainty that the caller is willing to tolerate. The probability that the new BigInteger represents a prime number will exceed (1 - 1/2certainty). The execution time of this constructor is proportional to the value of this parameter.

Probabilistic tests used for cryptographic purposes are guaranteed to bound the probability of false positives -- it's not like there's some gotcha numbers that exist that will sneak through, it's just a matter of how low you want the probability to be. If you don't trust the Java BigInteger class to use these (it would be nice if they documented what test was used), use the Rabin-Miller test.

like image 119
Jason S Avatar answered Nov 09 '22 10:11

Jason S


There are some methods to generate very large primes with acceptable performance, but not with sufficient density for most purposes other than getting into the Guiness Book of Records.

Look at it like this: the likelihood that a number returned by probablePrime() is not prime is lower than the likelihood of you and everyone you know getting hit by lighting. Twice. On a single day.

Just don't worry about it.

like image 44
Michael Borgwardt Avatar answered Nov 09 '22 09:11

Michael Borgwardt