当前位置: 首页>>代码示例>>Java>>正文


Java BigInteger.isProbablePrime方法代码示例

本文整理汇总了Java中java.math.BigInteger.isProbablePrime方法的典型用法代码示例。如果您正苦于以下问题:Java BigInteger.isProbablePrime方法的具体用法?Java BigInteger.isProbablePrime怎么用?Java BigInteger.isProbablePrime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.math.BigInteger的用法示例。


在下文中一共展示了BigInteger.isProbablePrime方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import java.math.BigInteger; //导入方法依赖的package包/类
public static void main(String[] args) {
	try (
			Scanner in = new Scanner(System.in);
			PrintWriter out = new PrintWriter(System.out);
	) {
		BigInteger n = in.nextBigInteger();

		// validation(constraints)
		assert (n.toString().length() <= 100);

		/**
		 * check if the number is prime using 'isProbablePrime' method
		 * For reference: if certainty is 10, then 1 - 1/2^10 is approximately 99.9%
		 * I gotta study for Miller-Rabin && Lucas-Lehmer
		 **/
		if (n.isProbablePrime(10)) {
			out.println("prime");
		} else {
			out.println("not prime");
		}
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
开发者ID:jsong00505,项目名称:HackerRank-Studies,代码行数:26,代码来源:Solution.java

示例2: validateDHPublicKey

import java.math.BigInteger; //导入方法依赖的package包/类
public static DHPublicKeyParameters validateDHPublicKey(DHPublicKeyParameters key)
    throws IOException
{
    BigInteger Y = key.getY();
    DHParameters params = key.getParameters();
    BigInteger p = params.getP();
    BigInteger g = params.getG();

    if (!p.isProbablePrime(2))
    {
        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
    }
    if (g.compareTo(TWO) < 0 || g.compareTo(p.subtract(TWO)) > 0)
    {
        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
    }
    if (Y.compareTo(TWO) < 0 || Y.compareTo(p.subtract(ONE)) > 0)
    {
        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
    }

    // TODO See RFC 2631 for more discussion of Diffie-Hellman validation

    return key;
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:26,代码来源:TlsDHUtils.java

示例3: checkMersennePrimes

import java.math.BigInteger; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:31,代码来源:PrimeTest.java

示例4: populatePrimesCache

import java.math.BigInteger; //导入方法依赖的package包/类
/**
 * 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();
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:32,代码来源:GeneralAlgorithms.java

示例5: isPrime

import java.math.BigInteger; //导入方法依赖的package包/类
public static boolean isPrime(BigInteger number) {
    if (!number.isProbablePrime(5))
        return false;
    BigInteger two = new BigInteger("2");
    if (!two.equals(number) && BigInteger.ZERO.equals(number.mod(two)))
        return false;
    for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(number) < 1; i = i.add(two))
        if (BigInteger.ZERO.equals(number.mod(i)))
            return false;
    return true;
}
 
开发者ID:Baizey,项目名称:Helpers,代码行数:12,代码来源:Numbers.java

示例6: JPAKEPrimeOrderGroup

import java.math.BigInteger; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:44,代码来源:JPAKEPrimeOrderGroup.java

示例7: checkKeyPair

import java.math.BigInteger; //导入方法依赖的package包/类
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);
        }
    }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:39,代码来源:SupportedDHKeys.java

示例8: checkKeyPair

import java.math.BigInteger; //导入方法依赖的package包/类
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);
        }
    }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:38,代码来源:SupportedDHParamGens.java

示例9: createIdentificationGroup

import java.math.BigInteger; //导入方法依赖的package包/类
private IdentificationGroup createIdentificationGroup(BigInteger p_hat, SecurityParameters securityParameters) {
    log.info("creating identification group");
    IdentificationGroup identificationGroup = null;
    while (identificationGroup == null) {
        BigInteger p_hatMinusOne = p_hat.subtract(ONE);

        BigInteger k = TWO;
        while (p_hatMinusOne.mod(k).compareTo(ZERO) != 0) {
            k = k.add(ONE);
        }
        BigInteger q_hat = p_hatMinusOne.divide(k);
        if (!q_hat.isProbablePrime(100)) {
            log.info("q_hat is not prime");
            continue;
        }
        if (q_hat.bitLength() < 2 * securityParameters.getTau()) {
            log.info("|q_hat| < 2*mu");
            continue;
        }

        BigInteger i = randomGenerator.randomInZq(p_hat);
        while (modExp(i, k, p_hat).compareTo(ONE) == 0) {
            i = randomGenerator.randomInZq(p_hat);
        }
        BigInteger g_hat = modExp(i, k, p_hat);

        try {
            identificationGroup = new IdentificationGroup(p_hat, q_hat, g_hat);
        } catch (IllegalArgumentException e) {
            log.warn("failed to create identification group", e);
            identificationGroup = null;
        }
    }
    log.info("created identification group");
    return identificationGroup;
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:37,代码来源:Simulation.java

示例10: createEncryptionGroup

import java.math.BigInteger; //导入方法依赖的package包/类
private EncryptionGroup createEncryptionGroup(BigInteger p) {
    log.info("creating encryption group");
    EncryptionGroup encryptionGroup = null;

    while (encryptionGroup == null) {
        if (!p.isProbablePrime(100)) {
            log.info("p is not prime...");
            continue;
        }

        BigInteger pMinusOne = p.subtract(ONE);
        BigInteger q = pMinusOne.shiftRight(1);
        if (!q.isProbablePrime(100)) {
            log.info("q is not prime...");
        }

        BigInteger g = getGenerator(q, p, pMinusOne);

        BigInteger h = randomGenerator.randomInGq(new EncryptionGroup(p, q, g, TWO));

        try {
            encryptionGroup = new EncryptionGroup(p, q, g, h);
        } catch (IllegalArgumentException e) {
            log.warn("Encryption group creation failed", e);
            encryptionGroup = null;
        }
    }
    log.info("encryption group created: " + encryptionGroup);
    return encryptionGroup;
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:31,代码来源:Simulation.java

示例11: nextProbablePrime

import java.math.BigInteger; //导入方法依赖的package包/类
/**
 * 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);
    }
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:57,代码来源:IntegerFunctions.java

示例12: generateParameters_FIPS186_2

import java.math.BigInteger; //导入方法依赖的package包/类
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));
            }
        }
    }
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:77,代码来源:DSAParametersGenerator.java

示例13: checkKeyPair

import java.math.BigInteger; //导入方法依赖的package包/类
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);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:43,代码来源:SupportedDHKeys.java


注:本文中的java.math.BigInteger.isProbablePrime方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。