1 package org.bouncycastle.crypto.generators; 2 3 import java.math.BigInteger; 4 import java.security.SecureRandom; 5 6 import org.bouncycastle.crypto.params.DHParameters; 7 import org.bouncycastle.util.BigIntegers; 8 9 class DHKeyGeneratorHelper 10 { 11 static final DHKeyGeneratorHelper INSTANCE = new DHKeyGeneratorHelper(); 12 13 private static final BigInteger ONE = BigInteger.valueOf(1); 14 private static final BigInteger TWO = BigInteger.valueOf(2); 15 16 private DHKeyGeneratorHelper() 17 { 18 } 19 20 BigInteger calculatePrivate(DHParameters dhParams, SecureRandom random) 21 { 22 BigInteger p = dhParams.getP(); 23 int limit = dhParams.getL(); 24 25 if (limit != 0) 26 { 27 return new BigInteger(limit, random).setBit(limit - 1); 28 } 29 30 BigInteger min = TWO; 31 int m = dhParams.getM(); 32 if (m != 0) 33 { 34 min = ONE.shiftLeft(m - 1); 35 } 36 37 BigInteger max = p.subtract(TWO); 38 BigInteger q = dhParams.getQ(); 39 if (q != null) 40 { 41 max = q.subtract(TWO); 42 } 43 44 return BigIntegers.createRandomInRange(min, max, random); 45 } 46 47 BigInteger calculatePublic(DHParameters dhParams, BigInteger x) 48 { 49 return dhParams.getG().modPow(x, dhParams.getP()); 50 } 51 } 52