Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Encryption/JWEDecrypter.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Encryption;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\Algorithm;
9 use Jose\Component\Core\AlgorithmManager;
10 use Jose\Component\Core\JWK;
11 use Jose\Component\Core\JWKSet;
12 use Jose\Component\Core\Util\KeyChecker;
13 use Jose\Component\Encryption\Algorithm\ContentEncryptionAlgorithm;
14 use Jose\Component\Encryption\Algorithm\KeyEncryption\DirectEncryption;
15 use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyAgreement;
16 use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyAgreementWithKeyWrapping;
17 use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyEncryption;
18 use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyWrapping;
19 use Jose\Component\Encryption\Algorithm\KeyEncryptionAlgorithm;
20 use Jose\Component\Encryption\Compression\CompressionMethodManager;
21 use Throwable;
22 use function array_key_exists;
23 use function is_string;
24
25 class JWEDecrypter
26 {
27 private readonly AlgorithmManager $keyEncryptionAlgorithmManager;
28
29 private readonly AlgorithmManager $contentEncryptionAlgorithmManager;
30
31 public function __construct(
32 AlgorithmManager $algorithmManager,
33 null|AlgorithmManager $contentEncryptionAlgorithmManager,
34 private readonly null|CompressionMethodManager $compressionMethodManager = null
35 ) {
36 if ($compressionMethodManager !== null) {
37 trigger_deprecation(
38 'web-token/jwt-library',
39 '3.3.0',
40 'The parameter "$compressionMethodManager" is deprecated and will be removed in 4.0.0. Compression is not recommended for JWE. Please set "null" instead.'
41 );
42 }
43 if ($contentEncryptionAlgorithmManager !== null) {
44 trigger_deprecation(
45 'web-token/jwt-library',
46 '3.3.0',
47 'The parameter "$contentEncryptionAlgorithmManager" is deprecated and will be removed in 4.0.0. Please set all algorithms in the first argument and set "null" instead.'
48 );
49 $this->keyEncryptionAlgorithmManager = $algorithmManager;
50 $this->contentEncryptionAlgorithmManager = $contentEncryptionAlgorithmManager;
51 } else {
52 $keyEncryptionAlgorithms = [];
53 $contentEncryptionAlgorithms = [];
54 foreach ($algorithmManager->all() as $key => $algorithm) {
55 if ($algorithm instanceof KeyEncryptionAlgorithm) {
56 $keyEncryptionAlgorithms[$key] = $algorithm;
57 }
58 if ($algorithm instanceof ContentEncryptionAlgorithm) {
59 $contentEncryptionAlgorithms[$key] = $algorithm;
60 }
61 }
62 $this->keyEncryptionAlgorithmManager = new AlgorithmManager($keyEncryptionAlgorithms);
63 $this->contentEncryptionAlgorithmManager = new AlgorithmManager($contentEncryptionAlgorithms);
64 }
65 }
66
67 /**
68 * Returns the key encryption algorithm manager.
69 */
70 public function getKeyEncryptionAlgorithmManager(): AlgorithmManager
71 {
72 return $this->keyEncryptionAlgorithmManager;
73 }
74
75 /**
76 * Returns the content encryption algorithm manager.
77 */
78 public function getContentEncryptionAlgorithmManager(): AlgorithmManager
79 {
80 return $this->contentEncryptionAlgorithmManager;
81 }
82
83 /**
84 * Returns the compression method manager.
85 * @deprecated This method is deprecated and will be removed in v4.0. Compression is not recommended for JWE.
86 */
87 public function getCompressionMethodManager(): null|CompressionMethodManager
88 {
89 return $this->compressionMethodManager;
90 }
91
92 /**
93 * This method will try to decrypt the given JWE and recipient using a JWK.
94 *
95 * @param JWE $jwe A JWE object to decrypt
96 * @param JWK $jwk The key used to decrypt the input
97 * @param int $recipient The recipient used to decrypt the token
98 */
99 public function decryptUsingKey(JWE &$jwe, JWK $jwk, int $recipient, ?JWK $senderKey = null): bool
100 {
101 $jwkset = new JWKSet([$jwk]);
102
103 return $this->decryptUsingKeySet($jwe, $jwkset, $recipient, $senderKey);
104 }
105
106 /**
107 * This method will try to decrypt the given JWE and recipient using a JWKSet.
108 *
109 * @param JWE $jwe A JWE object to decrypt
110 * @param JWKSet $jwkset The key set used to decrypt the input
111 * @param JWK $jwk The key used to decrypt the token in case of success
112 * @param int $recipient The recipient used to decrypt the token in case of success
113 */
114 public function decryptUsingKeySet(
115 JWE &$jwe,
116 JWKSet $jwkset,
117 int $recipient,
118 ?JWK &$jwk = null,
119 ?JWK $senderKey = null
120 ): bool {
121 if ($jwkset->count() === 0) {
122 throw new InvalidArgumentException('No key in the key set.');
123 }
124 if ($jwe->getPayload() !== null) {
125 return true;
126 }
127 if ($jwe->countRecipients() === 0) {
128 throw new InvalidArgumentException('The JWE does not contain any recipient.');
129 }
130
131 $plaintext = $this->decryptRecipientKey($jwe, $jwkset, $recipient, $jwk, $senderKey);
132 if ($plaintext !== null) {
133 $jwe = $jwe->withPayload($plaintext);
134
135 return true;
136 }
137
138 return false;
139 }
140
141 private function decryptRecipientKey(
142 JWE $jwe,
143 JWKSet $jwkset,
144 int $i,
145 ?JWK &$successJwk = null,
146 ?JWK $senderKey = null
147 ): ?string {
148 $recipient = $jwe->getRecipient($i);
149 $completeHeader = array_merge(
150 $jwe->getSharedProtectedHeader(),
151 $jwe->getSharedHeader(),
152 $recipient->getHeader()
153 );
154 $this->checkCompleteHeader($completeHeader);
155
156 $key_encryption_algorithm = $this->getKeyEncryptionAlgorithm($completeHeader);
157 $content_encryption_algorithm = $this->getContentEncryptionAlgorithm($completeHeader);
158
159 $this->checkIvSize($jwe->getIV(), $content_encryption_algorithm->getIVSize());
160
161 foreach ($jwkset as $recipientKey) {
162 try {
163 KeyChecker::checkKeyUsage($recipientKey, 'decryption');
164 if ($key_encryption_algorithm->name() !== 'dir') {
165 KeyChecker::checkKeyAlgorithm($recipientKey, $key_encryption_algorithm->name());
166 } else {
167 KeyChecker::checkKeyAlgorithm($recipientKey, $content_encryption_algorithm->name());
168 }
169 $cek = $this->decryptCEK(
170 $key_encryption_algorithm,
171 $content_encryption_algorithm,
172 $recipientKey,
173 $senderKey,
174 $recipient,
175 $completeHeader
176 );
177 $this->checkCekSize($cek, $key_encryption_algorithm, $content_encryption_algorithm);
178 $payload = $this->decryptPayload($jwe, $cek, $content_encryption_algorithm, $completeHeader);
179 $successJwk = $recipientKey;
180
181 return $payload;
182 } catch (Throwable) {
183 //We do nothing, we continue with other keys
184 continue;
185 }
186 }
187
188 return null;
189 }
190
191 private function checkCekSize(
192 string $cek,
193 KeyEncryptionAlgorithm $keyEncryptionAlgorithm,
194 ContentEncryptionAlgorithm $algorithm
195 ): void {
196 if ($keyEncryptionAlgorithm instanceof DirectEncryption || $keyEncryptionAlgorithm instanceof KeyAgreement) {
197 return;
198 }
199 if (mb_strlen($cek, '8bit') * 8 !== $algorithm->getCEKSize()) {
200 throw new InvalidArgumentException('Invalid CEK size');
201 }
202 }
203
204 private function checkIvSize(?string $iv, int $requiredIvSize): void
205 {
206 if ($iv === null && $requiredIvSize !== 0) {
207 throw new InvalidArgumentException('Invalid IV size');
208 }
209 if (is_string($iv) && mb_strlen($iv, '8bit') !== $requiredIvSize / 8) {
210 throw new InvalidArgumentException('Invalid IV size');
211 }
212 }
213
214 private function decryptCEK(
215 Algorithm $key_encryption_algorithm,
216 ContentEncryptionAlgorithm $content_encryption_algorithm,
217 JWK $recipientKey,
218 ?JWK $senderKey,
219 Recipient $recipient,
220 array $completeHeader
221 ): string {
222 if ($key_encryption_algorithm instanceof DirectEncryption) {
223 return $key_encryption_algorithm->getCEK($recipientKey);
224 }
225 if ($key_encryption_algorithm instanceof KeyAgreement) {
226 return $key_encryption_algorithm->getAgreementKey(
227 $content_encryption_algorithm->getCEKSize(),
228 $content_encryption_algorithm->name(),
229 $recipientKey,
230 $senderKey,
231 $completeHeader
232 );
233 }
234 if ($key_encryption_algorithm instanceof KeyAgreementWithKeyWrapping) {
235 return $key_encryption_algorithm->unwrapAgreementKey(
236 $recipientKey,
237 $senderKey,
238 $recipient->getEncryptedKey() ?? '',
239 $content_encryption_algorithm->getCEKSize(),
240 $completeHeader
241 );
242 }
243 if ($key_encryption_algorithm instanceof KeyEncryption) {
244 return $key_encryption_algorithm->decryptKey(
245 $recipientKey,
246 $recipient->getEncryptedKey() ?? '',
247 $completeHeader
248 );
249 }
250 if ($key_encryption_algorithm instanceof KeyWrapping) {
251 return $key_encryption_algorithm->unwrapKey(
252 $recipientKey,
253 $recipient->getEncryptedKey() ?? '',
254 $completeHeader
255 );
256 }
257
258 throw new InvalidArgumentException('Unsupported CEK generation');
259 }
260
261 private function decryptPayload(
262 JWE $jwe,
263 string $cek,
264 ContentEncryptionAlgorithm $content_encryption_algorithm,
265 array $completeHeader
266 ): string {
267 $payload = $content_encryption_algorithm->decryptContent(
268 $jwe->getCiphertext() ?? '',
269 $cek,
270 $jwe->getIV() ?? '',
271 $jwe->getAAD(),
272 $jwe->getEncodedSharedProtectedHeader(),
273 $jwe->getTag() ?? ''
274 );
275
276 return $this->decompressIfNeeded($payload, $completeHeader);
277 }
278
279 private function decompressIfNeeded(string $payload, array $completeHeaders): string
280 {
281 if ($this->compressionMethodManager === null || ! array_key_exists('zip', $completeHeaders)) {
282 return $payload;
283 }
284
285 $compression_method = $this->compressionMethodManager->get($completeHeaders['zip']);
286
287 return $compression_method->uncompress($payload);
288 }
289
290 private function checkCompleteHeader(array $completeHeaders): void
291 {
292 foreach (['enc', 'alg'] as $key) {
293 if (! isset($completeHeaders[$key])) {
294 throw new InvalidArgumentException(sprintf("Parameter '%s' is missing.", $key));
295 }
296 }
297 }
298
299 private function getKeyEncryptionAlgorithm(array $completeHeaders): KeyEncryptionAlgorithm
300 {
301 $key_encryption_algorithm = $this->keyEncryptionAlgorithmManager->get($completeHeaders['alg']);
302 if (! $key_encryption_algorithm instanceof KeyEncryptionAlgorithm) {
303 throw new InvalidArgumentException(sprintf(
304 'The key encryption algorithm "%s" is not supported or does not implement KeyEncryptionAlgorithm interface.',
305 $completeHeaders['alg']
306 ));
307 }
308
309 return $key_encryption_algorithm;
310 }
311
312 private function getContentEncryptionAlgorithm(array $completeHeader): ContentEncryptionAlgorithm
313 {
314 $content_encryption_algorithm = $this->contentEncryptionAlgorithmManager->get($completeHeader['enc']);
315 if (! $content_encryption_algorithm instanceof ContentEncryptionAlgorithm) {
316 throw new InvalidArgumentException(sprintf(
317 'The key encryption algorithm "%s" is not supported or does not implement the ContentEncryption interface.',
318 $completeHeader['enc']
319 ));
320 }
321
322 return $content_encryption_algorithm;
323 }
324 }