1package org.bouncycastle.crypto.generators;
2
3import java.math.BigInteger;
4import java.security.SecureRandom;
5
6import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
7import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
8import org.bouncycastle.crypto.KeyGenerationParameters;
9import org.bouncycastle.crypto.params.ECDomainParameters;
10import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
11import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
12import org.bouncycastle.crypto.params.ECPublicKeyParameters;
13import org.bouncycastle.math.ec.ECConstants;
14import org.bouncycastle.math.ec.ECPoint;
15
16public class ECKeyPairGenerator
17    implements AsymmetricCipherKeyPairGenerator, ECConstants
18{
19    ECDomainParameters  params;
20    SecureRandom        random;
21
22    public void init(
23        KeyGenerationParameters param)
24    {
25        ECKeyGenerationParameters  ecP = (ECKeyGenerationParameters)param;
26
27        this.random = ecP.getRandom();
28        this.params = ecP.getDomainParameters();
29
30        if (this.random == null)
31        {
32            this.random = new SecureRandom();
33        }
34    }
35
36    /**
37     * Given the domain parameters this routine generates an EC key
38     * pair in accordance with X9.62 section 5.2.1 pages 26, 27.
39     */
40    public AsymmetricCipherKeyPair generateKeyPair()
41    {
42        BigInteger n = params.getN();
43        int        nBitLength = n.bitLength();
44        BigInteger d;
45
46        do
47        {
48            d = new BigInteger(nBitLength, random);
49        }
50        while (d.equals(ZERO)  || (d.compareTo(n) >= 0));
51
52        ECPoint Q = params.getG().multiply(d);
53
54        return new AsymmetricCipherKeyPair(
55            new ECPublicKeyParameters(Q, params),
56            new ECPrivateKeyParameters(d, params));
57    }
58}
59