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

The following examples show how to use java.math.BigInteger#isProbablePrime() . These examples are extracted from open source projects. 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
public static void main(String[] args) throws IOException {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	String s;
	while (!(s=br.readLine()).equals("0")) {
		BigInteger largestPrime=BigInteger.ZERO;
		for (int start=0;start<s.length();start++) {
			for (int end=start+1;end<=s.length() && end<=start+5;end++) {
				BigInteger test=new BigInteger(s.substring(start,end));
				if (test.isProbablePrime(10) && test.compareTo(largestPrime)>0) {
					largestPrime=test;
				}
			}
		}
		System.out.println(largestPrime);
	}
}
 
Example 2
/**
 * Add a local primes cache, to save some time for primes computation
 *
 * @param n the requested size of the list
 * @throws NotEnoughPrimesInGroupException if the encryption group is too small to yield the requested number of $
 *                                         primes
 */
public synchronized void populatePrimesCache(int n) throws NotEnoughPrimesInGroupException {
    Preconditions.checkState(cachedPrimes == null, "The primes cache can only be initialized" +
            "once...");
    BigInteger x = BigInteger.ONE;
    ImmutableList.Builder<BigInteger> cacheBuilder = ImmutableList.builder();
    int i = 0;
    while (i < n) {
        do {
            // Performance improvement over +1 / +2 defined in algorithm
            x = x.nextProbablePrime();
            if (x.compareTo(encryptionGroup.getP()) >= 0)
                throw new NotEnoughPrimesInGroupException(
                        String.format("Only found %d primes (%s) in group %s",
                                i,
                                Joiner.on(",").join(
                                        cacheBuilder.build().stream().limit(4)
                                                .collect(Collectors.toList())), encryptionGroup));
        } while (!x.isProbablePrime(100) || !isMember(x));
        cacheBuilder.add(x);
        i++;
    }

    cachedPrimes = cacheBuilder.build();
}
 
Example 3
/**
 * Verifies whether a specified subset of Mersenne primes are correctly
 * identified as being prime. See
 * <a href="https://en.wikipedia.org/wiki/Mersenne_prime">Mersenne prime</a>
 * for more information.
 *
 * @return true if and only if the test succeeds
 */
private static boolean checkMersennePrimes(int certainty) {
    int[] MERSENNE_EXPONENTS = {
        2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
        2281, 3217, 4253, // uncomment remaining array elements to make this test run a long time
        /* 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497,
        86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269,
        2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951,
        30402457, 32582657, 37156667, 42643801, 43112609, 57885161 */
    };
    System.out.println("Checking first "+MERSENNE_EXPONENTS.length+" Mersenne primes");

    boolean result = true;
    for (int n : MERSENNE_EXPONENTS) {
        BigInteger mp = BigInteger.ONE.shiftLeft(n).subtract(BigInteger.ONE);
        if (!mp.isProbablePrime(certainty)) {
            System.err.println("Mp with p = "+n+" not classified as prime");
            result = false;
        }
    }

    return result;
}
 
