golang/go · error

crypto/rsa: prime factor is nil

Error message

crypto/rsa: prime factor is nil

What it means

Thrown in the legacy precompute path (after the FIPS key is built) when iterating priv.Primes and finding any nil element. This loop runs for keys with >=2 primes to compute Dp/Dq/Qinv and additional CRT values, guarding the Mod and ModInverse calls from a nil receiver.

Source

Thrown at src/crypto/rsa/rsa.go:645

}

func (priv *PrivateKey) precomputeLegacy() (PrecomputedValues, error) {
	var precomputed PrecomputedValues

	k, err := rsa.NewPrivateKeyWithoutCRT(priv.N.Bytes(), priv.E, priv.D.Bytes())
	if err != nil {
		return precomputed, err
	}
	precomputed.fips = k

	if len(priv.Primes) < 2 {
		return precomputed, nil
	}

	// Ensure the Mod and ModInverse calls below don't panic.
	for _, prime := range priv.Primes {
		if prime == nil {
			return precomputed, errors.New("crypto/rsa: prime factor is nil")
		}
		if prime.Cmp(bigOne) <= 0 {
			return precomputed, errors.New("crypto/rsa: prime factor is <= 1")
		}
	}

	precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne)
	precomputed.Dp.Mod(priv.D, precomputed.Dp)

	precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne)
	precomputed.Dq.Mod(priv.D, precomputed.Dq)

	precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0])
	if precomputed.Qinv == nil {
		return precomputed, errors.New("crypto/rsa: prime factors are not relatively prime")
	}

	r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1])

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Regenerate the key with rsa.GenerateKey or rsa.GenerateMultiPrimeKey.
  2. After load, call priv.Validate() to surface nil primes before use.
  3. Inspect priv.Primes for nil entries if you must construct manually: every element must be non-nil.
  4. Re-parse from an authoritative PKCS#1 encoding.

Example fix

// before
priv.Primes = []*big.Int{p, q, nil, r} // index 2 nil
err := priv.Validate()

// after
priv.Primes = []*big.Int{p, q, r} // all non-nil
err := priv.Validate()
Defensive patterns

Strategy: validation

Validate before calling

func checkAllPrimesNonNil(priv *rsa.PrivateKey) error {
    for i, p := range priv.Primes {
        if p == nil {
            return fmt.Errorf("rsa: prime[%d] is nil", i)
        }
    }
    return priv.Validate()
}

Prevention

When it happens

Trigger: Sign/Decrypt/Validate on a multi-prime or 2-prime key where any entry of priv.Primes is nil. Distinct from errors 521/522 because it covers primes beyond index 1 as well (multi-prime RSA).

Common situations: rsa.GenerateMultiPrimeKey result with a corrupted Primes slice; deserialized key where some prime entries failed to decode; test code that built a >2-prime key but left a middle entry nil.

Related errors


AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12). Data as JSON: /api/errors/93f59897c73779bc. Report an issue: GitHub.