1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
From: terrafrost <terrafrost@gmail.com>
Date: Sat, 24 Feb 2024 13:41:06 -0600
Subject: BigInteger: optimize getLength()
Origin: backport, https://github.com/phpseclib/phpseclib/commit/a922309855328273b818bbff049e9f422b0678ed
---
phpseclib/Math/BigInteger/Engines/Engine.php | 2 +-
phpseclib/Math/BigInteger/Engines/PHP.php | 13 +++++++++++++
tests/Unit/File/ASN1Test.php | 5 ++---
3 files changed, 16 insertions(+), 4 deletions(-)
diff --git a/phpseclib/Math/BigInteger/Engines/Engine.php b/phpseclib/Math/BigInteger/Engines/Engine.php
index 3a735e7..4c2c298 100644
--- a/phpseclib/Math/BigInteger/Engines/Engine.php
+++ b/phpseclib/Math/BigInteger/Engines/Engine.php
@@ -619,7 +619,7 @@ abstract class Engine implements \JsonSerializable
*/
public function getLengthInBytes()
{
- return strlen($this->toBytes());
+ return (int) ceil($this->getLength() / 8);
}
/**
diff --git a/phpseclib/Math/BigInteger/Engines/PHP.php b/phpseclib/Math/BigInteger/Engines/PHP.php
index ab9bdc9..37bc168 100644
--- a/phpseclib/Math/BigInteger/Engines/PHP.php
+++ b/phpseclib/Math/BigInteger/Engines/PHP.php
@@ -1326,4 +1326,17 @@ abstract class PHP extends Engine
return array_reverse($vals);
}
+
+ /**
+ * Return the size of a BigInteger in bits
+ *
+ * @return int
+ */
+ public function getLength()
+ {
+ $max = count($this->value) - 1;
+ return $max != -1 ?
+ $max * static::BASE + intval(ceil(log($this->value[$max] + 1, 2))) :
+ 0;
+ }
}
diff --git a/tests/Unit/File/ASN1Test.php b/tests/Unit/File/ASN1Test.php
index b39ce46..0dd40ed 100644
--- a/tests/Unit/File/ASN1Test.php
+++ b/tests/Unit/File/ASN1Test.php
@@ -455,9 +455,8 @@ class ASN1Test extends PhpseclibTestCase
{
$cert = file_get_contents(dirname(__FILE__) . '/ASN1/mal-cert-02.der');
- $asn1 = new ASN1();
- $decoded = $asn1->decodeBER($cert);
- $this->assertFalse($decoded[0]);
+ $decoded = ASN1::decodeBER($cert);
+ $this->assertNull($decoded);
//$x509 = new X509();
//$x509->loadX509($cert);
|