01: package org.bouncycastle.crypto.generators;
02:
03: import java.math.BigInteger;
04: import java.security.SecureRandom;
05:
06: class DHKeyGeneratorHelper {
07: private static final int MAX_ITERATIONS = 1000;
08:
09: static final DHKeyGeneratorHelper INSTANCE = new DHKeyGeneratorHelper();
10:
11: private static final BigInteger ZERO = BigInteger.valueOf(0);
12: private static final BigInteger TWO = BigInteger.valueOf(2);
13:
14: private DHKeyGeneratorHelper() {
15: }
16:
17: BigInteger calculatePrivate(BigInteger p, SecureRandom random,
18: int limit) {
19: //
20: // calculate the private key
21: //
22: BigInteger pSub2 = p.subtract(TWO);
23: BigInteger x;
24:
25: if (limit == 0) {
26: x = createInRange(pSub2, random);
27: } else {
28: do {
29: x = new BigInteger(limit, 0, random);
30: } while (x.equals(ZERO));
31: }
32:
33: return x;
34: }
35:
36: private BigInteger createInRange(BigInteger max, SecureRandom random) {
37: BigInteger x;
38: int maxLength = max.bitLength();
39: int count = 0;
40:
41: do {
42: x = new BigInteger(maxLength, random);
43: count++;
44: } while ((x.equals(ZERO) || x.compareTo(max) > 0)
45: && count != MAX_ITERATIONS);
46:
47: if (count == MAX_ITERATIONS) // fall back to a faster (restricted) method
48: {
49: return new BigInteger(maxLength - 1, random).setBit(0);
50: }
51:
52: return x;
53: }
54:
55: BigInteger calculatePublic(BigInteger p, BigInteger g, BigInteger x) {
56: return g.modPow(x, p);
57: }
58: }
|