Skip to content

Commit 4ab8741

Browse files
authored
Remove extra \0 byte if present (#476)
1 parent 227990b commit 4ab8741

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/Component/Core/Util/ECKey.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -317,9 +317,12 @@ private static function getKey(JWK $jwk): string
317317
if (! is_string($y)) {
318318
throw new InvalidArgumentException('Unable to get the public key');
319319
}
320+
$binX = ltrim(Base64UrlSafe::decode($x), "\0");
321+
$binY = ltrim(Base64UrlSafe::decode($y), "\0");
320322

321323
return "\04"
322-
. str_pad(Base64UrlSafe::decode($x), $length, "\0", STR_PAD_LEFT)
323-
. str_pad(Base64UrlSafe::decode($y), $length, "\0", STR_PAD_LEFT);
324+
. str_pad($binX, $length, "\0", STR_PAD_LEFT)
325+
. str_pad($binY, $length, "\0", STR_PAD_LEFT)
326+
;
324327
}
325328
}

tests/Component/Core/JWKTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use InvalidArgumentException;
88
use Jose\Component\Core\JWK;
9+
use Jose\Component\Core\Util\ECKey;
910
use const JSON_THROW_ON_ERROR;
1011
use PHPUnit\Framework\Attributes\Test;
1112
use PHPUnit\Framework\TestCase;
@@ -127,4 +128,28 @@ public function iCanConvertAPrivateKeyIntoPublicKey(): void
127128
'kid' => '9876543210',
128129
]), json_encode($public, JSON_THROW_ON_ERROR));
129130
}
131+
132+
/**
133+
* @test
134+
* @see https://github.com/web-token/jwt-framework/issues/475
135+
*/
136+
public static function convertToPEM(): void
137+
{
138+
// Given
139+
$key = '{"kty":"EC","crv":"P-256","x":"GDDdmNtwNvlXN04SEUp20BZJ9im6SQqkP8u4d8G6RAk","y":"AIAxkBwTTqbCcNbqbpk8l_Eh-4KtpgyyHkNJ6K4jnvOv","use":"sig","alg":"ES256","kid":"ayRrlw","key_ops":["verify"]}';
140+
$jwk = JWK::createFromJson($key);
141+
$expectedPEM = <<<'PEM'
142+
-----BEGIN PUBLIC KEY-----
143+
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGDDdmNtwNvlXN04SEUp20BZJ9im6
144+
SQqkP8u4d8G6RAmAMZAcE06mwnDW6m6ZPJfxIfuCraYMsh5DSeiuI57zrw==
145+
-----END PUBLIC KEY-----
146+
147+
PEM;
148+
149+
//When
150+
$pem = ECKey::convertToPEM($jwk);
151+
152+
//Then
153+
static::assertSame($expectedPEM, $pem);
154+
}
130155
}

0 commit comments

Comments
 (0)