Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Core/Util/KeyChecker.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Core\Util;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\JWK;
9 use function in_array;
10 use function is_array;
11 use function is_string;
12
13 /**
14 * @internal
15 */
16 final class KeyChecker
17 {
18 public static function checkKeyUsage(JWK $key, string $usage): void
19 {
20 if ($key->has('use')) {
21 self::checkUsage($key, $usage);
22 }
23 if ($key->has('key_ops')) {
24 self::checkOperation($key, $usage);
25 }
26 }
27
28 public static function checkKeyAlgorithm(JWK $key, string $algorithm): void
29 {
30 if (! $key->has('alg')) {
31 return;
32 }
33 $alg = $key->get('alg');
34 if (! is_string($alg)) {
35 throw new InvalidArgumentException('Invalid algorithm.');
36 }
37 if ($alg !== $algorithm) {
38 throw new InvalidArgumentException(sprintf('Key is only allowed for algorithm "%s".', $alg));
39 }
40 }
41
42 private static function checkOperation(JWK $key, string $usage): void
43 {
44 $ops = $key->get('key_ops');
45 if (! is_array($ops)) {
46 throw new InvalidArgumentException('Invalid key parameter "key_ops". Should be a list of key operations');
47 }
48
49 switch ($usage) {
50 case 'verification':
51 if (! in_array('verify', $ops, true)) {
52 throw new InvalidArgumentException('Key cannot be used to verify a signature');
53 }
54
55 break;
56
57 case 'signature':
58 if (! in_array('sign', $ops, true)) {
59 throw new InvalidArgumentException('Key cannot be used to sign');
60 }
61
62 break;
63
64 case 'encryption':
65 if (! in_array('encrypt', $ops, true) && ! in_array('wrapKey', $ops, true) && ! in_array(
66 'deriveKey',
67 $ops,
68 true
69 )) {
70 throw new InvalidArgumentException('Key cannot be used to encrypt');
71 }
72
73 break;
74
75 case 'decryption':
76 if (! in_array('decrypt', $ops, true) && ! in_array('unwrapKey', $ops, true) && ! in_array(
77 'deriveBits',
78 $ops,
79 true
80 )) {
81 throw new InvalidArgumentException('Key cannot be used to decrypt');
82 }
83
84 break;
85
86 default:
87 throw new InvalidArgumentException('Unsupported key usage.');
88 }
89 }
90
91 private static function checkUsage(JWK $key, string $usage): void
92 {
93 $use = $key->get('use');
94
95 switch ($usage) {
96 case 'verification':
97 case 'signature':
98 if ($use !== 'sig') {
99 throw new InvalidArgumentException('Key cannot be used to sign or verify a signature.');
100 }
101
102 break;
103
104 case 'encryption':
105 case 'decryption':
106 if ($use !== 'enc') {
107 throw new InvalidArgumentException('Key cannot be used to encrypt or decrypt.');
108 }
109
110 break;
111
112 default:
113 throw new InvalidArgumentException('Unsupported key usage.');
114 }
115 }
116 }