-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathJWEBuilder.php
562 lines (494 loc) · 19.7 KB
/
JWEBuilder.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
<?php
declare(strict_types=1);
namespace Jose\Component\Encryption;
use function array_key_exists;
use function count;
use InvalidArgumentException;
use function is_string;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Core\Util\JsonConverter;
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\CompressionMethod;
use Jose\Component\Encryption\Compression\CompressionMethodManager;
use LogicException;
use ParagonIE\ConstantTime\Base64UrlSafe;
use RuntimeException;
class JWEBuilder
{
protected ?string $payload = null;
protected ?string $aad = null;
protected array $recipients = [];
protected array $sharedProtectedHeader = [];
protected array $sharedHeader = [];
private ?CompressionMethod $compressionMethod = null;
private ?string $keyManagementMode = null;
private ?ContentEncryptionAlgorithm $contentEncryptionAlgorithm = null;
public function __construct(
private readonly AlgorithmManager $keyEncryptionAlgorithmManager,
private readonly AlgorithmManager $contentEncryptionAlgorithmManager,
private readonly CompressionMethodManager $compressionManager
) {
}
/**
* Reset the current data.
*/
public function create(): self
{
$this->payload = null;
$this->aad = null;
$this->recipients = [];
$this->sharedProtectedHeader = [];
$this->sharedHeader = [];
$this->compressionMethod = null;
$this->keyManagementMode = null;
return $this;
}
/**
* 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->compressionManager;
}
/**
* Set the payload of the JWE to build.
*/
public function withPayload(string $payload): self
{
if (mb_detect_encoding($payload, 'UTF-8', true) !== 'UTF-8') {
throw new InvalidArgumentException('The payload must be encoded in UTF-8');
}
$clone = clone $this;
$clone->payload = $payload;
return $clone;
}
/**
* Set the Additional Authenticated Data of the JWE to build.
*/
public function withAAD(?string $aad): self
{
$clone = clone $this;
$clone->aad = $aad;
return $clone;
}
/**
* Set the shared protected header of the JWE to build.
*/
public function withSharedProtectedHeader(array $sharedProtectedHeader): self
{
$this->checkDuplicatedHeaderParameters($sharedProtectedHeader, $this->sharedHeader);
foreach ($this->recipients as $recipient) {
$this->checkDuplicatedHeaderParameters($sharedProtectedHeader, $recipient->getHeader());
}
$clone = clone $this;
$clone->sharedProtectedHeader = $sharedProtectedHeader;
return $clone;
}
/**
* Set the shared header of the JWE to build.
*/
public function withSharedHeader(array $sharedHeader): self
{
$this->checkDuplicatedHeaderParameters($this->sharedProtectedHeader, $sharedHeader);
foreach ($this->recipients as $recipient) {
$this->checkDuplicatedHeaderParameters($sharedHeader, $recipient->getHeader());
}
$clone = clone $this;
$clone->sharedHeader = $sharedHeader;
return $clone;
}
/**
* Adds a recipient to the JWE to build.
*/
public function addRecipient(JWK $recipientKey, array $recipientHeader = []): self
{
$this->checkDuplicatedHeaderParameters($this->sharedProtectedHeader, $recipientHeader);
$this->checkDuplicatedHeaderParameters($this->sharedHeader, $recipientHeader);
$clone = clone $this;
$completeHeader = array_merge($clone->sharedHeader, $recipientHeader, $clone->sharedProtectedHeader);
$clone->checkAndSetContentEncryptionAlgorithm($completeHeader);
$keyEncryptionAlgorithm = $clone->getKeyEncryptionAlgorithm($completeHeader);
if ($clone->keyManagementMode === null) {
$clone->keyManagementMode = $keyEncryptionAlgorithm->getKeyManagementMode();
} else {
if (! $clone->areKeyManagementModesCompatible(
$clone->keyManagementMode,
$keyEncryptionAlgorithm->getKeyManagementMode()
)) {
throw new InvalidArgumentException('Foreign key management mode forbidden.');
}
}
$compressionMethod = $clone->getCompressionMethod($completeHeader);
if ($compressionMethod !== null) {
if ($clone->compressionMethod === null) {
$clone->compressionMethod = $compressionMethod;
} elseif ($clone->compressionMethod->name() !== $compressionMethod->name()) {
throw new InvalidArgumentException('Incompatible compression method.');
}
}
if ($compressionMethod === null && $clone->compressionMethod !== null) {
throw new InvalidArgumentException('Inconsistent compression method.');
}
$clone->checkKey($keyEncryptionAlgorithm, $recipientKey);
$clone->recipients[] = [
'key' => $recipientKey,
'header' => $recipientHeader,
'key_encryption_algorithm' => $keyEncryptionAlgorithm,
];
return $clone;
}
/**
* Builds the JWE.
*/
public function build(): JWE
{
if ($this->payload === null) {
throw new LogicException('Payload not set.');
}
if (count($this->recipients) === 0) {
throw new LogicException('No recipient.');
}
$additionalHeader = [];
$cek = $this->determineCEK($additionalHeader);
$recipients = [];
foreach ($this->recipients as $recipient) {
$recipient = $this->processRecipient($recipient, $cek, $additionalHeader);
$recipients[] = $recipient;
}
if ((is_countable($additionalHeader) ? count($additionalHeader) : 0) !== 0 && count($this->recipients) === 1) {
$sharedProtectedHeader = array_merge($additionalHeader, $this->sharedProtectedHeader);
} else {
$sharedProtectedHeader = $this->sharedProtectedHeader;
}
$encodedSharedProtectedHeader = count($sharedProtectedHeader) === 0 ? '' : Base64UrlSafe::encodeUnpadded(
JsonConverter::encode($sharedProtectedHeader)
);
[$ciphertext, $iv, $tag] = $this->encryptJWE($cek, $encodedSharedProtectedHeader);
return new JWE(
$ciphertext,
$iv,
$tag,
$this->aad,
$this->sharedHeader,
$sharedProtectedHeader,
$encodedSharedProtectedHeader,
$recipients
);
}
private function checkAndSetContentEncryptionAlgorithm(array $completeHeader): void
{
$contentEncryptionAlgorithm = $this->getContentEncryptionAlgorithm($completeHeader);
if ($this->contentEncryptionAlgorithm === null) {
$this->contentEncryptionAlgorithm = $contentEncryptionAlgorithm;
} elseif ($contentEncryptionAlgorithm->name() !== $this->contentEncryptionAlgorithm->name()) {
throw new InvalidArgumentException('Inconsistent content encryption algorithm');
}
}
private function processRecipient(array $recipient, string $cek, array &$additionalHeader): Recipient
{
$completeHeader = array_merge($this->sharedHeader, $recipient['header'], $this->sharedProtectedHeader);
$keyEncryptionAlgorithm = $recipient['key_encryption_algorithm'];
if (! $keyEncryptionAlgorithm instanceof KeyEncryptionAlgorithm) {
throw new InvalidArgumentException('The key encryption algorithm is not valid');
}
$encryptedContentEncryptionKey = $this->getEncryptedKey(
$completeHeader,
$cek,
$keyEncryptionAlgorithm,
$additionalHeader,
$recipient['key'],
$recipient['sender_key'] ?? null
);
$recipientHeader = $recipient['header'];
if ((is_countable($additionalHeader) ? count($additionalHeader) : 0) !== 0 && count($this->recipients) !== 1) {
$recipientHeader = array_merge($recipientHeader, $additionalHeader);
$additionalHeader = [];
}
return new Recipient($recipientHeader, $encryptedContentEncryptionKey);
}
private function encryptJWE(string $cek, string $encodedSharedProtectedHeader): array
{
if (! $this->contentEncryptionAlgorithm instanceof ContentEncryptionAlgorithm) {
throw new InvalidArgumentException('The content encryption algorithm is not valid');
}
$iv_size = $this->contentEncryptionAlgorithm->getIVSize();
$iv = $this->createIV($iv_size);
$payload = $this->preparePayload();
$tag = null;
$ciphertext = $this->contentEncryptionAlgorithm->encryptContent(
$payload ?? '',
$cek,
$iv,
$this->aad,
$encodedSharedProtectedHeader,
$tag
);
return [$ciphertext, $iv, $tag];
}
/**
* @return string
*/
private function preparePayload(): ?string
{
$prepared = $this->payload;
if ($this->compressionMethod === null) {
return $prepared;
}
return $this->compressionMethod->compress($prepared ?? '');
}
private function getEncryptedKey(
array $completeHeader,
string $cek,
KeyEncryptionAlgorithm $keyEncryptionAlgorithm,
array &$additionalHeader,
JWK $recipientKey,
?JWK $senderKey
): ?string {
if ($keyEncryptionAlgorithm instanceof KeyEncryption) {
return $this->getEncryptedKeyFromKeyEncryptionAlgorithm(
$completeHeader,
$cek,
$keyEncryptionAlgorithm,
$recipientKey,
$additionalHeader
);
}
if ($keyEncryptionAlgorithm instanceof KeyWrapping) {
return $this->getEncryptedKeyFromKeyWrappingAlgorithm(
$completeHeader,
$cek,
$keyEncryptionAlgorithm,
$recipientKey,
$additionalHeader
);
}
if ($keyEncryptionAlgorithm instanceof KeyAgreementWithKeyWrapping) {
return $this->getEncryptedKeyFromKeyAgreementAndKeyWrappingAlgorithm(
$completeHeader,
$cek,
$keyEncryptionAlgorithm,
$additionalHeader,
$recipientKey,
$senderKey
);
}
if ($keyEncryptionAlgorithm instanceof KeyAgreement) {
return null;
}
if ($keyEncryptionAlgorithm instanceof DirectEncryption) {
return null;
}
throw new InvalidArgumentException('Unsupported key encryption algorithm.');
}
private function getEncryptedKeyFromKeyAgreementAndKeyWrappingAlgorithm(
array $completeHeader,
string $cek,
KeyAgreementWithKeyWrapping $keyEncryptionAlgorithm,
array &$additionalHeader,
JWK $recipientKey,
?JWK $senderKey
): string {
if ($this->contentEncryptionAlgorithm === null) {
throw new InvalidArgumentException('Invalid content encryption algorithm');
}
return $keyEncryptionAlgorithm->wrapAgreementKey(
$recipientKey,
$senderKey,
$cek,
$this->contentEncryptionAlgorithm->getCEKSize(),
$completeHeader,
$additionalHeader
);
}
private function getEncryptedKeyFromKeyEncryptionAlgorithm(
array $completeHeader,
string $cek,
KeyEncryption $keyEncryptionAlgorithm,
JWK $recipientKey,
array &$additionalHeader
): string {
return $keyEncryptionAlgorithm->encryptKey($recipientKey, $cek, $completeHeader, $additionalHeader);
}
private function getEncryptedKeyFromKeyWrappingAlgorithm(
array $completeHeader,
string $cek,
KeyWrapping $keyEncryptionAlgorithm,
JWK $recipientKey,
array &$additionalHeader
): string {
return $keyEncryptionAlgorithm->wrapKey($recipientKey, $cek, $completeHeader, $additionalHeader);
}
private function checkKey(KeyEncryptionAlgorithm $keyEncryptionAlgorithm, JWK $recipientKey): void
{
if ($this->contentEncryptionAlgorithm === null) {
throw new InvalidArgumentException('Invalid content encryption algorithm');
}
KeyChecker::checkKeyUsage($recipientKey, 'encryption');
if ($keyEncryptionAlgorithm->name() !== 'dir') {
KeyChecker::checkKeyAlgorithm($recipientKey, $keyEncryptionAlgorithm->name());
} else {
KeyChecker::checkKeyAlgorithm($recipientKey, $this->contentEncryptionAlgorithm->name());
}
}
private function determineCEK(array &$additionalHeader): string
{
if ($this->contentEncryptionAlgorithm === null) {
throw new InvalidArgumentException('Invalid content encryption algorithm');
}
switch ($this->keyManagementMode) {
case KeyEncryption::MODE_ENCRYPT:
case KeyEncryption::MODE_WRAP:
return $this->createCEK($this->contentEncryptionAlgorithm->getCEKSize());
case KeyEncryption::MODE_AGREEMENT:
if (count($this->recipients) !== 1) {
throw new LogicException(
'Unable to encrypt for multiple recipients using key agreement algorithms.'
);
}
$recipientKey = $this->recipients[0]['key'];
$senderKey = $this->recipients[0]['sender_key'] ?? null;
$algorithm = $this->recipients[0]['key_encryption_algorithm'];
if (! $algorithm instanceof KeyAgreement) {
throw new InvalidArgumentException('Invalid content encryption algorithm');
}
$completeHeader = array_merge(
$this->sharedHeader,
$this->recipients[0]['header'],
$this->sharedProtectedHeader
);
return $algorithm->getAgreementKey(
$this->contentEncryptionAlgorithm->getCEKSize(),
$this->contentEncryptionAlgorithm->name(),
$recipientKey,
$senderKey,
$completeHeader,
$additionalHeader
);
case KeyEncryption::MODE_DIRECT:
if (count($this->recipients) !== 1) {
throw new LogicException(
'Unable to encrypt for multiple recipients using key agreement algorithms.'
);
}
/** @var JWK $key */
$key = $this->recipients[0]['key'];
if ($key->get('kty') !== 'oct') {
throw new RuntimeException('Wrong key type.');
}
$k = $key->get('k');
if (! is_string($k)) {
throw new RuntimeException('Invalid key.');
}
return Base64UrlSafe::decode($k);
default:
throw new InvalidArgumentException(sprintf(
'Unsupported key management mode "%s".',
$this->keyManagementMode
));
}
}
private function getCompressionMethod(array $completeHeader): ?CompressionMethod
{
if (! array_key_exists('zip', $completeHeader)) {
return null;
}
return $this->compressionManager->get($completeHeader['zip']);
}
private function areKeyManagementModesCompatible(string $current, string $new): bool
{
$agree = KeyEncryptionAlgorithm::MODE_AGREEMENT;
$dir = KeyEncryptionAlgorithm::MODE_DIRECT;
$enc = KeyEncryptionAlgorithm::MODE_ENCRYPT;
$wrap = KeyEncryptionAlgorithm::MODE_WRAP;
$supportedKeyManagementModeCombinations = [
$enc . $enc => true,
$enc . $wrap => true,
$wrap . $enc => true,
$wrap . $wrap => true,
$agree . $agree => false,
$agree . $dir => false,
$agree . $enc => false,
$agree . $wrap => false,
$dir . $agree => false,
$dir . $dir => false,
$dir . $enc => false,
$dir . $wrap => false,
$enc . $agree => false,
$enc . $dir => false,
$wrap . $agree => false,
$wrap . $dir => false,
];
if (array_key_exists($current . $new, $supportedKeyManagementModeCombinations)) {
return $supportedKeyManagementModeCombinations[$current . $new];
}
return false;
}
private function createCEK(int $size): string
{
return random_bytes($size / 8);
}
private function createIV(int $size): string
{
return random_bytes($size / 8);
}
private function getKeyEncryptionAlgorithm(array $completeHeader): KeyEncryptionAlgorithm
{
if (! isset($completeHeader['alg'])) {
throw new InvalidArgumentException('Parameter "alg" is missing.');
}
$keyEncryptionAlgorithm = $this->keyEncryptionAlgorithmManager->get($completeHeader['alg']);
if (! $keyEncryptionAlgorithm instanceof KeyEncryptionAlgorithm) {
throw new InvalidArgumentException(sprintf(
'The key encryption algorithm "%s" is not supported or not a key encryption algorithm instance.',
$completeHeader['alg']
));
}
return $keyEncryptionAlgorithm;
}
private function getContentEncryptionAlgorithm(array $completeHeader): ContentEncryptionAlgorithm
{
if (! isset($completeHeader['enc'])) {
throw new InvalidArgumentException('Parameter "enc" is missing.');
}
$contentEncryptionAlgorithm = $this->contentEncryptionAlgorithmManager->get($completeHeader['enc']);
if (! $contentEncryptionAlgorithm instanceof ContentEncryptionAlgorithm) {
throw new InvalidArgumentException(sprintf(
'The content encryption algorithm "%s" is not supported or not a content encryption algorithm instance.',
$completeHeader['enc']
));
}
return $contentEncryptionAlgorithm;
}
private function checkDuplicatedHeaderParameters(array $header1, array $header2): void
{
$inter = array_intersect_key($header1, $header2);
if (count($inter) !== 0) {
throw new InvalidArgumentException(sprintf(
'The header contains duplicated entries: %s.',
implode(', ', array_keys($inter))
));
}
}
}