Skip to content

BigInteger modPow() returns incorrect result for negative base #2086

@nanasess

Description

@nanasess

Bug Report

Summary

The BigInteger::modPow() method returns incorrect results when the base is negative. This affects BCMath and Default engines.

Expected Behavior

For (-9)^1024 mod 123, the result should be 42 (same as PHP's standard bcpowmod() function).

Actual Behavior

The BigInteger::modPow() method returns 16 instead of the expected 42.

Test Case

A test case has been added in tests/Unit/Math/BigInteger/TestCase.php:

public function testModPowNegativeBase(): void
{
    $a = $this->getInstance('-9');
    $b = $this->getInstance('1024');
    $c = $this->getInstance('123');
    $d = $a->modPow($b, $c);

    $this->assertSame('42', (string) $d);
}

Verification with PHP Standard Functions

PHP's bcpowmod() function correctly returns 42:

php -r 'echo bcpowmod("-9", "1024", "123") . "\n";'
// Output: 42

Test Results

The test fails for BCMath and Default engines:

Mathematical Context

Since 1024 is an even number, (-9)^1024 should equal 9^1024, which modulo 123 equals 42.

Environment

  • PHP 8.4.7
  • phpseclib version: master branch
  • Affected engines: BCMath, Default (PHP64)
  • Working engines: None tested (GMP extension not available in test environment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions