Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/KeyManagement/JWKFactory.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\KeyManagement;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\JWK;
9 use Jose\Component\Core\JWKSet;
10 use Jose\Component\Core\Util\Base64UrlSafe;
11 use Jose\Component\Core\Util\ECKey;
12 use Jose\Component\KeyManagement\KeyConverter\KeyConverter;
13 use Jose\Component\KeyManagement\KeyConverter\RSAKey;
14 use OpenSSLCertificate;
15 use RuntimeException;
16 use Throwable;
17 use function array_key_exists;
18 use function extension_loaded;
19 use function is_array;
20 use function is_string;
21 use const JSON_THROW_ON_ERROR;
22 use const OPENSSL_KEYTYPE_RSA;
23
24 /**
25 * @see \Jose\Tests\Component\KeyManagement\JWKFactoryTest
26 */
27 class JWKFactory
28 {
29 /**
30 * Creates a RSA key with the given key size and additional values.
31 *
32 * @param int $size The key size in bits
33 * @param array<string, mixed> $values values to configure the key
34 */
35 public static function createRSAKey(int $size, array $values = []): JWK
36 {
37 if (! extension_loaded('openssl')) {
38 throw new RuntimeException('Please install the OpenSSL extension');
39 }
40 if ($size % 8 !== 0) {
41 throw new InvalidArgumentException('Invalid key size.');
42 }
43 if ($size < 512) {
44 throw new InvalidArgumentException('Key length is too short. It needs to be at least 512 bits.');
45 }
46
47 $key = openssl_pkey_new([
48 'private_key_bits' => $size,
49 'private_key_type' => OPENSSL_KEYTYPE_RSA,
50 ]);
51 if ($key === false) {
52 throw new InvalidArgumentException('Unable to create the key');
53 }
54 $details = openssl_pkey_get_details($key);
55 if (! is_array($details)) {
56 throw new InvalidArgumentException('Unable to create the key');
57 }
58 $rsa = RSAKey::createFromKeyDetails($details['rsa']);
59 $values = array_merge($values, $rsa->toArray());
60
61 return new JWK($values);
62 }
63
64 /**
65 * Creates a EC key with the given curve and additional values.
66 *
67 * @param string $curve The curve
68 * @param array<string, mixed> $values values to configure the key
69 */
70 public static function createECKey(string $curve, array $values = []): JWK
71 {
72 return ECKey::createECKey($curve, $values);
73 }
74
75 /**
76 * Creates a octet key with the given key size and additional values.
77 *
78 * @param int $size The key size in bits
79 * @param array<string, mixed> $values values to configure the key
80 */
81 public static function createOctKey(int $size, array $values = []): JWK
82 {
83 if ($size % 8 !== 0) {
84 throw new InvalidArgumentException('Invalid key size.');
85 }
86
87 return self::createFromSecret(random_bytes($size / 8), $values);
88 }
89
90 /**
91 * Creates a OKP key with the given curve and additional values.
92 *
93 * @param string $curve The curve
94 * @param array<string, mixed> $values values to configure the key
95 */
96 public static function createOKPKey(string $curve, array $values = []): JWK
97 {
98 if (! extension_loaded('sodium')) {
99 throw new RuntimeException('The extension "sodium" is not available. Please install it to use this method');
100 }
101
102 switch ($curve) {
103 case 'X25519':
104 $keyPair = sodium_crypto_box_keypair();
105 $d = sodium_crypto_box_secretkey($keyPair);
106 $x = sodium_crypto_box_publickey($keyPair);
107
108 break;
109
110 case 'Ed25519':
111 $keyPair = sodium_crypto_sign_keypair();
112 $secret = sodium_crypto_sign_secretkey($keyPair);
113 $secretLength = mb_strlen($secret, '8bit');
114 $d = mb_substr($secret, 0, -$secretLength / 2, '8bit');
115 $x = sodium_crypto_sign_publickey($keyPair);
116
117 break;
118
119 default:
120 throw new InvalidArgumentException(sprintf('Unsupported "%s" curve', $curve));
121 }
122
123 $values = [
124 ...$values,
125 'kty' => 'OKP',
126 'crv' => $curve,
127 'd' => Base64UrlSafe::encodeUnpadded($d),
128 'x' => Base64UrlSafe::encodeUnpadded($x),
129 ];
130
131 return new JWK($values);
132 }
133
134 /**
135 * Creates a none key with the given additional values. Please note that this key type is not pat of any
136 * specification. It is used to prevent the use of the "none" algorithm with other key types.
137 *
138 * @param array<string, mixed> $values values to configure the key
139 */
140 public static function createNoneKey(array $values = []): JWK
141 {
142 $values = [
143 ...$values,
144 'kty' => 'none',
145 'alg' => 'none',
146 'use' => 'sig',
147 ];
148
149 return new JWK($values);
150 }
151
152 /**
153 * Creates a key from a Json string.
154 */
155 public static function createFromJsonObject(string $value): JWK|JWKSet
156 {
157 $json = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
158 if (! is_array($json)) {
159 throw new InvalidArgumentException('Invalid key or key set.');
160 }
161
162 return self::createFromValues($json);
163 }
164
165 /**
166 * Creates a key or key set from the given input.
167 */
168 public static function createFromValues(array $values): JWK|JWKSet
169 {
170 if (array_key_exists('keys', $values) && is_array($values['keys'])) {
171 return JWKSet::createFromKeyData($values);
172 }
173
174 return new JWK($values);
175 }
176
177 /**
178 * This method create a JWK object using a shared secret.
179 */
180 public static function createFromSecret(string $secret, array $additional_values = []): JWK
181 {
182 $values = array_merge(
183 $additional_values,
184 [
185 'kty' => 'oct',
186 'k' => Base64UrlSafe::encodeUnpadded($secret),
187 ]
188 );
189
190 return new JWK($values);
191 }
192
193 /**
194 * This method will try to load a X.509 certificate and convert it into a public key.
195 */
196 public static function createFromCertificateFile(string $file, array $additional_values = []): JWK
197 {
198 $values = KeyConverter::loadKeyFromCertificateFile($file);
199 $values = array_merge($values, $additional_values);
200
201 return new JWK($values);
202 }
203
204 /**
205 * Extract a keyfrom a key set identified by the given index .
206 */
207 public static function createFromKeySet(JWKSet $jwkset, int|string $index): JWK
208 {
209 return $jwkset->get($index);
210 }
211
212 /**
213 * This method will try to load a PKCS#12 file and convert it into a public key.
214 */
215 public static function createFromPKCS12CertificateFile(
216 string $file,
217 string $secret = '',
218 array $additional_values = []
219 ): JWK {
220 try {
221 $content = file_get_contents($file);
222 if (! is_string($content)) {
223 throw new RuntimeException('Unable to read the file.');
224 }
225 openssl_pkcs12_read($content, $certs, $secret);
226 if (! is_array($certs) || ! array_key_exists('pkey', $certs)) {
227 throw new RuntimeException('Unable to load the certificates.');
228 }
229
230 return self::createFromKey($certs['pkey'], null, $additional_values);
231 } catch (Throwable $throwable) {
232 throw new RuntimeException('Unable to load the certificates.', $throwable->getCode(), $throwable);
233 }
234 }
235
236 /**
237 * This method will try to convert a X.509 certificate into a public key.
238 */
239 public static function createFromCertificate(string $certificate, array $additional_values = []): JWK
240 {
241 $values = KeyConverter::loadKeyFromCertificate($certificate);
242 $values = array_merge($values, $additional_values);
243
244 return new JWK($values);
245 }
246
247 /**
248 * This method will try to convert a X.509 certificate resource into a public key.
249 */
250 public static function createFromX509Resource(OpenSSLCertificate $res, array $additional_values = []): JWK
251 {
252 $values = KeyConverter::loadKeyFromX509Resource($res);
253 $values = array_merge($values, $additional_values);
254
255 return new JWK($values);
256 }
257
258 /**
259 * This method will try to load and convert a key file into a JWK object. If the key is encrypted, the password must
260 * be set.
261 */
262 public static function createFromKeyFile(string $file, ?string $password = null, array $additional_values = []): JWK
263 {
264 $values = KeyConverter::loadFromKeyFile($file, $password);
265 $values = array_merge($values, $additional_values);
266
267 return new JWK($values);
268 }
269
270 /**
271 * This method will try to load and convert a key into a JWK object. If the key is encrypted, the password must be
272 * set.
273 */
274 public static function createFromKey(string $key, ?string $password = null, array $additional_values = []): JWK
275 {
276 $values = KeyConverter::loadFromKey($key, $password);
277 $values = array_merge($values, $additional_values);
278
279 return new JWK($values);
280 }
281
282 /**
283 * This method will try to load and convert a X.509 certificate chain into a public key.
284 *
285 * Be careful! The certificate chain is loaded, but it is NOT VERIFIED by any mean! It is mandatory to verify the
286 * root CA or intermediate CA are trusted. If not done, it may lead to potential security issues.
287 */
288 public static function createFromX5C(array $x5c, array $additional_values = []): JWK
289 {
290 $values = KeyConverter::loadFromX5C($x5c);
291 $values = array_merge($values, $additional_values);
292
293 return new JWK($values);
294 }
295 }