fix(jsbn2): handle negative exponents in BigInteger.modPow#650
Merged
kjur merged 2 commits intokjur:masterfrom Feb 20, 2026
Merged
fix(jsbn2): handle negative exponents in BigInteger.modPow#650kjur merged 2 commits intokjur:masterfrom
kjur merged 2 commits intokjur:masterfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes
BigInteger.modPow()for negative exponents injsbn2.Previously, negative exponents were processed through two's-complement bit scanning, which produced silent incorrect results (e.g.
a.modPow(-1, m)often returned1).Root Cause
bnModPowusede.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: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.modPowwith exponent-1BigInteger.modPowwith exponent-kBoth compare against the mathematically correct construction using
modInverse.Verification
npm testinnpm/: all tests passed.