Java Code Examples for java.math.BigInteger#probablePrime()

The following examples show how to use java.math.BigInteger#probablePrime() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PaillierKeyGenerator.java    From protect with MIT License 6 votes vote down vote up
public PaillierKeyPair generate() {
	final SecureRandom random = new SecureRandom();

	final BigInteger p = BigInteger.probablePrime(this.keyLength / 2, random); // random prime
	final BigInteger q = BigInteger.probablePrime(this.keyLength / 2, random); // random prime

	final BigInteger n = p.multiply(q); // p*q
	final BigInteger nSquared = n.multiply(n); // n^2

	final BigInteger pMinusOne = p.subtract(BigInteger.ONE); // p - 1
	final BigInteger qMinusOne = q.subtract(BigInteger.ONE); // q - 1

	final BigInteger lambda = pMinusOne.multiply(qMinusOne); // totient(n)
	final BigInteger g = n.add(BigInteger.ONE); // n + 1
	final BigInteger mu = lambda.modInverse(n); // lambda^-1 % n

	final PaillierPublicKey publicKey = new PaillierPublicKey(n, g, nSquared);
	final PaillierPrivateKey privateKey = new PaillierPrivateKey(lambda, mu, n, nSquared);
	
	return new PaillierKeyPair(publicKey, privateKey);
}
 
Example 2
Source File: BigIntUtilities.java    From secretshare with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static BigInteger createPrimeBigger(BigInteger valueThatDeterminesNumberOfBits,
                                           Random random)
{
    int numbits = valueThatDeterminesNumberOfBits.bitLength() + 1;

    BigInteger ret = BigInteger.probablePrime(numbits, random);
    return ret;
}
 
Example 3
Source File: BloomFilter.java    From joshua with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a prime number that is larger than the given number. This is used to find bigPrime, a
 * prime that has to be larger than the size of the Bloom filter.
 * 
 * @param n an integer
 * 
 * @return a prime number larger than n
 */
private long getPrimeLargerThan(int n) {
  BigInteger ret;
  BigInteger maxLong = BigInteger.valueOf(Long.MAX_VALUE);
  int numBits = BigInteger.valueOf(n).bitLength() + 1;
  do {
    ret = BigInteger.probablePrime(numBits, RANDOM);
  } while (ret.compareTo(maxLong) > 1);
  return ret.longValue();
}
 
Example 4
Source File: BigIntegerTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i=0; i<primesTo100.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != primesTo100[i]) {
            System.err.println("low range primes failed");
            System.err.println("p1 is "+p1);
            System.err.println("expected "+primesTo100[i]);
            failCount++;
        }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i=1; i<aPrimeSequence.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != aPrimeSequence[i]) {
            System.err.println("prime sequence failed");
            failCount++;
        }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i=0; i<100; i+=10) {
        p1 = BigInteger.probablePrime(50 + i, rnd);
        p2 = p1.add(ONE);
        p3 = p1.nextProbablePrime();
        while(p2.compareTo(p3) < 0) {
            if (p2.isProbablePrime(100)){
                System.err.println("nextProbablePrime failed");
                System.err.println("along range "+p1.toString(16));
                System.err.println("to "+p3.toString(16));
                failCount++;
                break;
            }
            p2 = p2.add(ONE);
        }
    }

    report("nextProbablePrime", failCount);
}
 
Example 5
Source File: BigIntegerTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i=0; i<primesTo100.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != primesTo100[i]) {
            System.err.println("low range primes failed");
            System.err.println("p1 is "+p1);
            System.err.println("expected "+primesTo100[i]);
            failCount++;
        }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i=1; i<aPrimeSequence.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != aPrimeSequence[i]) {
            System.err.println("prime sequence failed");
            failCount++;
        }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i=0; i<100; i+=10) {
        p1 = BigInteger.probablePrime(50 + i, rnd);
        p2 = p1.add(ONE);
        p3 = p1.nextProbablePrime();
        while(p2.compareTo(p3) < 0) {
            if (p2.isProbablePrime(100)){
                System.err.println("nextProbablePrime failed");
                System.err.println("along range "+p1.toString(16));
                System.err.println("to "+p3.toString(16));
                failCount++;
                break;
            }
            p2 = p2.add(ONE);
        }
    }

    report("nextProbablePrime", failCount);
}
 
