1
0
mirror of https://github.com/danog/phpseclib.git synced 2024-11-26 20:35:21 +01:00

fix bug with toBytes() with fixed precision negative numbers

This commit is contained in:
terrafrost 2019-09-15 17:19:35 -05:00
parent 27555c3a47
commit 11fea7d004
2 changed files with 26 additions and 1 deletions

View File

@ -556,7 +556,7 @@ class Math_BigInteger
$bytes = chr(0);
}
if (ord($bytes[0]) & 0x80) {
if ($this->precision <= 0 && (ord($bytes[0]) & 0x80)) {
$bytes = chr(0) . $bytes;
}
@ -724,6 +724,7 @@ class Math_BigInteger
}
$temp = $this->copy();
$temp->bitmask = false;
$temp->is_negative = false;
$divisor = new Math_BigInteger();
@ -3615,7 +3616,14 @@ class Math_BigInteger
switch (MATH_BIGINTEGER_MODE) {
case MATH_BIGINTEGER_MODE_GMP:
if ($this->bitmask !== false) {
$flip = gmp_cmp($result->value, gmp_init(0)) < 0;
if ($flip) {
$result->value = gmp_neg($result->value);
}
$result->value = gmp_and($result->value, $result->bitmask->value);
if ($flip) {
$result->value = gmp_neg($result->value);
}
}
return $result;

View File

@ -434,4 +434,21 @@ abstract class Unit_Math_BigInteger_TestCase extends PhpseclibTestCase
$temp = $this->getInstance('-0');
$this->assertSame($temp->toString(), '0');
}
public function testNegativePrecision()
{
$vals = [
'-9223372036854775808', // eg. 8000 0000 0000 0000
'-1'
];
foreach ($vals as $val) {
$x = $this->getInstance($val);
$x->setPrecision(64); // ie. 8 bytes
$this->assertSame($val, "$x");
$r = $x->toBytes(true);
$this->assertSame(8, strlen($r));
$x2 = $this->getInstance($r, -256);
$this->assertSame(0, $x->compare($x2));
}
}
}