Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove extra \0 byte if present #478

Merged
merged 1 commit into from
Aug 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/Component/Core/Util/ECKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
;
}
}
25 changes: 25 additions & 0 deletions tests/Component/Core/JWKTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
}
}
Loading