01: package org.bouncycastle.crypto.generators;
02:
03: import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
04: import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
05: import org.bouncycastle.crypto.KeyGenerationParameters;
06: import org.bouncycastle.crypto.params.DSAKeyGenerationParameters;
07: import org.bouncycastle.crypto.params.DSAParameters;
08: import org.bouncycastle.crypto.params.DSAPrivateKeyParameters;
09: import org.bouncycastle.crypto.params.DSAPublicKeyParameters;
10:
11: import java.math.BigInteger;
12: import java.security.SecureRandom;
13:
14: /**
15: * a DSA key pair generator.
16: *
17: * This generates DSA keys in line with the method described
18: * in FIPS 186-2.
19: */
20: public class DSAKeyPairGenerator implements
21: AsymmetricCipherKeyPairGenerator {
22: private static final BigInteger ZERO = BigInteger.valueOf(0);
23:
24: private DSAKeyGenerationParameters param;
25:
26: public void init(KeyGenerationParameters param) {
27: this .param = (DSAKeyGenerationParameters) param;
28: }
29:
30: public AsymmetricCipherKeyPair generateKeyPair() {
31: BigInteger p, q, g, x, y;
32: DSAParameters dsaParams = param.getParameters();
33: SecureRandom random = param.getRandom();
34:
35: q = dsaParams.getQ();
36: p = dsaParams.getP();
37: g = dsaParams.getG();
38:
39: do {
40: x = new BigInteger(160, random);
41: } while (x.equals(ZERO) || x.compareTo(q) >= 0);
42:
43: //
44: // calculate the public key.
45: //
46: y = g.modPow(x, p);
47:
48: return new AsymmetricCipherKeyPair(new DSAPublicKeyParameters(
49: y, dsaParams),
50: new DSAPrivateKeyParameters(x, dsaParams));
51: }
52: }
|