Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Encryption/JWEBuilder.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\AlgorithmManager;
9 use Jose\Component\Core\JWK;
10 use Jose\Component\Core\Util\Base64UrlSafe;
11 use Jose\Component\Core\Util\JsonConverter;
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\CompressionMethod;
21 use Jose\Component\Encryption\Compression\CompressionMethodManager;
22 use LogicException;
23 use RuntimeException;
24 use function array_key_exists;
25 use function count;
26 use function is_string;
27
28 class JWEBuilder
29 {
30 protected ?JWK $senderKey = null;
31
32 protected ?string $payload = null;
33
34 protected ?string $aad = null;
35
36 protected array $recipients = [];
37
38 protected array $sharedProtectedHeader = [];
39
40 protected array $sharedHeader = [];
41
42 private ?CompressionMethod $compressionMethod = null;
43
44 private ?string $keyManagementMode = null;
45
46 private ?ContentEncryptionAlgorithm $contentEncryptionAlgorithm = null;
47
48 private readonly AlgorithmManager $keyEncryptionAlgorithmManager;
49
50 private readonly AlgorithmManager $contentEncryptionAlgorithmManager;
51
52 public function __construct(
53 AlgorithmManager $algorithmManager,
54 null|AlgorithmManager $contentEncryptionAlgorithmManager = null,
55 private readonly null|CompressionMethodManager $compressionManager = null
56 ) {
57 if ($compressionManager !== null) {
58 trigger_deprecation(
59 'web-token/jwt-library',
60 '3.3.0',
61 'The parameter "$compressionManager" is deprecated and will be removed in 4.0.0. Compression is not recommended for JWE. Please set "null" instead.'
62 );
63 }
64 if ($contentEncryptionAlgorithmManager !== null) {
65 trigger_deprecation(
66 'web-token/jwt-library',
67 '3.3.0',
68 '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.'
69 );
70 $this->keyEncryptionAlgorithmManager = $algorithmManager;
71 $this->contentEncryptionAlgorithmManager = $contentEncryptionAlgorithmManager;
72 } else {
73 $keyEncryptionAlgorithms = [];
74 $contentEncryptionAlgorithms = [];
75 foreach ($algorithmManager->all() as $algorithm) {
76 if ($algorithm instanceof KeyEncryptionAlgorithm) {
77 $keyEncryptionAlgorithms[] = $algorithm;
78 }
79 if ($algorithm instanceof ContentEncryptionAlgorithm) {
80 $contentEncryptionAlgorithms[] = $algorithm;
81 }
82 }
83 $this->keyEncryptionAlgorithmManager = new AlgorithmManager($keyEncryptionAlgorithms);
84 $this->contentEncryptionAlgorithmManager = new AlgorithmManager($contentEncryptionAlgorithms);
85 }
86 }
87
88 /**
89 * Reset the current data.
90 */
91 public function create(): self
92 {
93 $this->senderKey = null;
94 $this->payload = null;
95 $this->aad = null;
96 $this->recipients = [];
97 $this->sharedProtectedHeader = [];
98 $this->sharedHeader = [];
99 $this->compressionMethod = null;
100 $this->keyManagementMode = null;
101
102 return $this;
103 }
104
105 /**
106 * Returns the key encryption algorithm manager.
107 */
108 public function getKeyEncryptionAlgorithmManager(): AlgorithmManager
109 {
110 return $this->keyEncryptionAlgorithmManager;
111 }
112
113 /**
114 * Returns the content encryption algorithm manager.
115 */
116 public function getContentEncryptionAlgorithmManager(): AlgorithmManager
117 {
118 return $this->contentEncryptionAlgorithmManager;
119 }
120
121 /**
122 * Returns the compression method manager.
123 * @deprecated This method is deprecated and will be removed in v4.0. Compression is not recommended for JWE.
124 */
125 public function getCompressionMethodManager(): null|CompressionMethodManager
126 {
127 return $this->compressionManager;
128 }
129
130 /**
131 * Set the payload of the JWE to build.
132 */
133 public function withPayload(string $payload): self
134 {
135 $clone = clone $this;
136 $clone->payload = $payload;
137
138 return $clone;
139 }
140
141 /**
142 * Set the Additional Authenticated Data of the JWE to build.
143 */
144 public function withAAD(?string $aad): self
145 {
146 $clone = clone $this;
147 $clone->aad = $aad;
148
149 return $clone;
150 }
151
152 /**
153 * Set the shared protected header of the JWE to build.
154 */
155 public function withSharedProtectedHeader(array $sharedProtectedHeader): self
156 {
157 $this->checkDuplicatedHeaderParameters($sharedProtectedHeader, $this->sharedHeader);
158 foreach ($this->recipients as $recipient) {
159 $this->checkDuplicatedHeaderParameters($sharedProtectedHeader, $recipient->getHeader());
160 }
161 $clone = clone $this;
162 $clone->sharedProtectedHeader = $sharedProtectedHeader;
163
164 return $clone;
165 }
166
167 /**
168 * Set the shared header of the JWE to build.
169 */
170 public function withSharedHeader(array $sharedHeader): self
171 {
172 $this->checkDuplicatedHeaderParameters($this->sharedProtectedHeader, $sharedHeader);
173 foreach ($this->recipients as $recipient) {
174 $this->checkDuplicatedHeaderParameters($sharedHeader, $recipient->getHeader());
175 }
176 $clone = clone $this;
177 $clone->sharedHeader = $sharedHeader;
178
179 return $clone;
180 }
181
182 /**
183 * Adds a recipient to the JWE to build.
184 */
185 public function addRecipient(JWK $recipientKey, array $recipientHeader = []): self
186 {
187 $this->checkDuplicatedHeaderParameters($this->sharedProtectedHeader, $recipientHeader);
188 $this->checkDuplicatedHeaderParameters($this->sharedHeader, $recipientHeader);
189 $clone = clone $this;
190 $completeHeader = array_merge($clone->sharedHeader, $recipientHeader, $clone->sharedProtectedHeader);
191 $clone->checkAndSetContentEncryptionAlgorithm($completeHeader);
192 $keyEncryptionAlgorithm = $clone->getKeyEncryptionAlgorithm($completeHeader);
193 if ($clone->keyManagementMode === null) {
194 $clone->keyManagementMode = $keyEncryptionAlgorithm->getKeyManagementMode();
195 } else {
196 if (! $clone->areKeyManagementModesCompatible(
197 $clone->keyManagementMode,
198 $keyEncryptionAlgorithm->getKeyManagementMode()
199 )) {
200 throw new InvalidArgumentException('Foreign key management mode forbidden.');
201 }
202 }
203
204 $compressionMethod = $clone->getCompressionMethod($completeHeader);
205 if ($compressionMethod !== null) {
206 if ($clone->compressionMethod === null) {
207 $clone->compressionMethod = $compressionMethod;
208 } elseif ($clone->compressionMethod->name() !== $compressionMethod->name()) {
209 throw new InvalidArgumentException('Incompatible compression method.');
210 }
211 }
212 if ($compressionMethod === null && $clone->compressionMethod !== null) {
213 throw new InvalidArgumentException('Inconsistent compression method.');
214 }
215 $clone->checkKey($keyEncryptionAlgorithm, $recipientKey);
216 $clone->recipients[] = [
217 'key' => $recipientKey,
218 'header' => $recipientHeader,
219 'key_encryption_algorithm' => $keyEncryptionAlgorithm,
220 ];
221
222 return $clone;
223 }
224
225 //TODO: Verify if the key is compatible with the key encryption algorithm like is done to the ECDH-ES
226 /**
227 * Set the sender JWK to be used instead of the internal generated JWK
228 */
229 public function withSenderKey(JWK $senderKey): self
230 {
231 $clone = clone $this;
232 $completeHeader = array_merge($clone->sharedHeader, $clone->sharedProtectedHeader);
233 $keyEncryptionAlgorithm = $clone->getKeyEncryptionAlgorithm($completeHeader);
234 if ($clone->keyManagementMode === null) {
235 $clone->keyManagementMode = $keyEncryptionAlgorithm->getKeyManagementMode();
236 } else {
237 if (! $clone->areKeyManagementModesCompatible(
238 $clone->keyManagementMode,
239 $keyEncryptionAlgorithm->getKeyManagementMode()
240 )) {
241 throw new InvalidArgumentException('Foreign key management mode forbidden.');
242 }
243 }
244 $clone->checkKey($keyEncryptionAlgorithm, $senderKey);
245 $clone->senderKey = $senderKey;
246
247 return $clone;
248 }
249
250 /**
251 * Builds the JWE.
252 */
253 public function build(): JWE
254 {
255 if ($this->payload === null) {
256 throw new LogicException('Payload not set.');
257 }
258 if (count($this->recipients) === 0) {
259 throw new LogicException('No recipient.');
260 }
261
262 $additionalHeader = [];
263 $cek = $this->determineCEK($additionalHeader);
264
265 $recipients = [];
266 foreach ($this->recipients as $recipient) {
267 $recipient = $this->processRecipient($recipient, $cek, $additionalHeader);
268 $recipients[] = $recipient;
269 }
270
271 if ((is_countable($additionalHeader) ? count($additionalHeader) : 0) !== 0 && count($this->recipients) === 1) {
272 $sharedProtectedHeader = array_merge($additionalHeader, $this->sharedProtectedHeader);
273 } else {
274 $sharedProtectedHeader = $this->sharedProtectedHeader;
275 }
276 $encodedSharedProtectedHeader = count($sharedProtectedHeader) === 0 ? '' : Base64UrlSafe::encodeUnpadded(
277 JsonConverter::encode($sharedProtectedHeader)
278 );
279
280 [$ciphertext, $iv, $tag] = $this->encryptJWE($cek, $encodedSharedProtectedHeader);
281
282 return new JWE(
283 $ciphertext,
284 $iv,
285 $tag,
286 $this->aad,
287 $this->sharedHeader,
288 $sharedProtectedHeader,
289 $encodedSharedProtectedHeader,
290 $recipients
291 );
292 }
293
294 private function checkAndSetContentEncryptionAlgorithm(array $completeHeader): void
295 {
296 $contentEncryptionAlgorithm = $this->getContentEncryptionAlgorithm($completeHeader);
297 if ($this->contentEncryptionAlgorithm === null) {
298 $this->contentEncryptionAlgorithm = $contentEncryptionAlgorithm;
299 } elseif ($contentEncryptionAlgorithm->name() !== $this->contentEncryptionAlgorithm->name()) {
300 throw new InvalidArgumentException('Inconsistent content encryption algorithm');
301 }
302 }
303
304 private function processRecipient(array $recipient, string $cek, array &$additionalHeader): Recipient
305 {
306 $completeHeader = array_merge($this->sharedHeader, $recipient['header'], $this->sharedProtectedHeader);
307 $keyEncryptionAlgorithm = $recipient['key_encryption_algorithm'];
308 if (! $keyEncryptionAlgorithm instanceof KeyEncryptionAlgorithm) {
309 throw new InvalidArgumentException('The key encryption algorithm is not valid');
310 }
311 $encryptedContentEncryptionKey = $this->getEncryptedKey(
312 $completeHeader,
313 $cek,
314 $keyEncryptionAlgorithm,
315 $additionalHeader,
316 $recipient['key'],
317 $recipient['sender_key'] ?? $this->senderKey ?? null
318 );
319 $recipientHeader = $recipient['header'];
320 if ((is_countable($additionalHeader) ? count($additionalHeader) : 0) !== 0 && count($this->recipients) !== 1) {
321 $recipientHeader = array_merge($recipientHeader, $additionalHeader);
322 $additionalHeader = [];
323 }
324
325 return new Recipient($recipientHeader, $encryptedContentEncryptionKey);
326 }
327
328 private function encryptJWE(string $cek, string $encodedSharedProtectedHeader): array
329 {
330 if (! $this->contentEncryptionAlgorithm instanceof ContentEncryptionAlgorithm) {
331 throw new InvalidArgumentException('The content encryption algorithm is not valid');
332 }
333 $iv_size = $this->contentEncryptionAlgorithm->getIVSize();
334 $iv = $this->createIV($iv_size);
335 $payload = $this->preparePayload();
336 $tag = null;
337 $ciphertext = $this->contentEncryptionAlgorithm->encryptContent(
338 $payload ?? '',
339 $cek,
340 $iv,
341 $this->aad,
342 $encodedSharedProtectedHeader,
343 $tag
344 );
345
346 return [$ciphertext, $iv, $tag];
347 }
348
349 private function preparePayload(): ?string
350 {
351 $prepared = $this->payload;
352 if ($this->compressionMethod === null) {
353 return $prepared;
354 }
355
356 return $this->compressionMethod->compress($prepared ?? '');
357 }
358
359 private function getEncryptedKey(
360 array $completeHeader,
361 string $cek,
362 KeyEncryptionAlgorithm $keyEncryptionAlgorithm,
363 array &$additionalHeader,
364 JWK $recipientKey,
365 ?JWK $senderKey
366 ): ?string {
367 if ($keyEncryptionAlgorithm instanceof KeyEncryption) {
368 return $this->getEncryptedKeyFromKeyEncryptionAlgorithm(
369 $completeHeader,
370 $cek,
371 $keyEncryptionAlgorithm,
372 $recipientKey,
373 $additionalHeader
374 );
375 }
376 if ($keyEncryptionAlgorithm instanceof KeyWrapping) {
377 return $this->getEncryptedKeyFromKeyWrappingAlgorithm(
378 $completeHeader,
379 $cek,
380 $keyEncryptionAlgorithm,
381 $recipientKey,
382 $additionalHeader
383 );
384 }
385 if ($keyEncryptionAlgorithm instanceof KeyAgreementWithKeyWrapping) {
386 return $this->getEncryptedKeyFromKeyAgreementAndKeyWrappingAlgorithm(
387 $completeHeader,
388 $cek,
389 $keyEncryptionAlgorithm,
390 $additionalHeader,
391 $recipientKey,
392 $senderKey
393 );
394 }
395 if ($keyEncryptionAlgorithm instanceof KeyAgreement) {
396 return null;
397 }
398 if ($keyEncryptionAlgorithm instanceof DirectEncryption) {
399 return null;
400 }
401
402 throw new InvalidArgumentException('Unsupported key encryption algorithm.');
403 }
404
405 private function getEncryptedKeyFromKeyAgreementAndKeyWrappingAlgorithm(
406 array $completeHeader,
407 string $cek,
408 KeyAgreementWithKeyWrapping $keyEncryptionAlgorithm,
409 array &$additionalHeader,
410 JWK $recipientKey,
411 ?JWK $senderKey
412 ): string {
413 if ($this->contentEncryptionAlgorithm === null) {
414 throw new InvalidArgumentException('Invalid content encryption algorithm');
415 }
416
417 return $keyEncryptionAlgorithm->wrapAgreementKey(
418 $recipientKey,
419 $senderKey,
420 $cek,
421 $this->contentEncryptionAlgorithm->getCEKSize(),
422 $completeHeader,
423 $additionalHeader
424 );
425 }
426
427 private function getEncryptedKeyFromKeyEncryptionAlgorithm(
428 array $completeHeader,
429 string $cek,
430 KeyEncryption $keyEncryptionAlgorithm,
431 JWK $recipientKey,
432 array &$additionalHeader
433 ): string {
434 return $keyEncryptionAlgorithm->encryptKey($recipientKey, $cek, $completeHeader, $additionalHeader);
435 }
436
437 private function getEncryptedKeyFromKeyWrappingAlgorithm(
438 array $completeHeader,
439 string $cek,
440 KeyWrapping $keyEncryptionAlgorithm,
441 JWK $recipientKey,
442 array &$additionalHeader
443 ): string {
444 return $keyEncryptionAlgorithm->wrapKey($recipientKey, $cek, $completeHeader, $additionalHeader);
445 }
446
447 private function checkKey(KeyEncryptionAlgorithm $keyEncryptionAlgorithm, JWK $recipientKey): void
448 {
449 if ($this->contentEncryptionAlgorithm === null) {
450 throw new InvalidArgumentException('Invalid content encryption algorithm');
451 }
452
453 KeyChecker::checkKeyUsage($recipientKey, 'encryption');
454 if ($keyEncryptionAlgorithm->name() !== 'dir') {
455 KeyChecker::checkKeyAlgorithm($recipientKey, $keyEncryptionAlgorithm->name());
456 } else {
457 KeyChecker::checkKeyAlgorithm($recipientKey, $this->contentEncryptionAlgorithm->name());
458 }
459 }
460
461 private function determineCEK(array &$additionalHeader): string
462 {
463 if ($this->contentEncryptionAlgorithm === null) {
464 throw new InvalidArgumentException('Invalid content encryption algorithm');
465 }
466
467 switch ($this->keyManagementMode) {
468 case KeyEncryption::MODE_ENCRYPT:
469 case KeyEncryption::MODE_WRAP:
470 return $this->createCEK($this->contentEncryptionAlgorithm->getCEKSize());
471
472 case KeyEncryption::MODE_AGREEMENT:
473 if (count($this->recipients) !== 1) {
474 throw new LogicException(
475 'Unable to encrypt for multiple recipients using key agreement algorithms.'
476 );
477 }
478 $recipientKey = $this->recipients[0]['key'];
479 $senderKey = $this->recipients[0]['sender_key'] ?? null;
480 $algorithm = $this->recipients[0]['key_encryption_algorithm'];
481 if (! $algorithm instanceof KeyAgreement) {
482 throw new InvalidArgumentException('Invalid content encryption algorithm');
483 }
484 $completeHeader = array_merge(
485 $this->sharedHeader,
486 $this->recipients[0]['header'],
487 $this->sharedProtectedHeader
488 );
489
490 return $algorithm->getAgreementKey(
491 $this->contentEncryptionAlgorithm->getCEKSize(),
492 $this->contentEncryptionAlgorithm->name(),
493 $recipientKey,
494 $senderKey,
495 $completeHeader,
496 $additionalHeader
497 );
498
499 case KeyEncryption::MODE_DIRECT:
500 if (count($this->recipients) !== 1) {
501 throw new LogicException(
502 'Unable to encrypt for multiple recipients using key agreement algorithms.'
503 );
504 }
505 /** @var JWK $key */
506 $key = $this->recipients[0]['key'];
507 if ($key->get('kty') !== 'oct') {
508 throw new RuntimeException('Wrong key type.');
509 }
510 $k = $key->get('k');
511 if (! is_string($k)) {
512 throw new RuntimeException('Invalid key.');
513 }
514
515 return Base64UrlSafe::decodeNoPadding($k);
516
517 default:
518 throw new InvalidArgumentException(sprintf(
519 'Unsupported key management mode "%s".',
520 $this->keyManagementMode
521 ));
522 }
523 }
524
525 private function getCompressionMethod(array $completeHeader): ?CompressionMethod
526 {
527 if ($this->compressionManager === null || ! array_key_exists('zip', $completeHeader)) {
528 return null;
529 }
530
531 return $this->compressionManager->get($completeHeader['zip']);
532 }
533
534 private function areKeyManagementModesCompatible(string $current, string $new): bool
535 {
536 $agree = KeyEncryptionAlgorithm::MODE_AGREEMENT;
537 $dir = KeyEncryptionAlgorithm::MODE_DIRECT;
538 $enc = KeyEncryptionAlgorithm::MODE_ENCRYPT;
539 $wrap = KeyEncryptionAlgorithm::MODE_WRAP;
540 $supportedKeyManagementModeCombinations = [
541 $enc . $enc => true,
542 $enc . $wrap => true,
543 $wrap . $enc => true,
544 $wrap . $wrap => true,
545 $agree . $agree => false,
546 $agree . $dir => false,
547 $agree . $enc => false,
548 $agree . $wrap => false,
549 $dir . $agree => false,
550 $dir . $dir => false,
551 $dir . $enc => false,
552 $dir . $wrap => false,
553 $enc . $agree => false,
554 $enc . $dir => false,
555 $wrap . $agree => false,
556 $wrap . $dir => false,
557 ];
558
559 if (array_key_exists($current . $new, $supportedKeyManagementModeCombinations)) {
560 return $supportedKeyManagementModeCombinations[$current . $new];
561 }
562
563 return false;
564 }
565
566 private function createCEK(int $size): string
567 {
568 return random_bytes($size / 8);
569 }
570
571 private function createIV(int $size): string
572 {
573 return random_bytes($size / 8);
574 }
575
576 private function getKeyEncryptionAlgorithm(array $completeHeader): KeyEncryptionAlgorithm
577 {
578 if (! isset($completeHeader['alg'])) {
579 throw new InvalidArgumentException('Parameter "alg" is missing.');
580 }
581 $keyEncryptionAlgorithm = $this->keyEncryptionAlgorithmManager->get($completeHeader['alg']);
582 if (! $keyEncryptionAlgorithm instanceof KeyEncryptionAlgorithm) {
583 throw new InvalidArgumentException(sprintf(
584 'The key encryption algorithm "%s" is not supported or not a key encryption algorithm instance.',
585 $completeHeader['alg']
586 ));
587 }
588
589 return $keyEncryptionAlgorithm;
590 }
591
592 private function getContentEncryptionAlgorithm(array $completeHeader): ContentEncryptionAlgorithm
593 {
594 if (! isset($completeHeader['enc'])) {
595 throw new InvalidArgumentException('Parameter "enc" is missing.');
596 }
597 $contentEncryptionAlgorithm = $this->contentEncryptionAlgorithmManager->get($completeHeader['enc']);
598 if (! $contentEncryptionAlgorithm instanceof ContentEncryptionAlgorithm) {
599 throw new InvalidArgumentException(sprintf(
600 'The content encryption algorithm "%s" is not supported or not a content encryption algorithm instance.',
601 $completeHeader['enc']
602 ));
603 }
604
605 return $contentEncryptionAlgorithm;
606 }
607
608 private function checkDuplicatedHeaderParameters(array $header1, array $header2): void
609 {
610 $inter = array_intersect_key($header1, $header2);
611 if (count($inter) !== 0) {
612 throw new InvalidArgumentException(sprintf(
613 'The header contains duplicated entries: %s.',
614 implode(', ', array_keys($inter))
615 ));
616 }
617 }
618 }