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