1package org.bouncycastle.crypto.generators;
2
3import java.math.BigInteger;
4import java.security.SecureRandom;
5
6// BEGIN android-added
7import java.util.logging.Logger;
8// END android-added
9import org.bouncycastle.util.BigIntegers;
10
11class DHParametersHelper
12{
13    // BEGIN android-added
14    private static final Logger logger = Logger.getLogger(DHParametersHelper.class.getName());
15    // END android-added
16
17    private static final BigInteger ONE = BigInteger.valueOf(1);
18    private static final BigInteger TWO = BigInteger.valueOf(2);
19
20    /*
21     * Finds a pair of prime BigInteger's {p, q: p = 2q + 1}
22     *
23     * (see: Handbook of Applied Cryptography 4.86)
24     */
25    static BigInteger[] generateSafePrimes(int size, int certainty, SecureRandom random)
26    {
27        // BEGIN android-added
28        logger.info("Generating safe primes. This may take a long time.");
29        long start = System.currentTimeMillis();
30        int tries = 0;
31        // END android-added
32        BigInteger p, q;
33        int qLength = size - 1;
34
35        for (;;)
36        {
37            // BEGIN android-added
38            tries++;
39            // END android-added
40            q = new BigInteger(qLength, 2, random);
41
42            // p <- 2q + 1
43            p = q.shiftLeft(1).add(ONE);
44
45            if (p.isProbablePrime(certainty) && (certainty <= 2 || q.isProbablePrime(certainty)))
46            {
47                break;
48            }
49        }
50        // BEGIN android-added
51        long end = System.currentTimeMillis();
52        long duration = end - start;
53        logger.info("Generated safe primes: " + tries + " tries took " + duration + "ms");
54        // END android-added
55
56        return new BigInteger[] { p, q };
57    }
58
59    /*
60     * Select a high order element of the multiplicative group Zp*
61     *
62     * p and q must be s.t. p = 2*q + 1, where p and q are prime (see generateSafePrimes)
63     */
64    static BigInteger selectGenerator(BigInteger p, BigInteger q, SecureRandom random)
65    {
66        BigInteger pMinusTwo = p.subtract(TWO);
67        BigInteger g;
68
69        /*
70         * (see: Handbook of Applied Cryptography 4.80)
71         */
72//        do
73//        {
74//            g = BigIntegers.createRandomInRange(TWO, pMinusTwo, random);
75//        }
76//        while (g.modPow(TWO, p).equals(ONE) || g.modPow(q, p).equals(ONE));
77
78
79        /*
80         * RFC 2631 2.2.1.2 (and see: Handbook of Applied Cryptography 4.81)
81         */
82        do
83        {
84            BigInteger h = BigIntegers.createRandomInRange(TWO, pMinusTwo, random);
85
86            g = h.modPow(TWO, p);
87        }
88        while (g.equals(ONE));
89
90
91        return g;
92    }
93}
94