Debian Codegraph @

lib/3rdParty/composer/firebase/php-jwt/src/JWT.php

raw symbols SCIP
1 <?php
2
3 namespace Firebase\JWT;
4
5 use ArrayAccess;
6 use DateTime;
7 use DomainException;
8 use Exception;
9 use InvalidArgumentException;
10 use OpenSSLAsymmetricKey;
11 use OpenSSLCertificate;
12 use stdClass;
13 use UnexpectedValueException;
14
15 /**
16 * JSON Web Token implementation, based on this spec:
17 * https://tools.ietf.org/html/rfc7519
18 *
19 * PHP version 5
20 *
21 * @category Authentication
22 * @package Authentication_JWT
23 * @author Neuman Vong <[email protected]>
24 * @author Anant Narayanan <[email protected]>
25 * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
26 * @link https://github.com/firebase/php-jwt
27 */
28 class JWT
29 {
30 private const ASN1_INTEGER = 0x02;
31 private const ASN1_SEQUENCE = 0x10;
32 private const ASN1_BIT_STRING = 0x03;
33
34 private const RSA_KEY_MIN_LENGTH = 2048;
35
36 /**
37 * When checking nbf, iat or expiration times,
38 * we want to provide some extra leeway time to
39 * account for clock skew.
40 *
41 * @var int
42 */
43 public static $leeway = 0;
44
45 /**
46 * Allow the current timestamp to be specified.
47 * Useful for fixing a value within unit testing.
48 * Will default to PHP time() value if null.
49 *
50 * @var ?int
51 */
52 public static $timestamp = null;
53
54 /**
55 * @var array<string, string[]>
56 */
57 public static $supported_algs = [
58 'ES384' => ['openssl', 'SHA384'],
59 'ES256' => ['openssl', 'SHA256'],
60 'ES256K' => ['openssl', 'SHA256'],
61 'HS256' => ['hash_hmac', 'SHA256'],
62 'HS384' => ['hash_hmac', 'SHA384'],
63 'HS512' => ['hash_hmac', 'SHA512'],
64 'RS256' => ['openssl', 'SHA256'],
65 'RS384' => ['openssl', 'SHA384'],
66 'RS512' => ['openssl', 'SHA512'],
67 'EdDSA' => ['sodium_crypto', 'EdDSA'],
68 ];
69
70 /**
71 * Decodes a JWT string into a PHP object.
72 *
73 * @param string $jwt The JWT
74 * @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray The Key or associative array of key IDs
75 * (kid) to Key objects.
76 * If the algorithm used is asymmetric, this is
77 * the public key.
78 * Each Key object contains an algorithm and
79 * matching key.
80 * Supported algorithms are 'ES384','ES256',
81 * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384'
82 * and 'RS512'.
83 * @param stdClass $headers Optional. Populates stdClass with headers.
84 *
85 * @return stdClass The JWT's payload as a PHP object
86 *
87 * @throws InvalidArgumentException Provided key/key-array was empty or malformed
88 * @throws DomainException Provided JWT is malformed
89 * @throws UnexpectedValueException Provided JWT was invalid
90 * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
91 * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
92 * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
93 * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
94 *
95 * @uses jsonDecode
96 * @uses urlsafeB64Decode
97 */
98 public static function decode(
99 string $jwt,
100 #[\SensitiveParameter] $keyOrKeyArray,
101 ?stdClass &$headers = null
102 ): stdClass {
103 // Validate JWT
104 $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
105
106 if (empty($keyOrKeyArray)) {
107 throw new InvalidArgumentException('Key may not be empty');
108 }
109 $tks = \explode('.', $jwt);
110 if (\count($tks) !== 3) {
111 throw new UnexpectedValueException('Wrong number of segments');
112 }
113 list($headb64, $bodyb64, $cryptob64) = $tks;
114 $headerRaw = static::urlsafeB64Decode($headb64);
115 if (null === ($header = static::jsonDecode($headerRaw))) {
116 throw new UnexpectedValueException('Invalid header encoding');
117 }
118 if ($headers !== null) {
119 $headers = $header;
120 }
121 $payloadRaw = static::urlsafeB64Decode($bodyb64);
122 if (null === ($payload = static::jsonDecode($payloadRaw))) {
123 throw new UnexpectedValueException('Invalid claims encoding');
124 }
125 if (\is_array($payload)) {
126 // prevent PHP Fatal Error in edge-cases when payload is empty array
127 $payload = (object) $payload;
128 }
129 if (!$payload instanceof stdClass) {
130 throw new UnexpectedValueException('Payload must be a JSON object');
131 }
132 if (isset($payload->iat) && !\is_numeric($payload->iat)) {
133 throw new UnexpectedValueException('Payload iat must be a number');
134 }
135 if (isset($payload->nbf) && !\is_numeric($payload->nbf)) {
136 throw new UnexpectedValueException('Payload nbf must be a number');
137 }
138 if (isset($payload->exp) && !\is_numeric($payload->exp)) {
139 throw new UnexpectedValueException('Payload exp must be a number');
140 }
141
142 $sig = static::urlsafeB64Decode($cryptob64);
143 if (empty($header->alg)) {
144 throw new UnexpectedValueException('Empty algorithm');
145 }
146 if (empty(static::$supported_algs[$header->alg])) {
147 throw new UnexpectedValueException('Algorithm not supported');
148 }
149
150 $key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null);
151
152 // Check the algorithm
153 if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) {
154 // See issue #351
155 throw new UnexpectedValueException('Incorrect key for this algorithm');
156 }
157 if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) {
158 // OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures
159 $sig = self::signatureToDER($sig);
160 }
161 if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) {
162 throw new SignatureInvalidException('Signature verification failed');
163 }
164
165 // Check the nbf if it is defined. This is the time that the
166 // token can actually be used. If it's not yet that time, abort.
167 if (isset($payload->nbf) && floor($payload->nbf) > ($timestamp + static::$leeway)) {
168 $ex = new BeforeValidException(
169 'Cannot handle token with nbf prior to ' . \date(DateTime::ATOM, (int) floor($payload->nbf))
170 );
171 $ex->setPayload($payload);
172 throw $ex;
173 }
174
175 // Check that this token has been created before 'now'. This prevents
176 // using tokens that have been created for later use (and haven't
177 // correctly used the nbf claim).
178 if (!isset($payload->nbf) && isset($payload->iat) && floor($payload->iat) > ($timestamp + static::$leeway)) {
179 $ex = new BeforeValidException(
180 'Cannot handle token with iat prior to ' . \date(DateTime::ATOM, (int) floor($payload->iat))
181 );
182 $ex->setPayload($payload);
183 throw $ex;
184 }
185
186 // Check if this token has expired.
187 if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
188 $ex = new ExpiredException('Expired token');
189 $ex->setPayload($payload);
190 $ex->setTimestamp($timestamp);
191 throw $ex;
192 }
193
194 return $payload;
195 }
196
197 /**
198 * Converts and signs a PHP array into a JWT string.
199 *
200 * @param array<mixed> $payload PHP array
201 * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
202 * @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256',
203 * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
204 * @param string $keyId
205 * @param array<string, string|string[]> $head An array with header elements to attach
206 *
207 * @return string A signed JWT
208 *
209 * @uses jsonEncode
210 * @uses urlsafeB64Encode
211 */
212 public static function encode(
213 array $payload,
214 #[\SensitiveParameter] $key,
215 string $alg,
216 ?string $keyId = null,
217 ?array $head = null
218 ): string {
219 $header = ['typ' => 'JWT'];
220 if (isset($head)) {
221 $header = \array_merge($header, $head);
222 }
223 $header['alg'] = $alg;
224 if ($keyId !== null) {
225 $header['kid'] = $keyId;
226 }
227 $segments = [];
228 $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
229 $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
230 $signing_input = \implode('.', $segments);
231
232 $signature = static::sign($signing_input, $key, $alg);
233 $segments[] = static::urlsafeB64Encode($signature);
234
235 return \implode('.', $segments);
236 }
237
238 /**
239 * Sign a string with a given key and algorithm.
240 *
241 * @param string $msg The message to sign
242 * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
243 * @param string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256',
244 * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
245 *
246 * @return string An encrypted message
247 *
248 * @throws DomainException Unsupported algorithm or bad key was specified
249 */
250 public static function sign(
251 string $msg,
252 #[\SensitiveParameter] $key,
253 string $alg
254 ): string {
255 if (empty(static::$supported_algs[$alg])) {
256 throw new DomainException('Algorithm not supported');
257 }
258 list($function, $algorithm) = static::$supported_algs[$alg];
259 switch ($function) {
260 case 'hash_hmac':
261 if (!\is_string($key)) {
262 throw new InvalidArgumentException('key must be a string when using hmac');
263 }
264 self::validateHmacKeyLength($key, $algorithm);
265 return \hash_hmac($algorithm, $msg, $key, true);
266 case 'openssl':
267 $signature = '';
268 if (!$key = openssl_pkey_get_private($key)) {
269 throw new DomainException('OpenSSL unable to validate key');
270 }
271 if (str_starts_with($alg, 'RS')) {
272 self::validateRsaKeyLength($key);
273 } elseif (str_starts_with($alg, 'ES')) {
274 self::validateEcKeyLength($key, $alg);
275 }
276 $success = \openssl_sign($msg, $signature, $key, $algorithm);
277 if (!$success) {
278 throw new DomainException('OpenSSL unable to sign data');
279 }
280 if ($alg === 'ES256' || $alg === 'ES256K') {
281 $signature = self::signatureFromDER($signature, 256);
282 } elseif ($alg === 'ES384') {
283 $signature = self::signatureFromDER($signature, 384);
284 }
285 return $signature;
286 case 'sodium_crypto':
287 try {
288 return sodium_crypto_sign_detached($msg, self::validateEdDSAKey($key));
289 } catch (Exception $e) {
290 throw new DomainException($e->getMessage(), 0, $e);
291 }
292 }
293
294 throw new DomainException('Algorithm not supported');
295 }
296
297 /**
298 * Verify a signature with the message, key and method. Not all methods
299 * are symmetric, so we must have a separate verify and sign method.
300 *
301 * @param string $msg The original message (header and body)
302 * @param string $signature The original signature
303 * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For Ed*, ES*, HS*, a string key works. for RS*, must be an instance of OpenSSLAsymmetricKey
304 * @param string $alg The algorithm
305 *
306 * @return bool
307 *
308 * @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure
309 */
310 private static function verify(
311 string $msg,
312 string $signature,
313 #[\SensitiveParameter] $keyMaterial,
314 string $alg
315 ): bool {
316 if (empty(static::$supported_algs[$alg])) {
317 throw new DomainException('Algorithm not supported');
318 }
319
320 list($function, $algorithm) = static::$supported_algs[$alg];
321 switch ($function) {
322 case 'openssl':
323 if (!$key = openssl_pkey_get_public($keyMaterial)) {
324 throw new DomainException('OpenSSL unable to validate key');
325 }
326 if (str_starts_with($alg, 'RS')) {
327 self::validateRsaKeyLength($key);
328 } elseif (str_starts_with($alg, 'ES')) {
329 self::validateEcKeyLength($key, $alg);
330 }
331 $success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm);
332 if ($success === 1) {
333 return true;
334 }
335 if ($success === 0) {
336 return false;
337 }
338 // returns 1 on success, 0 on failure, -1 on error.
339 throw new DomainException(
340 'OpenSSL error: ' . \openssl_error_string()
341 );
342 case 'sodium_crypto':
343 try {
344 $key = self::validateEdDSAKey($keyMaterial);
345 if (\strlen($signature) === 0) {
346 throw new DomainException('Signature cannot be empty string');
347 }
348 return sodium_crypto_sign_verify_detached($signature, $msg, $key);
349 } catch (Exception $e) {
350 throw new DomainException($e->getMessage(), 0, $e);
351 }
352 case 'hash_hmac':
353 default:
354 if (!\is_string($keyMaterial)) {
355 throw new InvalidArgumentException('key must be a string when using hmac');
356 }
357 self::validateHmacKeyLength($keyMaterial, $algorithm);
358 $hash = \hash_hmac($algorithm, $msg, $keyMaterial, true);
359 return self::constantTimeEquals($hash, $signature);
360 }
361 }
362
363 /**
364 * Decode a JSON string into a PHP object.
365 *
366 * @param string $input JSON string
367 *
368 * @return mixed The decoded JSON string
369 *
370 * @throws DomainException Provided string was invalid JSON
371 */
372 public static function jsonDecode(string $input)
373 {
374 $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
375
376 if ($errno = \json_last_error()) {
377 self::handleJsonError($errno);
378 } elseif ($obj === null && $input !== 'null') {
379 throw new DomainException('Null result with non-null input');
380 }
381 return $obj;
382 }
383
384 /**
385 * Encode a PHP array into a JSON string.
386 *
387 * @param array<mixed> $input A PHP array
388 *
389 * @return string JSON representation of the PHP array
390 *
391 * @throws DomainException Provided object could not be encoded to valid JSON
392 */
393 public static function jsonEncode(array $input): string
394 {
395 $json = \json_encode($input, \JSON_UNESCAPED_SLASHES);
396 if ($errno = \json_last_error()) {
397 self::handleJsonError($errno);
398 } elseif ($json === 'null') {
399 throw new DomainException('Null result with non-null input');
400 }
401 if ($json === false) {
402 throw new DomainException('Provided object could not be encoded to valid JSON');
403 }
404 return $json;
405 }
406
407 /**
408 * Decode a string with URL-safe Base64.
409 *
410 * @param string $input A Base64 encoded string
411 *
412 * @return string A decoded string
413 *
414 * @throws InvalidArgumentException invalid base64 characters
415 */
416 public static function urlsafeB64Decode(string $input): string
417 {
418 return \base64_decode(self::convertBase64UrlToBase64($input));
419 }
420
421 /**
422 * Convert a string in the base64url (URL-safe Base64) encoding to standard base64.
423 *
424 * @param string $input A Base64 encoded string with URL-safe characters (-_ and no padding)
425 *
426 * @return string A Base64 encoded string with standard characters (+/) and padding (=), when
427 * needed.
428 *
429 * @see https://www.rfc-editor.org/rfc/rfc4648
430 */
431 public static function convertBase64UrlToBase64(string $input): string
432 {
433 $remainder = \strlen($input) % 4;
434 if ($remainder) {
435 $padlen = 4 - $remainder;
436 $input .= \str_repeat('=', $padlen);
437 }
438 return \strtr($input, '-_', '+/');
439 }
440
441 /**
442 * Encode a string with URL-safe Base64.
443 *
444 * @param string $input The string you want encoded
445 *
446 * @return string The base64 encode of what you passed in
447 */
448 public static function urlsafeB64Encode(string $input): string
449 {
450 return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
451 }
452
453 /**
454 * Determine if an algorithm has been provided for each Key
455 *
456 * @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray
457 * @param string|null $kid
458 *
459 * @throws UnexpectedValueException
460 *
461 * @return Key
462 */
463 private static function getKey(
464 #[\SensitiveParameter] $keyOrKeyArray,
465 ?string $kid
466 ): Key {
467 if ($keyOrKeyArray instanceof Key) {
468 return $keyOrKeyArray;
469 }
470
471 if (empty($kid) && $kid !== '0') {
472 throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
473 }
474
475 if ($keyOrKeyArray instanceof CachedKeySet) {
476 // Skip "isset" check, as this will automatically refresh if not set
477 return $keyOrKeyArray[$kid];
478 }
479
480 if (!isset($keyOrKeyArray[$kid])) {
481 throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
482 }
483
484 return $keyOrKeyArray[$kid];
485 }
486
487 /**
488 * @param string $left The string of known length to compare against
489 * @param string $right The user-supplied string
490 * @return bool
491 */
492 public static function constantTimeEquals(string $left, string $right): bool
493 {
494 if (\function_exists('hash_equals')) {
495 return \hash_equals($left, $right);
496 }
497 $len = \min(self::safeStrlen($left), self::safeStrlen($right));
498
499 $status = 0;
500 for ($i = 0; $i < $len; $i++) {
501 $status |= (\ord($left[$i]) ^ \ord($right[$i]));
502 }
503 $status |= (self::safeStrlen($left) ^ self::safeStrlen($right));
504
505 return ($status === 0);
506 }
507
508 /**
509 * Helper method to create a JSON error.
510 *
511 * @param int $errno An error number from json_last_error()
512 *
513 * @throws DomainException
514 *
515 * @return void
516 */
517 private static function handleJsonError(int $errno): void
518 {
519 $messages = [
520 JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
521 JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
522 JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
523 JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
524 JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
525 ];
526 throw new DomainException(
527 isset($messages[$errno])
528 ? $messages[$errno]
529 : 'Unknown JSON error: ' . $errno
530 );
531 }
532
533 /**
534 * Get the number of bytes in cryptographic strings.
535 *
536 * @param string $str
537 *
538 * @return int
539 */
540 private static function safeStrlen(string $str): int
541 {
542 if (\function_exists('mb_strlen')) {
543 return \mb_strlen($str, '8bit');
544 }
545 return \strlen($str);
546 }
547
548 /**
549 * Convert an ECDSA signature to an ASN.1 DER sequence
550 *
551 * @param string $sig The ECDSA signature to convert
552 * @return string The encoded DER object
553 */
554 private static function signatureToDER(string $sig): string
555 {
556 // Separate the signature into r-value and s-value
557 $length = max(1, (int) (\strlen($sig) / 2));
558 list($r, $s) = \str_split($sig, $length);
559
560 // Trim leading zeros
561 $r = \ltrim($r, "\x00");
562 $s = \ltrim($s, "\x00");
563
564 // Convert r-value and s-value from unsigned big-endian integers to
565 // signed two's complement
566 if (\ord($r[0]) > 0x7f) {
567 $r = "\x00" . $r;
568 }
569 if (\ord($s[0]) > 0x7f) {
570 $s = "\x00" . $s;
571 }
572
573 return self::encodeDER(
574 self::ASN1_SEQUENCE,
575 self::encodeDER(self::ASN1_INTEGER, $r) .
576 self::encodeDER(self::ASN1_INTEGER, $s)
577 );
578 }
579
580 /**
581 * Encodes a value into a DER object.
582 *
583 * @param int $type DER tag
584 * @param string $value the value to encode
585 *
586 * @return string the encoded object
587 */
588 private static function encodeDER(int $type, string $value): string
589 {
590 $tag_header = 0;
591 if ($type === self::ASN1_SEQUENCE) {
592 $tag_header |= 0x20;
593 }
594
595 // Type
596 $der = \chr($tag_header | $type);
597
598 // Length
599 $der .= \chr(\strlen($value));
600
601 return $der . $value;
602 }
603
604 /**
605 * Encodes signature from a DER object.
606 *
607 * @param string $der binary signature in DER format
608 * @param int $keySize the number of bits in the key
609 *
610 * @return string the signature
611 */
612 private static function signatureFromDER(string $der, int $keySize): string
613 {
614 // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
615 list($offset, $_) = self::readDER($der);
616 list($offset, $r) = self::readDER($der, $offset);
617 list($offset, $s) = self::readDER($der, $offset);
618
619 // Convert r-value and s-value from signed two's compliment to unsigned
620 // big-endian integers
621 $r = \ltrim($r, "\x00");
622 $s = \ltrim($s, "\x00");
623
624 // Pad out r and s so that they are $keySize bits long
625 $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
626 $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
627
628 return $r . $s;
629 }
630
631 /**
632 * Reads binary DER-encoded data and decodes into a single object
633 *
634 * @param string $der the binary data in DER format
635 * @param int $offset the offset of the data stream containing the object
636 * to decode
637 *
638 * @return array{int, string|null} the new offset and the decoded object
639 */
640 private static function readDER(string $der, int $offset = 0): array
641 {
642 $pos = $offset;
643 $size = \strlen($der);
644 $constructed = (\ord($der[$pos]) >> 5) & 0x01;
645 $type = \ord($der[$pos++]) & 0x1f;
646
647 // Length
648 $len = \ord($der[$pos++]);
649 if ($len & 0x80) {
650 $n = $len & 0x1f;
651 $len = 0;
652 while ($n-- && $pos < $size) {
653 $len = ($len << 8) | \ord($der[$pos++]);
654 }
655 }
656
657 // Value
658 if ($type === self::ASN1_BIT_STRING) {
659 $pos++; // Skip the first contents octet (padding indicator)
660 $data = \substr($der, $pos, $len - 1);
661 $pos += $len - 1;
662 } elseif (!$constructed) {
663 $data = \substr($der, $pos, $len);
664 $pos += $len;
665 } else {
666 $data = null;
667 }
668
669 return [$pos, $data];
670 }
671
672 /**
673 * Validate HMAC key length
674 *
675 * @param string $key HMAC key material
676 * @param string $algorithm The algorithm
677 *
678 * @throws DomainException Provided key is too short
679 */
680 private static function validateHmacKeyLength(string $key, string $algorithm): void
681 {
682 $keyLength = \strlen($key) * 8;
683 $minKeyLength = (int) \str_replace('SHA', '', $algorithm);
684 if ($keyLength < $minKeyLength) {
685 throw new DomainException('Provided key is too short');
686 }
687 }
688
689 /**
690 * Validate RSA key length
691 *
692 * @param OpenSSLAsymmetricKey $key RSA key material
693 * @throws DomainException Provided key is too short
694 */
695 private static function validateRsaKeyLength(#[\SensitiveParameter] OpenSSLAsymmetricKey $key): void
696 {
697 if (!$keyDetails = openssl_pkey_get_details($key)) {
698 throw new DomainException('Unable to validate key');
699 }
700 if ($keyDetails['bits'] < self::RSA_KEY_MIN_LENGTH) {
701 throw new DomainException('Provided key is too short');
702 }
703 }
704
705 /**
706 * Validate RSA key length
707 *
708 * @param OpenSSLAsymmetricKey $key RSA key material
709 * @param string $algorithm The algorithm
710 * @throws DomainException Provided key is too short
711 */
712 private static function validateEcKeyLength(
713 #[\SensitiveParameter] OpenSSLAsymmetricKey $key,
714 string $algorithm
715 ): void {
716 if (!$keyDetails = openssl_pkey_get_details($key)) {
717 throw new DomainException('Unable to validate key');
718 }
719 $minKeyLength = (int) \str_replace('ES', '', $algorithm);
720 if ($keyDetails['bits'] < $minKeyLength) {
721 throw new DomainException('Provided key is too short');
722 }
723 }
724
725 /**
726 * @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial
727 * @return non-empty-string
728 */
729 private static function validateEdDSAKey(#[\SensitiveParameter] $keyMaterial): string
730 {
731 if (!\function_exists('sodium_crypto_sign_verify_detached')) {
732 throw new DomainException('libsodium is not available');
733 }
734 if (!\is_string($keyMaterial)) {
735 throw new InvalidArgumentException('key must be a string when using EdDSA');
736 }
737 // The last non-empty line is used as the key.
738 $lines = array_filter(explode("\n", $keyMaterial));
739 $key = self::urlsafeB64Decode((string) end($lines));
740 if (\strlen($key) === 0) {
741 throw new DomainException('Key cannot be empty string');
742 }
743 return $key;
744 }
745 }