Example 6
Source File: BigIntUtilitiesTest.java    From secretshare with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testBitsPrime()
    throws NoSuchAlgorithmException
{
    final int bits = 194;  // 24 characters plus a little extra

    Random random = new SecureRandom(); // let the system pick our provider
    BigInteger bi = BigInteger.probablePrime(bits, random);
    System.out.println("ProbablePrime(" + bits + ")=" + bi);
    System.out.println("                  =" + bi.toString(16));
    System.out.println("                  =" +
                       BigIntUtilities.Checksum.createMd5CheckSumString(bi));
    System.out.println("  bitlength=" + bi.bitLength());
    System.out.println("  bitcount =" + bi.bitCount());
    final int certainty = Integer.MAX_VALUE; //10000000;
    if (true)
    {
        if (! bi.isProbablePrime(certainty))
        {
            System.out.println("***** did not pass certainty=" + certainty);
        }
        else
        {
            System.out.println("passed certainty " + certainty);
        }
    }
    if (runPassesMillerRabin)
    {
        // this takes 2+ seconds with 10,000 iterations

        int iterations = 10000;
        final long start = new java.util.Date().getTime();
        if (! passesMillerRabin(bi, iterations, null))
        {
            System.out.println("***** did not pass iterations=" + iterations);
        }
        else
        {
            System.out.println("passed iterations " + iterations);
        }

        final long stop = new java.util.Date().getTime();
        System.out.println("Iterations, time elapsed=" + (stop - start));
    }
}
 
Example 7
Source File: Exercise32_UniqueSubstrings.java    From algorithms-sedgewick-wayne with MIT License 4 votes vote down vote up
private long longRandomPrime() {
    BigInteger prime = BigInteger.probablePrime(31, new Random());
    return prime.longValue();
}
 
Example 8
Source File: BigIntegerTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i=0; i<primesTo100.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != primesTo100[i]) {
            System.err.println("low range primes failed");
            System.err.println("p1 is "+p1);
            System.err.println("expected "+primesTo100[i]);
            failCount++;
        }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i=1; i<aPrimeSequence.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != aPrimeSequence[i]) {
            System.err.println("prime sequence failed");
            failCount++;
        }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i=0; i<100; i+=10) {
        p1 = BigInteger.probablePrime(50 + i, rnd);
        p2 = p1.add(ONE);
        p3 = p1.nextProbablePrime();
        while(p2.compareTo(p3) < 0) {
            if (p2.isProbablePrime(100)){
                System.err.println("nextProbablePrime failed");
                System.err.println("along range "+p1.toString(16));
                System.err.println("to "+p3.toString(16));
                failCount++;
                break;
            }
            p2 = p2.add(ONE);
        }
    }

    report("nextProbablePrime", failCount);
}
 
Example 9
Source File: RSAKeyPairGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(n, e);
            PrivateKey privateKey =
                    new RSAPrivateCrtKeyImpl(n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 10
Source File: Exercise33_RandomPrimes.java    From algorithms-sedgewick-wayne with MIT License 4 votes vote down vote up
@Override
protected long longRandomPrime() {
    BigInteger prime = BigInteger.probablePrime(31, new Random());
    return prime.longValue();
}
 
Example 11
Source File: RSAKeyPairGenerator.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(n, e);
            PrivateKey privateKey =
                    new RSAPrivateCrtKeyImpl(n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 12
Source File: RSAKeyPairGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(n, e);
            PrivateKey privateKey =
                    new RSAPrivateCrtKeyImpl(n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 13
Source File: RSAKeyPairGenerator.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(n, e);
            PrivateKey privateKey =
                    new RSAPrivateCrtKeyImpl(n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 14
Source File: BigIntegerTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i=0; i<primesTo100.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != primesTo100[i]) {
            System.err.println("low range primes failed");
            System.err.println("p1 is "+p1);
            System.err.println("expected "+primesTo100[i]);
            failCount++;
        }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i=1; i<aPrimeSequence.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != aPrimeSequence[i]) {
            System.err.println("prime sequence failed");
            failCount++;
        }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i=0; i<100; i+=10) {
        p1 = BigInteger.probablePrime(50 + i, rnd);
        p2 = p1.add(ONE);
        p3 = p1.nextProbablePrime();
        while(p2.compareTo(p3) < 0) {
            if (p2.isProbablePrime(100)){
                System.err.println("nextProbablePrime failed");
                System.err.println("along range "+p1.toString(16));
                System.err.println("to "+p3.toString(16));
                failCount++;
                break;
            }
            p2 = p2.add(ONE);
        }
    }

    report("nextProbablePrime", failCount);
}
 
Example 15
Source File: RSAKeyPairGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(rsaId, n, e);
            PrivateKey privateKey = new RSAPrivateCrtKeyImpl(
                rsaId, n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 16
Source File: BigIntegerTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i=0; i<primesTo100.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != primesTo100[i]) {
            System.err.println("low range primes failed");
            System.err.println("p1 is "+p1);
            System.err.println("expected "+primesTo100[i]);
            failCount++;
        }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i=1; i<aPrimeSequence.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != aPrimeSequence[i]) {
            System.err.println("prime sequence failed");
            failCount++;
        }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i=0; i<100; i+=10) {
        p1 = BigInteger.probablePrime(50 + i, rnd);
        p2 = p1.add(ONE);
        p3 = p1.nextProbablePrime();
        while(p2.compareTo(p3) < 0) {
            if (p2.isProbablePrime(100)){
                System.err.println("nextProbablePrime failed");
                System.err.println("along range "+p1.toString(16));
                System.err.println("to "+p3.toString(16));
                failCount++;
                break;
            }
            p2 = p2.add(ONE);
        }
    }

    report("nextProbablePrime", failCount);
}
 
