Skip to content

Commit bd629a4

Browse files
committed
gmp encoding fix
1 parent e166cb7 commit bd629a4

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

src/PublicKey.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,9 @@ public function compress(): self
9393
throw new PublicKeyException('Public key is already compressed.');
9494
}
9595

96-
$wasOdd = \gmp_cmp(
97-
\gmp_mod($this->y, \gmp_init(2)),
98-
\gmp_init(0)
96+
$wasOdd = gmp_cmp(
97+
gmp_mod($this->y, gmp_init(2)),
98+
gmp_init(0)
9999
) !== 0;
100100

101101
return new static($this->x, null, $wasOdd);
@@ -154,7 +154,7 @@ static public function parse(string $data): self
154154
throw new PublicKeyException('Invalid compressed public key prefix.');
155155
}
156156

157-
$x = \gmp_init(bin2hex(substr($data, 1, 32)), 16);
157+
$x = Utils::binToGmp(substr($data, 1, 32));
158158
$y = null;
159159
} elseif ($length == static::LENGTH_UNCOMPRESSED) {
160160
$prefix = substr($data, 0, 1);
@@ -163,8 +163,8 @@ static public function parse(string $data): self
163163
throw new PublicKeyException('Invalid uncompressed public key prefix.');
164164
}
165165

166-
$x = \gmp_init(bin2hex(substr($data, 1, 32)), 16);
167-
$y = \gmp_init(bin2hex(substr($data, 33, 32)), 16);
166+
$x = Utils::binToGmp(substr($data, 1, 32));
167+
$y = Utils::binToGmp(substr($data, 33, 32));
168168
} else {
169169
throw new PublicKeyException('Invalid public key size.');
170170
}
@@ -177,14 +177,14 @@ static public function parse(string $data): self
177177
*/
178178
public function serialize(): string
179179
{
180-
$x = hex2bin(\gmp_strval($this->x, 16));
180+
$x = Utils::gmpToBin($this->x);
181181

182182
if ($this->isCompressed()) {
183183
$prefix = $this->wasOdd ? static::PREFIX_COMPRESSED_ODD : static::PREFIX_COMPRESSED_EVEN;
184184
$y = '';
185185
} else {
186186
$prefix = static::PREFIX_UNCOMPRESSED;
187-
$y = hex2bin(\gmp_strval($this->y, 16));
187+
$y = Utils::gmpToBin($this->y);
188188
}
189189

190190
return $prefix . $x . $y;

src/Utils.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,26 @@ static public function hexToHash(string $hex): string
9292
{
9393
return strrev(hex2bin($hex));
9494
}
95+
96+
/**
97+
* @param \GMP $gmp
98+
* @return string
99+
*/
100+
static public function gmpToBin(\GMP $gmp): string
101+
{
102+
$hex = gmp_strval($gmp, 16);
103+
if (strlen($hex) % 2 != 0) {
104+
$hex = '0' . $hex;
105+
}
106+
return hex2bin($hex);
107+
}
108+
109+
/**
110+
* @param string $data
111+
* @return \GMP
112+
*/
113+
static public function binToGmp(string $data): \GMP
114+
{
115+
return gmp_init(bin2hex($data), 16);
116+
}
95117
}

0 commit comments

Comments
 (0)