Example 4
private static void checkKeyPair(KeyPair kp, int pSize) throws Exception {

        DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
        BigInteger p = privateKey.getParams().getP();
        if (p.bitLength() != pSize) {
            throw new Exception(
                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
        }

        if (!p.isProbablePrime(128)) {
            throw new Exception("Good luck, the modulus is composite!");
        }

        DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
        p = publicKey.getParams().getP();
        if (p.bitLength() != pSize) {
            throw new Exception(
                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
        }

        BigInteger leftOpen = BigInteger.ONE;
        BigInteger rightOpen = p.subtract(BigInteger.ONE);

        BigInteger x = privateKey.getX();
        if ((x.compareTo(leftOpen) <= 0) ||
                (x.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
        }

        BigInteger y = publicKey.getY();
        if ((y.compareTo(leftOpen) <= 0) ||
                (y.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "Y outside range [2, p - 2]:  x: " + x + " p: " + p);
        }
    }
 
Example 5
Source Project: ripple-lib-java   File: JPAKEPrimeOrderGroup.java    License: ISC License 5 votes vote down vote up
/**
 * Internal package-private constructor used by the pre-approved
 * groups in {@link JPAKEPrimeOrderGroups}.
 * These pre-approved groups can avoid the expensive checks.
 */
JPAKEPrimeOrderGroup(BigInteger p, BigInteger q, BigInteger g, boolean skipChecks)
{
    JPAKEUtil.validateNotNull(p, "p");
    JPAKEUtil.validateNotNull(q, "q");
    JPAKEUtil.validateNotNull(g, "g");

    if (!skipChecks)
    {
        if (!p.subtract(JPAKEUtil.ONE).mod(q).equals(JPAKEUtil.ZERO))
        {
            throw new IllegalArgumentException("p-1 must be evenly divisible by q");
        }
        if (g.compareTo(BigInteger.valueOf(2)) == -1 || g.compareTo(p.subtract(JPAKEUtil.ONE)) == 1)
        {
            throw new IllegalArgumentException("g must be in [2, p-1]");
        }
        if (!g.modPow(q, p).equals(JPAKEUtil.ONE))
        {
            throw new IllegalArgumentException("g^q mod p must equal 1");
        }
        /*
         * Note that these checks do not guarantee that p and q are prime.
         * We just have reasonable certainty that they are prime.
         */
        if (!p.isProbablePrime(20))
        {
            throw new IllegalArgumentException("p must be prime");
        }
        if (!q.isProbablePrime(20))
        {
            throw new IllegalArgumentException("q must be prime");
        }
    }

    this.p = p;
    this.q = q;
    this.g = g;
}
 
Example 6
public static void main(String[] args) throws IOException {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	while (true) {
		BigInteger bi=new BigInteger(br.readLine());
		if (bi.compareTo(BigInteger.ZERO)<0) {
			break;
		}
		StringBuilder sb=new StringBuilder();
		if (bi.isProbablePrime(10)) {
			sb.append("    ");
			sb.append(bi);
			sb.append("\n");
		} else if (!bi.equals(BigInteger.ZERO)){
			BigInteger biTwo=BigInteger.valueOf(2);
			while (bi.mod(biTwo).equals(BigInteger.ZERO)) {
				bi=bi.divide(biTwo);
				sb.append("    ");
				sb.append(2);
				sb.append("\n");
			}
			for (BigInteger i=BigInteger.valueOf(3);i.multiply(i).compareTo(bi)<0;i=i.add(biTwo)) {
				while (bi.mod(i).equals(BigInteger.ZERO)) {
					bi=bi.divide(i);
					sb.append("    ");
					sb.append(i);
					sb.append("\n");
				}
			}
			if (bi.compareTo(BigInteger.ONE)>0) {
				sb.append("    ");
				sb.append(bi);
				sb.append("\n");
			}
		} else {
			sb.append("\n");
		}
		System.out.println(sb.toString());
	}
}
 
Example 7
Source Project: protect   File: Primes.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the corresponding "safe prime" from a given Sophie-Germain prime
 * prime
 * 
 * @param sophieGermainPrime
 * @return
 */
public static BigInteger getSafePrime(final BigInteger sophieGermainPrime) {
	BigInteger safePrime = (sophieGermainPrime.multiply(TWO)).add(BigInteger.ONE);
	if (safePrime.isProbablePrime(PRIMALITY_TEST_STRENGTH)) {
		return safePrime;
	} else {
		return null;
	}

}
 
Example 8
private static void checkKeyPair(KeyPair kp, int pSize) throws Exception {

        DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
        BigInteger p = privateKey.getParams().getP();
        if (p.bitLength() != pSize) {
            throw new Exception(
                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
        }

        // System.out.println("P(" + pSize + "): " + p.toString());
        if (!p.isProbablePrime(128)) {
            throw new Exception("Good luck, the modulus is composite!");
        }

        DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
        p = publicKey.getParams().getP();
        if (p.bitLength() != pSize) {
            throw new Exception(
                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
        }

        BigInteger leftOpen = BigInteger.ONE;
        BigInteger rightOpen = p.subtract(BigInteger.ONE);

        BigInteger x = privateKey.getX();
        if ((x.compareTo(leftOpen) <= 0) ||
                (x.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
        }

        BigInteger y = publicKey.getY();
        if ((y.compareTo(leftOpen) <= 0) ||
                (y.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "Y outside range [2, p - 2]:  x: " + x + " p: " + p);
        }
    }
 
Example 9
private static void checkKeyPair(KeyPair kp, int pSize) throws Exception {

        DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
        BigInteger p = privateKey.getParams().getP();
        if (p.bitLength() != pSize) {
            throw new Exception(
                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
        }

        // System.out.println("P(" + pSize + "): " + p.toString());
        if (!p.isProbablePrime(128)) {
            throw new Exception("Good luck, the modulus is composite!");
        }

        DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
        p = publicKey.getParams().getP();
        if (p.bitLength() != pSize) {
            throw new Exception(
                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
        }

        BigInteger leftOpen = BigInteger.ONE;
        BigInteger rightOpen = p.subtract(BigInteger.ONE);

        BigInteger x = privateKey.getX();
        if ((x.compareTo(leftOpen) <= 0) ||
                (x.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
        }

        BigInteger y = publicKey.getY();
        if ((y.compareTo(leftOpen) <= 0) ||
                (y.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "Y outside range [2, p - 2]:  x: " + x + " p: " + p);
        }
    }
 
Example 10
private static void checkKeyPair(KeyPair kp, int pSize) throws Exception {

        DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
        BigInteger p = privateKey.getParams().getP();
        if (p.bitLength() != pSize) {
            throw new Exception(
                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
        }

        if (!p.isProbablePrime(128)) {
            throw new Exception("Good luck, the modulus is composite!");
        }

        DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
        p = publicKey.getParams().getP();
        if (p.bitLength() != pSize) {
            throw new Exception(
                "Invalid modulus size: " + p.bitLength() + "/" + pSize);
        }

        BigInteger leftOpen = BigInteger.ONE;
        BigInteger rightOpen = p.subtract(BigInteger.ONE);

        BigInteger x = privateKey.getX();
        if ((x.compareTo(leftOpen) <= 0) ||
                (x.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
        }

        BigInteger y = publicKey.getY();
        if ((y.compareTo(leftOpen) <= 0) ||
                (y.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "Y outside range [2, p - 2]:  x: " + x + " p: " + p);
        }
    }
 
Example 11
/**
 * See <a href="https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm"> Wikipedia: Pollards rho algorithm</a>
 * 
 * @param val
 * @param map
 */
public static void pollardRhoFactors(final BigInteger val, Map<BigInteger, Integer> map) {
	BigInteger factor;
	BigInteger temp = val;
	int iterationCounter = 0;
	Integer count;
	while (!temp.isProbablePrime(32)) {
		factor = rho(temp);
		if (factor.equals(temp)) {
			if (iterationCounter++ > 4) {
				break;
			}
		} else {
			iterationCounter = 1;
		}
		count = map.get(factor);
		if (count == null) {
			map.put(factor, 1);
		} else {
			map.put(factor, count + 1);
		}
		temp = temp.divide(factor);
	}
	count = map.get(temp);
	if (count == null) {
		map.put(temp, 1);
	} else {
		map.put(temp, count + 1);
	}
}
 
Example 12
/**
 * Test.
 * @param args ignored
 */
public static void main(String[] args) {
	ConfigUtil.initProject();
	SquFoF63 squfof63 = new SquFoF63();
	FactorAlgorithm testFactorizer = FactorAlgorithm.DEFAULT;
	
	// test numbers that caused problems with former versions
	BigInteger N0 = BigInteger.valueOf(1099511627970L); // 2*3*5*7*23*227642159
	LOG.info("Factoring N=" + N0 + ":");
	SortedMultiset<BigInteger> correctFactors = testFactorizer.factor(N0);
	LOG.info("testFactorizer found " + correctFactors);
	SortedMultiset<BigInteger> squfofFactors = squfof63.factor(N0);
	LOG.info("SquFoF63 found " + squfofFactors);
	
	// test random N
	SecureRandom RNG = new SecureRandom();
	int count = 100000;
	for (int bits=52; bits<63; bits++) {
		LOG.info("Testing " + count + " random numbers with " + bits + " bits...");
		int failCount = 0;
		for (int i=0; i<count; i++) {
			long N = 0;
			while (true) { 
				BigInteger N_big = new BigInteger(bits, RNG);
				N = N_big.longValue();
				if (N>2 && !N_big.isProbablePrime(20)) break;
			}
			long tdivFactor = squfof63.findSingleFactor(N);
			if (tdivFactor<2) {
				long squfofFactor = testFactorizer.findSingleFactor(BigInteger.valueOf(N)).longValue();
				if (squfofFactor > 1 && squfofFactor<N) {
					//LOG.debug("N=" + N + ": TDiv failed to find factor " + squfofFactor);
					failCount++;
				} else {
					LOG.error("Squfof63 failed to factor N=" + N + " !");
				}
			} else {
				if (N%tdivFactor!=0) {
					failCount++;
				}
			}
		}
		LOG.info("    #fails = " + failCount);
	}
}
 
Example 13
@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 14
private static void checkKeyPair(KeyPair kp, int pSize,
            Provider provider) throws Exception {

    DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
    BigInteger p = privateKey.getParams().getP();
    if (p.bitLength() != pSize) {
        throw new Exception(
            "Invalid modulus size: " + p.bitLength() + "/" + pSize);
    }

    // System.out.println("P(" + pSize + "): " + p.toString());
    if (!p.isProbablePrime(128)) {
        throw new Exception("Good luck, the modulus is composite!");
    }

    DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
    p = publicKey.getParams().getP();
    if (p.bitLength() != pSize) {
        throw new Exception(
            "Invalid modulus size: " + p.bitLength() + "/" + pSize);
    }

    BigInteger leftOpen = BigInteger.ONE;
    BigInteger rightOpen = p.subtract(BigInteger.ONE);

    // ignore the private key range checking on Solaris at present
    if (provider.getName().equals("SunPKCS11-Solaris") &&
            !System.getProperty("os.name").equals("SunOS")) {
        BigInteger x = privateKey.getX();
        if ((x.compareTo(leftOpen) <= 0) ||
                (x.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
        }
    }

    BigInteger y = publicKey.getY();
    if ((y.compareTo(leftOpen) <= 0) ||
            (y.compareTo(rightOpen) >= 0)) {
        throw new Exception(
            "Y outside range [2, p - 2]:  y: " + y + " p: " + p);
    }
}
 
Example 15
Source Project: RipplePower   File: IntegerFunctions.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Compute the next probable prime greater than <tt>n</tt> with the
 * specified certainty.
 *
 * @param n         a integer number
 * @param certainty the certainty that the generated number is prime
 * @return the next prime greater than <tt>n</tt>
 */
public static BigInteger nextProbablePrime(BigInteger n, int certainty)
{

    if (n.signum() < 0 || n.signum() == 0 || n.equals(ONE))
    {
        return TWO;
    }

    BigInteger result = n.add(ONE);

    // Ensure an odd number
    if (!result.testBit(0))
    {
        result = result.add(ONE);
    }

    while (true)
    {
        // Do cheap "pre-test" if applicable
        if (result.bitLength() > 6)
        {
            long r = result.remainder(
                BigInteger.valueOf(SMALL_PRIME_PRODUCT)).longValue();
            if ((r % 3 == 0) || (r % 5 == 0) || (r % 7 == 0)
                || (r % 11 == 0) || (r % 13 == 0) || (r % 17 == 0)
                || (r % 19 == 0) || (r % 23 == 0) || (r % 29 == 0)
                || (r % 31 == 0) || (r % 37 == 0) || (r % 41 == 0))
            {
                result = result.add(TWO);
                continue; // Candidate is composite; try another
            }
        }

        // All candidates of bitLength 2 and 3 are prime by this point
        if (result.bitLength() < 4)
        {
            return result;
        }

        // The expensive test
        if (result.isProbablePrime(certainty))
        {
            return result;
        }

        result = result.add(TWO);
    }
}
 
Example 16
Source Project: ripple-lib-java   File: IntegerFunctions.java    License: ISC License 4 votes vote down vote up
/**
 * Compute the next probable prime greater than <tt>n</tt> with the
 * specified certainty.
 *
 * @param n         a integer number
 * @param certainty the certainty that the generated number is prime
 * @return the next prime greater than <tt>n</tt>
 */
public static BigInteger nextProbablePrime(BigInteger n, int certainty)
{

    if (n.signum() < 0 || n.signum() == 0 || n.equals(ONE))
    {
        return TWO;
    }

    BigInteger result = n.add(ONE);

    // Ensure an odd number
    if (!result.testBit(0))
    {
        result = result.add(ONE);
    }

    while (true)
    {
        // Do cheap "pre-test" if applicable
        if (result.bitLength() > 6)
        {
            long r = result.remainder(
                BigInteger.valueOf(SMALL_PRIME_PRODUCT)).longValue();
            if ((r % 3 == 0) || (r % 5 == 0) || (r % 7 == 0)
                || (r % 11 == 0) || (r % 13 == 0) || (r % 17 == 0)
                || (r % 19 == 0) || (r % 23 == 0) || (r % 29 == 0)
                || (r % 31 == 0) || (r % 37 == 0) || (r % 41 == 0))
            {
                result = result.add(TWO);
                continue; // Candidate is composite; try another
            }
        }

        // All candidates of bitLength 2 and 3 are prime by this point
        if (result.bitLength() < 4)
        {
            return result;
        }

        // The expensive test
        if (result.isProbablePrime(certainty))
        {
            return result;
        }

        result = result.add(TWO);
    }
}
 
Example 17
private DSAParameters generateParameters_FIPS186_2()
{
    byte[]          seed = new byte[20];
    byte[]          part1 = new byte[20];
    byte[]          part2 = new byte[20];
    byte[]          u = new byte[20];
    int             n = (L - 1) / 160;
    byte[]          w = new byte[L / 8];

    if (!(digest instanceof SHA1Digest))
    {
        throw new IllegalStateException("can only use SHA-1 for generating FIPS 186-2 parameters");
    }

    for (;;)
    {
        random.nextBytes(seed);

        hash(digest, seed, part1);
        System.arraycopy(seed, 0, part2, 0, seed.length);
        inc(part2);
        hash(digest, part2, part2);

        for (int i = 0; i != u.length; i++)
        {
            u[i] = (byte)(part1[i] ^ part2[i]);
        }

        u[0] |= (byte)0x80;
        u[19] |= (byte)0x01;

        BigInteger q = new BigInteger(1, u);

        if (!q.isProbablePrime(certainty))
        {
            continue;
        }

        byte[] offset = Arrays.clone(seed);
        inc(offset);

        for (int counter = 0; counter < 4096; ++counter)
        {
            for (int k = 0; k < n; k++)
            {
                inc(offset);
                hash(digest, offset, part1);
                System.arraycopy(part1, 0, w, w.length - (k + 1) * part1.length, part1.length);
            }

            inc(offset);
            hash(digest, offset, part1);
            System.arraycopy(part1, part1.length - ((w.length - (n) * part1.length)), w, 0, w.length - n * part1.length);

            w[0] |= (byte)0x80;

            BigInteger x = new BigInteger(1, w);

            BigInteger c = x.mod(q.shiftLeft(1));

            BigInteger p = x.subtract(c.subtract(ONE));

            if (p.bitLength() != L)
            {
                continue;
            }

            if (p.isProbablePrime(certainty))
            {
                BigInteger g = calculateGenerator_FIPS186_2(p, q, random);

                return new DSAParameters(p, q, g, new DSAValidationParameters(seed, counter));
            }
        }
    }
}
 
Example 18
/**
 * Test.
 * @param args ignored
 */
public static void main(String[] args) {
	ConfigUtil.initProject();
	SquFoF31 squfof31 = new SquFoF31();
	FactorAlgorithm testFactorizer = FactorAlgorithm.DEFAULT;
	
	// test numbers that caused problems with former versions
	BigInteger N0 = BigInteger.valueOf(1099511627970L); // 2*3*5*7*23*227642159
	LOG.info("Factoring N=" + N0 + ":");
	SortedMultiset<BigInteger> correctFactors = testFactorizer.factor(N0);
	LOG.info("testFactorizer found " + correctFactors);
	SortedMultiset<BigInteger> squfofFactors = squfof31.factor(N0);
	LOG.info("SquFoF31 found " + squfofFactors);
	
	// test random N
	SecureRandom RNG = new SecureRandom();
	int count = 100000;
	for (int bits=52; bits<63; bits++) {
		LOG.info("Testing " + count + " random numbers with " + bits + " bits...");
		int failCount = 0;
		for (int i=0; i<count; i++) {
			long N = 0;
			while (true) { 
				BigInteger N_big = new BigInteger(bits, RNG);
				N = N_big.longValue();
				if (N>2 && !N_big.isProbablePrime(20)) break;
			}
			long tdivFactor = squfof31.findSingleFactor(N);
			if (tdivFactor<2) {
				long squfofFactor = testFactorizer.findSingleFactor(BigInteger.valueOf(N)).longValue();
				if (squfofFactor > 1 && squfofFactor<N) {
					//LOG.debug("N=" + N + ": TDiv failed to find factor " + squfofFactor);
					failCount++;
				} else {
					LOG.error("Squfof63 failed to factor N=" + N + " !");
				}
			} else {
				if (N%tdivFactor!=0) {
					failCount++;
				}
			}
		}
		LOG.info("    #fails = " + failCount);
	}
}
 
Example 19
private static void checkKeyPair(KeyPair kp, int pSize,
            Provider provider) throws Exception {

    DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
    BigInteger p = privateKey.getParams().getP();
    if (p.bitLength() != pSize) {
        throw new Exception(
            "Invalid modulus size: " + p.bitLength() + "/" + pSize);
    }

    // System.out.println("P(" + pSize + "): " + p.toString());
    if (!p.isProbablePrime(128)) {
        throw new Exception("Good luck, the modulus is composite!");
    }

    DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
    p = publicKey.getParams().getP();
    if (p.bitLength() != pSize) {
        throw new Exception(
            "Invalid modulus size: " + p.bitLength() + "/" + pSize);
    }

    BigInteger leftOpen = BigInteger.ONE;
    BigInteger rightOpen = p.subtract(BigInteger.ONE);

    // ignore the private key range checking on Solaris at present
    if (provider.getName().equals("SunPKCS11-Solaris") &&
            !System.getProperty("os.name").equals("SunOS")) {
        BigInteger x = privateKey.getX();
        if ((x.compareTo(leftOpen) <= 0) ||
                (x.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
        }
    }

    BigInteger y = publicKey.getY();
    if ((y.compareTo(leftOpen) <= 0) ||
            (y.compareTo(rightOpen) >= 0)) {
        throw new Exception(
            "Y outside range [2, p - 2]:  y: " + y + " p: " + p);
    }
}
 
Example 20
private static void checkKeyPair(KeyPair kp, int pSize,
            Provider provider) throws Exception {

    DHPrivateKey privateKey = (DHPrivateKey)kp.getPrivate();
    BigInteger p = privateKey.getParams().getP();
    if (p.bitLength() != pSize) {
        throw new Exception(
            "Invalid modulus size: " + p.bitLength() + "/" + pSize);
    }

    // System.out.println("P(" + pSize + "): " + p.toString());
    if (!p.isProbablePrime(128)) {
        throw new Exception("Good luck, the modulus is composite!");
    }

    DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
    p = publicKey.getParams().getP();
    if (p.bitLength() != pSize) {
        throw new Exception(
            "Invalid modulus size: " + p.bitLength() + "/" + pSize);
    }

    BigInteger leftOpen = BigInteger.ONE;
    BigInteger rightOpen = p.subtract(BigInteger.ONE);

    // ignore the private key range checking on Solaris at present
    if (!provider.getName().equals("SunPKCS11-Solaris")) {
        BigInteger x = privateKey.getX();
        if ((x.compareTo(leftOpen) <= 0) ||
                (x.compareTo(rightOpen) >= 0)) {
            throw new Exception(
                "X outside range [2, p - 2]:  x: " + x + " p: " + p);
        }
    }

    BigInteger y = publicKey.getY();
    if ((y.compareTo(leftOpen) <= 0) ||
            (y.compareTo(rightOpen) >= 0)) {
        throw new Exception(
            "Y outside range [2, p - 2]:  y: " + y + " p: " + p);
    }
}