Skip to content

Commit

Permalink
Parse octet typed JWK
Browse files Browse the repository at this point in the history
Resolves firebase#555
  • Loading branch information
apiwat-chantawibul committed Dec 8, 2024
1 parent 29fa2ce commit 4c79857
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/JWK.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,12 @@ public static function parseKey(array $jwk, ?string $defaultAlg = null): ?Key
// This library works internally with EdDSA keys (Ed25519) encoded in standard base64.
$publicKey = JWT::convertBase64urlToBase64($jwk['x']);
return new Key($publicKey, $jwk['alg']);
case 'oct':
if (!isset($jwk['k'])) {
throw new UnexpectedValueException('k not set');
}

return new Key(JWT::urlsafeB64Decode($jwk['k']), $jwk['alg']);
default:
break;
}
Expand Down
24 changes: 24 additions & 0 deletions tests/JWKTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,30 @@ public function testDecodeByMultiJwkKeySet()
$this->assertSame('bar', $result->sub);
}

public function testDecodeByOctetJwkKeySet()
{
$jwkSet = json_decode(
file_get_contents(__DIR__ . '/data/octet-jwkset.json'),
true
);
$keys = JWK::parseKeySet($jwkSet);
$payload = ['sub' => 'foo', 'exp' => strtotime('+10 seconds')];
foreach ($keys as $keyId => $key) {
$msg = JWT::encode($payload, $key->getKeyMaterial(), $key->getAlgorithm(), $keyId);
$result = JWT::decode($msg, $keys);

$this->assertSame('foo', $result->sub);
}
}

public function testOctetJwkMissingK() {
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('k not set');

$badJwk = ['kty' => 'oct', 'alg' => 'HS256'];
$keys = JWK::parseKeySet(['keys' => [$badJwk]]);
}

public function testParseKey()
{
// Use a known module and exponent, and ensure it parses as expected
Expand Down
22 changes: 22 additions & 0 deletions tests/data/octet-jwkset.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"keys": [
{
"kty": "oct",
"alg": "HS256",
"kid": "jwk1",
"k": "xUNfVvQ-WdmXB9qp6qK0SrG-yKW4AJqmcSP66Gm2TrE"
},
{
"kty": "oct",
"alg": "HS384",
"kid": "jwk2",
"k": "z7990HoD72QDX9JKqeQc3l7EtXutco72j2YulZMjeakFVDbFGXGDFG4awOF7eu9l"
},
{
"kty": "oct",
"alg": "HS512",
"kid": "jwk3",
"k": "EmYGSDG5W1UjkPIL7LelG-QMVtsXn7bz5lUxBrkqq3kdFEzkLWVGrXKpZxRe7YcApCe0d4s9lXRQtn5Nzaf49w"
}
]
}

0 comments on commit 4c79857

Please sign in to comment.