Skip to content

Comments

fix(jsbn2): reject non-positive values in primality checks#651

Merged
kjur merged 1 commit intokjur:masterfrom
Kr0emer:fix/bug-007-isprobableprime-negative
Feb 20, 2026
Merged

fix(jsbn2): reject non-positive values in primality checks#651
kjur merged 1 commit intokjur:masterfrom
Kr0emer:fix/bug-007-isprobableprime-negative

Conversation

@Kr0emer
Copy link
Contributor

@Kr0emer Kr0emer commented Feb 20, 2026

Summary

This PR fixes BigInteger primality checks for non-positive inputs.

isProbablePrime previously operated on abs(this) and could return true
for negative values (e.g. -7, -97). Since primes are defined only for
positive integers greater than 1, this is incorrect behavior.

Changes

  • ext/jsbn2.js
    • bnIsProbablePrime(t): now returns false when this.signum() <= 0
    • bnpMillerRabin(t): adds the same defensive guard for non-positive input
  • test/qunit-do-crypto.html
    • Added regression test: negative values must return false
    • Added control test: positive prime/composite behavior remains unchanged

Why

This ensures primality checks are mathematically correct and avoids accepting
invalid negative parameters in callers that rely on isProbablePrime.

Validation

  • Manual check after patch:
    • -2, -7, -13, -97 -> false
    • 7 -> true, 4 -> false
  • Ran test suite:
    • npm test passes

@kjur kjur merged commit 77f1776 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