package org.bouncycastle.crypto.generators;

import java.math.BigInteger;
import java.security.SecureRandom;

import org.bouncycastle.crypto.params.DHParameters;
import org.bouncycastle.util.BigIntegers;

class DHKeyGeneratorHelper
{
    static final DHKeyGeneratorHelper INSTANCE = new DHKeyGeneratorHelper();

    private static final BigInteger ONE = BigInteger.valueOf(1);
    private static final BigInteger TWO = BigInteger.valueOf(2);

    private DHKeyGeneratorHelper()
    {
    }

    BigInteger calculatePrivate(DHParameters dhParams, SecureRandom random)
    {
        BigInteger p = dhParams.getP();
        int limit = dhParams.getL();

        if (limit != 0)
        {
            return new BigInteger(limit, random).setBit(limit - 1);
        }

        BigInteger min = TWO;
        int m = dhParams.getM();
        if (m != 0)
        {
            min = ONE.shiftLeft(m - 1);
        }

        BigInteger max = p.subtract(TWO);
        BigInteger q = dhParams.getQ();
        if (q != null)
        {
            max = q.subtract(TWO);
        }

        return BigIntegers.createRandomInRange(min, max, random);
    }

    BigInteger calculatePublic(DHParameters dhParams, BigInteger x)
    {
        return dhParams.getG().modPow(x, dhParams.getP());
    }
}

@@ -570,48 +570,8 @@
   %7B%0A
-        BigInteger p = dhParams.getP();%0A
     
@@ -865,50 +865,8 @@
  %7D%0A%0A
-        BigInteger max = p.subtract(TWO);%0A
     
@@ -915,17 +915,17 @@
   if (q 
-!
+=
 = null)%0A
@@ -946,16 +946,66 @@
         
+q = dhParams.getP();%0A        %7D%0A        BigInteger 
 max = q.
@@ -1018,26 +1018,16 @@
 ct(TWO);
-%0A        %7D
 %0A%0A      

Avoid redundant subtraction