generateProbablePrime function

BigInt generateProbablePrime(
  1. int bitLength,
  2. int certainty,
  3. SecureRandom rnd
)

Implementation

BigInt generateProbablePrime(int bitLength, int certainty, SecureRandom rnd) {
  if (bitLength < 2) {
    return BigInt.one;
  }

  var candidate = rnd.nextBigInteger(bitLength);

  // force MSB set
  if (!_testBit(candidate, bitLength - 1)) {
    candidate |= BigInt.one << (bitLength - 1);
  }

  // force odd
  if (candidate.isEven) {
    candidate += BigInt.one;
  }

  while (!_isProbablePrime(candidate, certainty)) {
    candidate += _bigTwo;
    if (candidate.bitLength > bitLength) {
      candidate -= BigInt.one << (bitLength - 1);
    }
  }

  return candidate;
}