1package org.bouncycastle.crypto.generators;
2
3import org.bouncycastle.crypto.params.DHParameters;
4
5import java.math.BigInteger;
6import java.security.SecureRandom;
7
8public class DHParametersGenerator
9{
10    private int             size;
11    private int             certainty;
12    private SecureRandom    random;
13
14    private static final BigInteger TWO = BigInteger.valueOf(2);
15
16    /**
17     * Initialise the parameters generator.
18     *
19     * @param size bit length for the prime p
20     * @param certainty level of certainty for the prime number tests
21     * @param random  a source of randomness
22     */
23    public void init(
24        int             size,
25        int             certainty,
26        SecureRandom    random)
27    {
28        this.size = size;
29        this.certainty = certainty;
30        this.random = random;
31    }
32
33    /**
34     * which generates the p and g values from the given parameters,
35     * returning the DHParameters object.
36     * <p>
37     * Note: can take a while...
38     */
39    public DHParameters generateParameters()
40    {
41        //
42        // find a safe prime p where p = 2*q + 1, where p and q are prime.
43        //
44        BigInteger[] safePrimes = DHParametersHelper.generateSafePrimes(size, certainty, random);
45
46        BigInteger p = safePrimes[0];
47        BigInteger q = safePrimes[1];
48        BigInteger g = DHParametersHelper.selectGenerator(p, q, random);
49
50        return new DHParameters(p, g, q, TWO, null);
51    }
52}
53