OpenNHP/opennhp · error

invalid r value

Error message

invalid r value

What it means

Raised in the SM2/ECDSA-style Sign routine: after picking random nonce k and computing r = (k*G).x mod N, the result was zero. This is a vanishingly rare algebraic edge case (probability ~1/N); the signature would be invalid, so signing aborts. The input at fault is the freshly generated random k, not the caller's message or key.

Solutions

  1. Retry the Sign operation with a new random nonce — a different k will virtually never reproduce a zero r
  2. Treat repeated occurrences as a sign of a broken RNG and investigate the entropy source
Defensive patterns

Strategy: retry

When it happens

Trigger: Thrown at endpoints/kgc/user/user.go:196 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of OpenNHP/opennhp@6e04ca5ff0 (2026-09-07). Data as JSON: /api/errors/1f7c7ffa66944473. Report an issue: GitHub.

Appendix: source

Thrown at endpoints/kgc/user/user.go:196

// 4. Computes s = k⁻¹·(e + r·dA) mod N
// where e is the message hash, dA is the private key, and N is the curve order.
func (u *UserImpl) Sign(prkBase64 string, message string) (r, s *big.Int, err error) {
	u.h.Write([]byte(message))
	msgHash := u.h.Sum(nil)
	u.h.Reset()

	k, err := kgc.GenerateRandomNumber(u.Params().N)
	if err != nil {
		return nil, nil, err
	}

	// k*G
	kGx, _ := u.Curve.ScalarBaseMult(k.Bytes())

	// r = kGx mod N
	r = new(big.Int).Mod(kGx, u.Params().N)
	if r.Sign() == 0 {
		return nil, nil, fmt.Errorf("invalid r value")
	}

	// k⁻¹
	kInv := new(big.Int).ModInverse(k, u.Params().N)

	prk, err := base64.StdEncoding.DecodeString(prkBase64)
	if err != nil {
		return nil, nil, err
	}

	// s = k⁻¹·(e + r·dA) mod n
	rda := new(big.Int).Mul(r, new(big.Int).SetBytes(prk))
	ePlusRda := new(big.Int).Add(rda, new(big.Int).SetBytes(msgHash))
	s = new(big.Int).Mod(new(big.Int).Mul(ePlusRda, kInv), u.Params().N)

	if s.Sign() == 0 {
		return nil, nil, fmt.Errorf("invalid s value")
	}

View on GitHub (pinned to 6e04ca5ff0)