-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathJWEDecrypter.php
289 lines (257 loc) · 10.2 KB
/
JWEDecrypter.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
<?php
declare(strict_types=1);
namespace Jose\Component\Encryption;
use function array_key_exists;
use InvalidArgumentException;
use function is_string;
use Jose\Component\Core\Algorithm;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Core\JWKSet;
use Jose\Component\Core\Util\KeyChecker;
use Jose\Component\Encryption\Algorithm\ContentEncryptionAlgorithm;
use Jose\Component\Encryption\Algorithm\KeyEncryption\DirectEncryption;
use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyAgreement;
use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyAgreementWithKeyWrapping;
use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyEncryption;
use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyWrapping;
use Jose\Component\Encryption\Algorithm\KeyEncryptionAlgorithm;
use Jose\Component\Encryption\Compression\CompressionMethodManager;
use Throwable;
class JWEDecrypter
{
public function __construct(
private readonly AlgorithmManager $keyEncryptionAlgorithmManager,
private readonly AlgorithmManager $contentEncryptionAlgorithmManager,
private readonly CompressionMethodManager $compressionMethodManager
) {
}
/**
* Returns the key encryption algorithm manager.
*/
public function getKeyEncryptionAlgorithmManager(): AlgorithmManager
{
return $this->keyEncryptionAlgorithmManager;
}
/**
* Returns the content encryption algorithm manager.
*/
public function getContentEncryptionAlgorithmManager(): AlgorithmManager
{
return $this->contentEncryptionAlgorithmManager;
}
/**
* Returns the compression method manager.
*/
public function getCompressionMethodManager(): CompressionMethodManager
{
return $this->compressionMethodManager;
}
/**
* This method will try to decrypt the given JWE and recipient using a JWK.
*
* @param JWE $jwe A JWE object to decrypt
* @param JWK $jwk The key used to decrypt the input
* @param int $recipient The recipient used to decrypt the token
*/
public function decryptUsingKey(JWE &$jwe, JWK $jwk, int $recipient, ?JWK $senderKey = null): bool
{
$jwkset = new JWKSet([$jwk]);
return $this->decryptUsingKeySet($jwe, $jwkset, $recipient, $senderKey);
}
/**
* This method will try to decrypt the given JWE and recipient using a JWKSet.
*
* @param JWE $jwe A JWE object to decrypt
* @param JWKSet $jwkset The key set used to decrypt the input
* @param JWK $jwk The key used to decrypt the token in case of success
* @param int $recipient The recipient used to decrypt the token in case of success
*/
public function decryptUsingKeySet(
JWE &$jwe,
JWKSet $jwkset,
int $recipient,
JWK &$jwk = null,
?JWK $senderKey = null
): bool {
if ($jwkset->count() === 0) {
throw new InvalidArgumentException('No key in the key set.');
}
if ($jwe->getPayload() !== null) {
return true;
}
if ($jwe->countRecipients() === 0) {
throw new InvalidArgumentException('The JWE does not contain any recipient.');
}
$plaintext = $this->decryptRecipientKey($jwe, $jwkset, $recipient, $jwk, $senderKey);
if ($plaintext !== null) {
$jwe = $jwe->withPayload($plaintext);
return true;
}
return false;
}
private function decryptRecipientKey(
JWE $jwe,
JWKSet $jwkset,
int $i,
JWK &$successJwk = null,
?JWK $senderKey = null
): ?string {
$recipient = $jwe->getRecipient($i);
$completeHeader = array_merge(
$jwe->getSharedProtectedHeader(),
$jwe->getSharedHeader(),
$recipient->getHeader()
);
$this->checkCompleteHeader($completeHeader);
$key_encryption_algorithm = $this->getKeyEncryptionAlgorithm($completeHeader);
$content_encryption_algorithm = $this->getContentEncryptionAlgorithm($completeHeader);
$this->checkIvSize($jwe->getIV(), $content_encryption_algorithm->getIVSize());
foreach ($jwkset as $recipientKey) {
try {
KeyChecker::checkKeyUsage($recipientKey, 'decryption');
if ($key_encryption_algorithm->name() !== 'dir') {
KeyChecker::checkKeyAlgorithm($recipientKey, $key_encryption_algorithm->name());
} else {
KeyChecker::checkKeyAlgorithm($recipientKey, $content_encryption_algorithm->name());
}
$cek = $this->decryptCEK(
$key_encryption_algorithm,
$content_encryption_algorithm,
$recipientKey,
$senderKey,
$recipient,
$completeHeader
);
$this->checkCekSize($cek, $key_encryption_algorithm, $content_encryption_algorithm);
$payload = $this->decryptPayload($jwe, $cek, $content_encryption_algorithm, $completeHeader);
$successJwk = $recipientKey;
return $payload;
} catch (Throwable) {
//We do nothing, we continue with other keys
continue;
}
}
return null;
}
private function checkCekSize(
string $cek,
KeyEncryptionAlgorithm $keyEncryptionAlgorithm,
ContentEncryptionAlgorithm $algorithm
): void {
if ($keyEncryptionAlgorithm instanceof DirectEncryption || $keyEncryptionAlgorithm instanceof KeyAgreement) {
return;
}
if (mb_strlen($cek, '8bit') * 8 !== $algorithm->getCEKSize()) {
throw new InvalidArgumentException('Invalid CEK size');
}
}
private function checkIvSize(?string $iv, int $requiredIvSize): void
{
if ($iv === null && $requiredIvSize !== 0) {
throw new InvalidArgumentException('Invalid IV size');
}
if (is_string($iv) && mb_strlen($iv, '8bit') !== $requiredIvSize / 8) {
throw new InvalidArgumentException('Invalid IV size');
}
}
private function decryptCEK(
Algorithm $key_encryption_algorithm,
ContentEncryptionAlgorithm $content_encryption_algorithm,
JWK $recipientKey,
?JWK $senderKey,
Recipient $recipient,
array $completeHeader
): string {
if ($key_encryption_algorithm instanceof DirectEncryption) {
return $key_encryption_algorithm->getCEK($recipientKey);
}
if ($key_encryption_algorithm instanceof KeyAgreement) {
return $key_encryption_algorithm->getAgreementKey(
$content_encryption_algorithm->getCEKSize(),
$content_encryption_algorithm->name(),
$recipientKey,
$senderKey,
$completeHeader
);
}
if ($key_encryption_algorithm instanceof KeyAgreementWithKeyWrapping) {
return $key_encryption_algorithm->unwrapAgreementKey(
$recipientKey,
$senderKey,
$recipient->getEncryptedKey() ?? '',
$content_encryption_algorithm->getCEKSize(),
$completeHeader
);
}
if ($key_encryption_algorithm instanceof KeyEncryption) {
return $key_encryption_algorithm->decryptKey(
$recipientKey,
$recipient->getEncryptedKey() ?? '',
$completeHeader
);
}
if ($key_encryption_algorithm instanceof KeyWrapping) {
return $key_encryption_algorithm->unwrapKey(
$recipientKey,
$recipient->getEncryptedKey() ?? '',
$completeHeader
);
}
throw new InvalidArgumentException('Unsupported CEK generation');
}
private function decryptPayload(
JWE $jwe,
string $cek,
ContentEncryptionAlgorithm $content_encryption_algorithm,
array $completeHeader
): string {
$payload = $content_encryption_algorithm->decryptContent(
$jwe->getCiphertext() ?? '',
$cek,
$jwe->getIV() ?? '',
$jwe->getAAD(),
$jwe->getEncodedSharedProtectedHeader(),
$jwe->getTag() ?? ''
);
return $this->decompressIfNeeded($payload, $completeHeader);
}
private function decompressIfNeeded(string $payload, array $completeHeaders): string
{
if (array_key_exists('zip', $completeHeaders)) {
$compression_method = $this->compressionMethodManager->get($completeHeaders['zip']);
$payload = $compression_method->uncompress($payload);
}
return $payload;
}
private function checkCompleteHeader(array $completeHeaders): void
{
foreach (['enc', 'alg'] as $key) {
if (! isset($completeHeaders[$key])) {
throw new InvalidArgumentException(sprintf("Parameter '%s' is missing.", $key));
}
}
}
private function getKeyEncryptionAlgorithm(array $completeHeaders): KeyEncryptionAlgorithm
{
$key_encryption_algorithm = $this->keyEncryptionAlgorithmManager->get($completeHeaders['alg']);
if (! $key_encryption_algorithm instanceof KeyEncryptionAlgorithm) {
throw new InvalidArgumentException(sprintf(
'The key encryption algorithm "%s" is not supported or does not implement KeyEncryptionAlgorithm interface.',
$completeHeaders['alg']
));
}
return $key_encryption_algorithm;
}
private function getContentEncryptionAlgorithm(array $completeHeader): ContentEncryptionAlgorithm
{
$content_encryption_algorithm = $this->contentEncryptionAlgorithmManager->get($completeHeader['enc']);
if (! $content_encryption_algorithm instanceof ContentEncryptionAlgorithm) {
throw new InvalidArgumentException(sprintf(
'The key encryption algorithm "%s" is not supported or does not implement the ContentEncryption interface.',
$completeHeader['enc']
));
}
return $content_encryption_algorithm;
}
}