Skip to content

Comments

fix(jsbn2): handle negative exponents in BigInteger.modPow#650

Merged
kjur merged 2 commits intokjur:masterfrom
Kr0emer:fix/bug-006-modpow-negative-exponent
Feb 20, 2026
Merged

fix(jsbn2): handle negative exponents in BigInteger.modPow#650
kjur merged 2 commits intokjur:masterfrom
Kr0emer:fix/bug-006-modpow-negative-exponent

Conversation

@Kr0emer
Copy link
Contributor

@Kr0emer Kr0emer commented Feb 20, 2026

Summary

This PR fixes BigInteger.modPow() for negative exponents in jsbn2.

Previously, negative exponents were processed through two's-complement bit scanning, which produced silent incorrect results (e.g. a.modPow(-1, m) often returned 1).

Root Cause

bnModPow used e.bitLength() and exponent bit scanning without checking exponent sign, so negative values were interpreted as invalid positive bit patterns.

Fix

In ext/jsbn2.js, bnModPow(e, m) now handles negative exponents explicitly:

  • if e < 0, compute:
    • this.modInverse(m).modPow(e.negate(), m)

This preserves existing behavior for non-negative exponents and returns mathematically correct values for negative exponents.

Tests

Added regression tests in test/qunit-do-crypto.html:

  • BigInteger.modPow with exponent -1
  • BigInteger.modPow with exponent -k

Both compare against the mathematically correct construction using modInverse.

Verification

  • Reproduced original issue before patch: multiple negative-exponent cases mismatched expected values.
  • After patch: all tested cases matched expected results.
  • Ran npm test in npm/: all tests passed.

@kjur kjur merged commit 5ea1c32 into kjur:master Feb 20, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants