Debian Codegraph @

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

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Encryption;
6
7 use Jose\Component\Checker\HeaderCheckerManager;
8 use Jose\Component\Core\JWK;
9 use Jose\Component\Core\JWKSet;
10 use Jose\Component\Encryption\Serializer\JWESerializerManager;
11 use RuntimeException;
12 use Throwable;
13
14 /**
15 * @see \Jose\Tests\Component\Encryption\JWELoaderTest
16 */
17 class JWELoader
18 {
19 public function __construct(
20 private readonly JWESerializerManager $serializerManager,
21 private readonly JWEDecrypter $jweDecrypter,
22 private readonly ?HeaderCheckerManager $headerCheckerManager
23 ) {
24 }
25
26 /**
27 * Returns the JWE Decrypter object.
28 */
29 public function getJweDecrypter(): JWEDecrypter
30 {
31 return $this->jweDecrypter;
32 }
33
34 /**
35 * Returns the header checker manager if set.
36 */
37 public function getHeaderCheckerManager(): ?HeaderCheckerManager
38 {
39 return $this->headerCheckerManager;
40 }
41
42 /**
43 * Returns the serializer manager.
44 */
45 public function getSerializerManager(): JWESerializerManager
46 {
47 return $this->serializerManager;
48 }
49
50 /**
51 * This method will try to load and decrypt the given token using a JWK. If succeeded, the methods will populate the
52 * $recipient variable and returns the JWE.
53 */
54 public function loadAndDecryptWithKey(string $token, JWK $key, ?int &$recipient): JWE
55 {
56 $keyset = new JWKSet([$key]);
57
58 return $this->loadAndDecryptWithKeySet($token, $keyset, $recipient);
59 }
60
61 /**
62 * This method will try to load and decrypt the given token using a JWKSet. If succeeded, the methods will populate
63 * the $recipient variable and returns the JWE.
64 */
65 public function loadAndDecryptWithKeySet(string $token, JWKSet $keyset, ?int &$recipient): JWE
66 {
67 try {
68 $jwe = $this->serializerManager->unserialize($token);
69 $nbRecipients = $jwe->countRecipients();
70 for ($i = 0; $i < $nbRecipients; ++$i) {
71 if ($this->processRecipient($jwe, $keyset, $i)) {
72 $recipient = $i;
73
74 return $jwe;
75 }
76 }
77 } catch (Throwable) {
78 // Nothing to do. Exception thrown just after
79 }
80
81 throw new RuntimeException('Unable to load and decrypt the token.');
82 }
83
84 private function processRecipient(JWE &$jwe, JWKSet $keyset, int $recipient): bool
85 {
86 try {
87 if ($this->headerCheckerManager !== null) {
88 $this->headerCheckerManager->check($jwe, $recipient);
89 }
90
91 return $this->jweDecrypter->decryptUsingKeySet($jwe, $keyset, $recipient);
92 } catch (Throwable) {
93 return false;
94 }
95 }
96 }