Skip to content

Commit bfceee5

Browse files
authored
Remove extra \0 byte if present (#478)
1 parent aef1302 commit bfceee5

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\TestCase;
1112

@@ -136,4 +137,28 @@ public function iCanConvertAPrivateKeyIntoPublicKey(): void
136137
'kid' => '9876543210',
137138
]), json_encode($public, JSON_THROW_ON_ERROR));
138139
}
140+
141+
/**
142+
* @test
143+
* @see https://github.com/web-token/jwt-framework/issues/475
144+
*/
145+
public static function convertToPEM(): void
146+
{
147+
// Given
148+
$key = '{"kty":"EC","crv":"P-256","x":"GDDdmNtwNvlXN04SEUp20BZJ9im6SQqkP8u4d8G6RAk","y":"AIAxkBwTTqbCcNbqbpk8l_Eh-4KtpgyyHkNJ6K4jnvOv","use":"sig","alg":"ES256","kid":"ayRrlw","key_ops":["verify"]}';
149+
$jwk = JWK::createFromJson($key);
150+
$expectedPEM = <<<'PEM'
151+
-----BEGIN PUBLIC KEY-----
152+
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGDDdmNtwNvlXN04SEUp20BZJ9im6
153+
SQqkP8u4d8G6RAmAMZAcE06mwnDW6m6ZPJfxIfuCraYMsh5DSeiuI57zrw==
154+
-----END PUBLIC KEY-----
155+
156+
PEM;
157+
158+
//When
159+
$pem = ECKey::convertToPEM($jwk);
160+
161+
//Then
162+
static::assertSame($expectedPEM, $pem);
163+
}
139164
}

0 commit comments

Comments
 (0)