Example 17
Source File: BigIntegerTest.java    From native-obfuscator with GNU General Public License v3.0 4 votes vote down vote up
public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i=0; i<primesTo100.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != primesTo100[i]) {
            System.err.println("low range primes failed");
            System.err.println("p1 is "+p1);
            System.err.println("expected "+primesTo100[i]);
            failCount++;
        }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i=1; i<aPrimeSequence.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != aPrimeSequence[i]) {
            System.err.println("prime sequence failed");
            failCount++;
        }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i=0; i<100; i+=10) {
        p1 = BigInteger.probablePrime(50 + i, rnd);
        p2 = p1.add(ONE);
        p3 = p1.nextProbablePrime();
        while(p2.compareTo(p3) < 0) {
            if (p2.isProbablePrime(100)){
                System.err.println("nextProbablePrime failed");
                System.err.println("along range "+p1.toString(16));
                System.err.println("to "+p3.toString(16));
                failCount++;
                break;
            }
            p2 = p2.add(ONE);
        }
    }

    report("nextProbablePrime", failCount);
}
 
Example 18
Source File: BigIntegerTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i=0; i<primesTo100.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != primesTo100[i]) {
            System.err.println("low range primes failed");
            System.err.println("p1 is "+p1);
            System.err.println("expected "+primesTo100[i]);
            failCount++;
        }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i=1; i<aPrimeSequence.length; i++) {
        p1 = p1.nextProbablePrime();
        if (p1.longValue() != aPrimeSequence[i]) {
            System.err.println("prime sequence failed");
            failCount++;
        }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i=0; i<100; i+=10) {
        p1 = BigInteger.probablePrime(50 + i, rnd);
        p2 = p1.add(ONE);
        p3 = p1.nextProbablePrime();
        while(p2.compareTo(p3) < 0) {
            if (p2.isProbablePrime(100)){
                System.err.println("nextProbablePrime failed");
                System.err.println("along range "+p1.toString(16));
                System.err.println("to "+p3.toString(16));
                failCount++;
                break;
            }
            p2 = p2.add(ONE);
        }
    }

    report("nextProbablePrime", failCount);
}
 
Example 19
Source File: RSAKeyPairGenerator.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public KeyPair generateKeyPair() {
    // accommodate odd key sizes in case anybody wants to use them
    int lp = (keySize + 1) >> 1;
    int lq = keySize - lp;
    if (random == null) {
        random = JCAUtil.getSecureRandom();
    }
    BigInteger e = publicExponent;
    while (true) {
        // generate two random primes of size lp/lq
        BigInteger p = BigInteger.probablePrime(lp, random);
        BigInteger q, n;
        do {
            q = BigInteger.probablePrime(lq, random);
            // convention is for p > q
            if (p.compareTo(q) < 0) {
                BigInteger tmp = p;
                p = q;
                q = tmp;
            }
            // modulus n = p * q
            n = p.multiply(q);
            // even with correctly sized p and q, there is a chance that
            // n will be one bit short. re-generate the smaller prime if so
        } while (n.bitLength() < keySize);

        // phi = (p - 1) * (q - 1) must be relative prime to e
        // otherwise RSA just won't work ;-)
        BigInteger p1 = p.subtract(BigInteger.ONE);
        BigInteger q1 = q.subtract(BigInteger.ONE);
        BigInteger phi = p1.multiply(q1);
        // generate new p and q until they work. typically
        // the first try will succeed when using F4
        if (e.gcd(phi).equals(BigInteger.ONE) == false) {
            continue;
        }

        // private exponent d is the inverse of e mod phi
        BigInteger d = e.modInverse(phi);

        // 1st prime exponent pe = d mod (p - 1)
        BigInteger pe = d.mod(p1);
        // 2nd prime exponent qe = d mod (q - 1)
        BigInteger qe = d.mod(q1);

        // crt coefficient coeff is the inverse of q mod p
        BigInteger coeff = q.modInverse(p);

        try {
            PublicKey publicKey = new RSAPublicKeyImpl(n, e);
            PrivateKey privateKey =
                    new RSAPrivateCrtKeyImpl(n, e, d, p, q, pe, qe, coeff);
            return new KeyPair(publicKey, privateKey);
        } catch (InvalidKeyException exc) {
            // invalid key exception only thrown for keys < 512 bit,
            // will not happen here
            throw new RuntimeException(exc);
        }
    }
}
 
Example 20
Source File: Primes.java    From protect with MIT License 2 votes vote down vote up
/**
 * Generates a prime number of the requested number of bits using a
 * cryptographically secure random number generator.
 * 
 * @param bitLength
 * @return A BigInteger representing a randomly prime number.
 */
public static BigInteger generatePrime(final int bitLength) {
	return BigInteger.probablePrime(bitLength, new SecureRandom());
}