verifyGenerator function

void verifyGenerator(
  1. BigInt generator,
  2. BigInt safePrime
)

Verifies that a generator is valid for the given safe prime.

For a safe prime N = 2q + 1, a generator g must satisfy: g^q mod N ≠ 1

This ensures g generates the large order-q subgroup, which is required for SRP security.

Note: This uses a probabilistic primality test (Miller-Rabin) which is computationally efficient but has a very small chance of false positives. For cryptographic applications, this is generally acceptable.

Parameters:

  • generator: The generator value to verify (typically 2 or 5).
  • safePrime: The safe prime N that the generator should work with.

Throws:

Implementation

void verifyGenerator(BigInt generator, BigInt safePrime) {
  if (generator < BigInt.two || generator >= safePrime) {
    throw InvalidParameterException('Generator $generator is out of range 2 <= generator <= safe prime.');
  }

  if (!isProbablyPrime(generator)) {
    throw InvalidParameterException('Generator $generator is unlikely to be prime.');
  }

  // q = (N - 1) / 2
  final q = (safePrime - BigInt.one) ~/ BigInt.two;

  // Check g^2 mod N ≠ 1
  if (generator.modPow(BigInt.from(2), safePrime) == BigInt.one) {
    throw InvalidParameterException('Generator $generator only generates the trivial subgroup of the safe prime.');
  }
  // Check g^q mod N ≠ 1
  if (generator.modPow(q, safePrime) == BigInt.one) {
    throw InvalidParameterException('Generator $generator does not generate the full subgroup of the safe prime.');
  }
}