Skip to content

Commit 70265d8

Browse files
committed
Add utility class to create JWKs JSON from public key.
1 parent d2b5ec9 commit 70265d8

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

src/Utils/Jwks.php

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
3+
namespace Pdsinterop\Solid\Auth\Utils;
4+
5+
use JsonSerializable;
6+
use Lcobucci\JWT\Signer\Key;
7+
use Pdsinterop\Solid\Auth\Enum\Jwk\Parameter as JwkParameter;
8+
use Pdsinterop\Solid\Auth\Enum\Rsa\Parameter as RsaParameter;
9+
10+
class Jwks implements JsonSerializable
11+
{
12+
////////////////////////////// CLASS PROPERTIES \\\\\\\\\\\\\\\\\\\\\\\\\\\\
13+
14+
/** @var Key */
15+
private $publicKey;
16+
17+
//////////////////////////////// PUBLIC API \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
18+
19+
final public function __construct(Key $publicKey)
20+
{
21+
$this->publicKey = $publicKey;
22+
}
23+
24+
final public function __toString() : string
25+
{
26+
return (string) json_encode($this);
27+
}
28+
29+
final public function jsonSerialize()
30+
{
31+
return $this->create();
32+
}
33+
34+
////////////////////////////// UTILITY METHODS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\
35+
36+
/**
37+
* @param string $certificate
38+
* @param $subject
39+
*
40+
* @return array
41+
*/
42+
private function createKey(string $certificate, $subject) : array
43+
{
44+
return [
45+
JwkParameter::ALGORITHM => 'RS256',
46+
JwkParameter::KEY_ID => md5($certificate),
47+
JwkParameter::KEY_TYPE => 'RSA',
48+
RsaParameter::PUBLIC_EXPONENT => 'AQAB', // Hard-coded as `Base64Url::encode($keyInfo['rsa']['e'])` tends to be empty...
49+
RsaParameter::PUBLIC_MODULUS => Base64Url::encode($subject),
50+
];
51+
}
52+
53+
/**
54+
* As the JWT library does not (yet?) have support for JWK, a custom solution is used for now.
55+
*
56+
* @return array
57+
*
58+
* @see https://github.com/lcobucci/jwt/issues/32
59+
*/
60+
private function create() : array
61+
{
62+
$jwks = ['keys' => []];
63+
64+
$publicKeys = [$this->publicKey];
65+
66+
array_walk($publicKeys, function (Key $publicKey) use (&$jwks) {
67+
$certificate = $publicKey->getContent();
68+
69+
$key = openssl_pkey_get_public($certificate);
70+
$keyInfo = openssl_pkey_get_details($key);
71+
72+
$jwks['keys'][] = $this->createKey($certificate, $keyInfo['rsa']['n']);
73+
});
74+
75+
return $jwks;
76+
}
77+
}

0 commit comments

Comments
 (0)