diff --git a/src/Component/Core/Util/ECKey.php b/src/Component/Core/Util/ECKey.php index 31a0bb748..9b83d1dd4 100644 --- a/src/Component/Core/Util/ECKey.php +++ b/src/Component/Core/Util/ECKey.php @@ -317,9 +317,12 @@ private static function getKey(JWK $jwk): string if (! is_string($y)) { throw new InvalidArgumentException('Unable to get the public key'); } + $binX = ltrim(Base64UrlSafe::decode($x), "\0"); + $binY = ltrim(Base64UrlSafe::decode($y), "\0"); return "\04" - . str_pad(Base64UrlSafe::decode($x), $length, "\0", STR_PAD_LEFT) - . str_pad(Base64UrlSafe::decode($y), $length, "\0", STR_PAD_LEFT); + . str_pad($binX, $length, "\0", STR_PAD_LEFT) + . str_pad($binY, $length, "\0", STR_PAD_LEFT) + ; } } diff --git a/tests/Component/Core/JWKTest.php b/tests/Component/Core/JWKTest.php index 34147d874..1dfe701ee 100644 --- a/tests/Component/Core/JWKTest.php +++ b/tests/Component/Core/JWKTest.php @@ -6,6 +6,7 @@ use InvalidArgumentException; use Jose\Component\Core\JWK; +use Jose\Component\Core\Util\ECKey; use const JSON_THROW_ON_ERROR; use PHPUnit\Framework\TestCase; @@ -136,4 +137,28 @@ public function iCanConvertAPrivateKeyIntoPublicKey(): void 'kid' => '9876543210', ]), json_encode($public, JSON_THROW_ON_ERROR)); } + + /** + * @test + * @see https://github.com/web-token/jwt-framework/issues/475 + */ + public static function convertToPEM(): void + { + // Given + $key = '{"kty":"EC","crv":"P-256","x":"GDDdmNtwNvlXN04SEUp20BZJ9im6SQqkP8u4d8G6RAk","y":"AIAxkBwTTqbCcNbqbpk8l_Eh-4KtpgyyHkNJ6K4jnvOv","use":"sig","alg":"ES256","kid":"ayRrlw","key_ops":["verify"]}'; + $jwk = JWK::createFromJson($key); + $expectedPEM = <<<'PEM' +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEGDDdmNtwNvlXN04SEUp20BZJ9im6 +SQqkP8u4d8G6RAmAMZAcE06mwnDW6m6ZPJfxIfuCraYMsh5DSeiuI57zrw== +-----END PUBLIC KEY----- + +PEM; + + //When + $pem = ECKey::convertToPEM($jwk); + + //Then + static::assertSame($expectedPEM, $pem); + } }