Failed Conditions
Push — v7 ( a94305...5a1c51 )
by Florent
02:15
created

JWEBuilder   D

Complexity

Total Complexity 66

Size/Duplication

Total Lines 502
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
wmc 66
lcom 1
cbo 14
dl 0
loc 502
rs 4.6268
c 0
b 0
f 0

26 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getSupportedKeyEncryptionAlgorithms() 0 4 1
A getSupportedContentEncryptionAlgorithms() 0 4 1
A getSupportedCompressionMethods() 0 4 1
A withPayload() 0 7 1
A withAAD() 0 7 1
A withSharedProtectedHeaders() 0 7 1
A withSharedHeaders() 0 7 1
C addRecipient() 0 34 8
B build() 0 26 6
A checkAndSetContentEncryptionAlgorithm() 0 9 3
A processRecipient() 0 14 3
A encryptJWE() 0 11 2
B preparePayload() 0 17 5
B getEncryptedKey() 0 15 6
A getEncryptedKeyFromKeyAgreementAndKeyWrappingAlgorithm() 0 4 1
A getEncryptedKeyFromKeyEncryptionAlgorithm() 0 4 1
A getEncryptedKeyFromKeyWrappingAlgorithm() 0 4 1
A checkKey() 0 9 2
C determineCEK() 0 32 8
A getCompressionMethod() 0 8 2
A areKeyManagementModesCompatible() 0 14 2
A createCEK() 0 4 1
A createIV() 0 4 1
A getKeyEncryptionAlgorithm() 0 12 3
A getContentEncryptionAlgorithm() 0 12 3

How to fix   Complexity   

Complex Class

Complex classes like JWEBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use JWEBuilder, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Component\Encryption;
15
16
use Base64Url\Base64Url;
17
use Jose\Component\Core\JWAManager;
18
use Jose\Component\Core\JWK;
19
use Jose\Component\Core\KeyChecker;
20
use Jose\Component\Encryption\Algorithm\ContentEncryptionAlgorithmInterface;
21
use Jose\Component\Encryption\Algorithm\KeyEncryption\DirectEncryptionInterface;
22
use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyAgreementInterface;
23
use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyAgreementWrappingInterface;
24
use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyEncryptionInterface;
25
use Jose\Component\Encryption\Algorithm\KeyEncryption\KeyWrappingInterface;
26
use Jose\Component\Encryption\Algorithm\KeyEncryptionAlgorithmInterface;
27
use Jose\Component\Encryption\Compression\CompressionInterface;
28
use Jose\Component\Encryption\Compression\CompressionMethodsManager;
29
30
final class JWEBuilder
31
{
32
    /**
33
     * @var mixed
34
     */
35
    private $payload;
36
37
    /**
38
     * @var string|null
39
     */
40
    private $aad;
41
42
    /**
43
     * @var array
44
     */
45
    private $recipients = [];
46
47
    /**
48
     * @var JWAManager
49
     */
50
    private $keyEncryptionAlgorithmManager;
51
52
    /**
53
     * @var JWAManager
54
     */
55
    private $contentEncryptionAlgorithmManager;
56
57
    /**
58
     * @var CompressionMethodsManager
59
     */
60
    private $compressionManager;
61
62
    /**
63
     * @var array
64
     */
65
    private $sharedProtectedHeaders = [];
66
67
    /**
68
     * @var array
69
     */
70
    private $sharedHeaders = [];
71
72
    /**
73
     * @var null|CompressionInterface
74
     */
75
    private $compressionMethod = null;
76
77
    /**
78
     * @var null|ContentEncryptionAlgorithmInterface
79
     */
80
    private $contentEncryptionAlgorithm = null;
81
82
    /**
83
     * @var null|string
84
     */
85
    private $keyManagementMode = null;
86
87
    /**
88
     * JWEBuilder constructor.
89
     *
90
     * @param JWAManager                $keyEncryptionAlgorithmManager
91
     * @param JWAManager                $contentEncryptionAlgorithmManager
92
     * @param CompressionMethodsManager $compressionManager
93
     */
94
    public function __construct(JWAManager $keyEncryptionAlgorithmManager, JWAManager $contentEncryptionAlgorithmManager, CompressionMethodsManager $compressionManager)
95
    {
96
        $this->keyEncryptionAlgorithmManager = $keyEncryptionAlgorithmManager;
97
        $this->contentEncryptionAlgorithmManager = $contentEncryptionAlgorithmManager;
98
        $this->compressionManager = $compressionManager;
99
    }
100
101
    /**
102
     * @return string[]
103
     */
104
    public function getSupportedKeyEncryptionAlgorithms(): array
105
    {
106
        return $this->keyEncryptionAlgorithmManager->list();
107
    }
108
109
    /**
110
     * @return string[]
111
     */
112
    public function getSupportedContentEncryptionAlgorithms(): array
113
    {
114
        return $this->contentEncryptionAlgorithmManager->list();
115
    }
116
117
    /**
118
     * @return string[]
119
     */
120
    public function getSupportedCompressionMethods(): array
121
    {
122
        return $this->compressionManager->list();
123
    }
124
125
    /**
126
     * @param mixed $payload
127
     *
128
     * @return JWEBuilder
129
     */
130
    public function withPayload($payload): JWEBuilder
131
    {
132
        $clone = clone $this;
133
        $clone->payload = $payload;
134
135
        return $clone;
136
    }
137
138
    /**
139
     * @param string|null $aad
140
     *
141
     * @return JWEBuilder
142
     */
143
    public function withAAD(?string $aad): JWEBuilder
144
    {
145
        $clone = clone $this;
146
        $clone->aad = $aad;
147
148
        return $clone;
149
    }
150
151
    /**
152
     * @param array $sharedProtectedHeaders
153
     *
154
     * @return JWEBuilder
155
     */
156
    public function withSharedProtectedHeaders(array $sharedProtectedHeaders): JWEBuilder
157
    {
158
        $clone = clone $this;
159
        $clone->sharedProtectedHeaders = $sharedProtectedHeaders;
160
161
        return $clone;
162
    }
163
164
    /**
165
     * @param array $sharedHeaders
166
     *
167
     * @return JWEBuilder
168
     */
169
    public function withSharedHeaders(array $sharedHeaders): JWEBuilder
170
    {
171
        $clone = clone $this;
172
        $clone->sharedHeaders = $sharedHeaders;
173
174
        return $clone;
175
    }
176
177
    /**
178
     * @param JWK   $recipientKey
179
     * @param array $recipientHeaders
180
     *
181
     * @return JWEBuilder
182
     */
183
    public function addRecipient(JWK $recipientKey, array $recipientHeaders = []): JWEBuilder
184
    {
185
        $clone = clone $this;
186
        $completeHeaders = array_merge($clone->sharedHeaders, $recipientHeaders, $clone->sharedProtectedHeaders);
187
        $clone->checkAndSetContentEncryptionAlgorithm($completeHeaders);
188
        $keyEncryptionAlgorithm = $clone->getKeyEncryptionAlgorithm($completeHeaders);
189
        if (null === $clone->keyManagementMode) {
190
            $clone->keyManagementMode = $keyEncryptionAlgorithm->getKeyManagementMode();
191
        } else {
192
            if (!$clone->areKeyManagementModesCompatible($clone->keyManagementMode, $keyEncryptionAlgorithm->getKeyManagementMode())) {
193
                throw new \InvalidArgumentException('Foreign key management mode forbidden.');
194
            }
195
        }
196
197
        $compressionMethod = $clone->getCompressionMethod($completeHeaders);
198
        if (null !== $compressionMethod) {
199
            if (null === $clone->compressionMethod) {
200
                $clone->compressionMethod = $compressionMethod;
201
            } elseif ($clone->compressionMethod->name() !== $compressionMethod->name()) {
202
                throw new \InvalidArgumentException('Incompatible compression method.');
203
            }
204
        }
205
        if (null === $compressionMethod && null !== $clone->compressionMethod) {
206
            throw new \InvalidArgumentException('Inconsistent compression method.');
207
        }
208
        $clone->checkKey($keyEncryptionAlgorithm, $recipientKey);
209
        $clone->recipients[] = [
210
            'key' => $recipientKey,
211
            'headers' => $recipientHeaders,
212
            'key_encryption_algorithm' => $keyEncryptionAlgorithm,
213
        ];
214
215
        return $clone;
216
    }
217
218
    /**
219
     * @return JWE
220
     */
221
    public function build(): JWE
222
    {
223
        if (0 === count($this->recipients)) {
224
            throw new \LogicException('No recipient.');
225
        }
226
227
        $additionalHeaders = [];
228
        $cek = $this->determineCEK($additionalHeaders);
229
230
        $recipients = [];
231
        foreach ($this->recipients as $recipient) {
232
            $recipient = $this->processRecipient($recipient, $cek, $additionalHeaders);
233
            $recipients[] = $recipient;
234
        }
235
236
        if (!empty($additionalHeaders) && 1 === count($this->recipients)) {
237
            $sharedProtectedHeaders = array_merge($additionalHeaders, $this->sharedProtectedHeaders);
238
        } else {
239
            $sharedProtectedHeaders = $this->sharedProtectedHeaders;
240
        }
241
        $encodedSharedProtectedHeaders = empty($sharedProtectedHeaders) ? '' : Base64Url::encode(json_encode($sharedProtectedHeaders));
242
243
        list($ciphertext, $iv, $tag) = $this->encryptJWE($cek, $encodedSharedProtectedHeaders);
244
245
        return JWE::create($ciphertext, $iv, $this->aad, $tag, $this->sharedHeaders, $sharedProtectedHeaders, $encodedSharedProtectedHeaders, $recipients);
246
    }
247
248
    /**
249
     * @param array $completeHeaders
250
     */
251
    private function checkAndSetContentEncryptionAlgorithm(array $completeHeaders): void
252
    {
253
        $contentEncryptionAlgorithm = $this->getContentEncryptionAlgorithm($completeHeaders);
254
        if (null === $this->contentEncryptionAlgorithm) {
255
            $this->contentEncryptionAlgorithm = $contentEncryptionAlgorithm;
256
        } elseif ($contentEncryptionAlgorithm->name() !== $this->contentEncryptionAlgorithm->name()) {
257
            throw new \InvalidArgumentException('Inconsistent content encryption algorithm');
258
        }
259
    }
260
261
    /**
262
     * @param array  $recipient
263
     * @param string $cek
264
     * @param array  $additionalHeaders
265
     *
266
     * @return Recipient
267
     */
268
    private function processRecipient(array $recipient, string $cek, array &$additionalHeaders): Recipient
269
    {
270
        $completeHeaders = array_merge($this->sharedHeaders, $recipient['headers'], $this->sharedProtectedHeaders);
271
        /** @var KeyEncryptionAlgorithmInterface $keyEncryptionAlgorithm */
272
        $keyEncryptionAlgorithm = $recipient['key_encryption_algorithm'];
273
        $encryptedContentEncryptionKey = $this->getEncryptedKey($completeHeaders, $cek, $keyEncryptionAlgorithm, $additionalHeaders, $recipient['key']);
274
        $recipientHeaders = $recipient['headers'];
275
        if (!empty($additionalHeaders) && 1 !== count($this->recipients)) {
276
            $recipientHeaders = array_merge($recipientHeaders, $additionalHeaders);
277
            $additionalHeaders = [];
278
        }
279
280
        return Recipient::create($recipientHeaders, $encryptedContentEncryptionKey);
281
    }
282
283
    /**
284
     * @param string $cek
285
     * @param string $encodedSharedProtectedHeaders
286
     *
287
     * @return array
288
     */
289
    private function encryptJWE(string $cek, string $encodedSharedProtectedHeaders): array
290
    {
291
        $tag = null;
292
        $iv_size = $this->contentEncryptionAlgorithm->getIVSize();
293
        $iv = $this->createIV($iv_size);
294
        $payload = $this->preparePayload();
295
        $aad = $this->aad ? Base64Url::encode($this->aad) : null;
296
        $ciphertext = $this->contentEncryptionAlgorithm->encryptContent($payload, $cek, $iv, $aad, $encodedSharedProtectedHeaders, $tag);
297
298
        return [$ciphertext, $iv, $tag];
299
    }
300
301
    /**
302
     * @return string
303
     */
304
    private function preparePayload(): ?string
305
    {
306
        $prepared = is_string($this->payload) ? $this->payload : json_encode($this->payload);
307
        if (null === $prepared) {
308
            throw new \RuntimeException('The payload is empty or cannot encoded into JSON.');
309
        }
310
311
        if (null === $this->compressionMethod) {
312
            return $prepared;
313
        }
314
        $compressedPayload = $this->compressionMethod->compress($prepared);
315
        if (null === $compressedPayload) {
316
            throw new \RuntimeException('The payload cannot be compressed.');
317
        }
318
319
        return $compressedPayload;
320
    }
321
322
    /**
323
     * @param array                           $completeHeaders
324
     * @param string                          $cek
325
     * @param KeyEncryptionAlgorithmInterface $keyEncryptionAlgorithm
326
     * @param JWK                             $recipientKey
327
     * @param array                           $additionalHeaders
328
     *
329
     * @return string|null
330
     */
331
    private function getEncryptedKey(array $completeHeaders, string $cek, KeyEncryptionAlgorithmInterface $keyEncryptionAlgorithm, array &$additionalHeaders, JWK $recipientKey): ?string
332
    {
333
        if ($keyEncryptionAlgorithm instanceof KeyEncryptionInterface) {
334
            return $this->getEncryptedKeyFromKeyEncryptionAlgorithm($completeHeaders, $cek, $keyEncryptionAlgorithm, $recipientKey, $additionalHeaders);
335
        } elseif ($keyEncryptionAlgorithm instanceof KeyWrappingInterface) {
336
            return $this->getEncryptedKeyFromKeyWrappingAlgorithm($completeHeaders, $cek, $keyEncryptionAlgorithm, $recipientKey, $additionalHeaders);
337
        } elseif ($keyEncryptionAlgorithm instanceof KeyAgreementWrappingInterface) {
338
            return $this->getEncryptedKeyFromKeyAgreementAndKeyWrappingAlgorithm($completeHeaders, $cek, $keyEncryptionAlgorithm, $additionalHeaders, $recipientKey);
339
        } elseif ($keyEncryptionAlgorithm instanceof KeyAgreementInterface) {
340
            return null;
341
        } elseif ($keyEncryptionAlgorithm instanceof DirectEncryptionInterface) {
342
            return null;
343
        }
344
        throw new \InvalidArgumentException('Unsupported key encryption algorithm.');
345
    }
346
347
    /**
348
     * @param array                         $completeHeaders
349
     * @param string                        $cek
350
     * @param KeyAgreementWrappingInterface $keyEncryptionAlgorithm
351
     * @param array                         $additionalHeaders
352
     * @param JWK                           $recipientKey
353
     *
354
     * @return string
355
     */
356
    private function getEncryptedKeyFromKeyAgreementAndKeyWrappingAlgorithm(array $completeHeaders, string $cek, KeyAgreementWrappingInterface $keyEncryptionAlgorithm, array &$additionalHeaders, JWK $recipientKey): string
357
    {
358
        return $keyEncryptionAlgorithm->wrapAgreementKey($recipientKey, $cek, $this->contentEncryptionAlgorithm->getCEKSize(), $completeHeaders, $additionalHeaders);
359
    }
360
361
    /**
362
     * @param array                  $completeHeaders
363
     * @param string                 $cek
364
     * @param KeyEncryptionInterface $keyEncryptionAlgorithm
365
     * @param JWK                    $recipientKey
366
     * @param array                  $additionalHeaders
367
     *
368
     * @return string
369
     */
370
    private function getEncryptedKeyFromKeyEncryptionAlgorithm(array $completeHeaders, string $cek, KeyEncryptionInterface $keyEncryptionAlgorithm, JWK $recipientKey, array &$additionalHeaders): string
371
    {
372
        return $keyEncryptionAlgorithm->encryptKey($recipientKey, $cek, $completeHeaders, $additionalHeaders);
373
    }
374
375
    /**
376
     * @param array                $completeHeaders
377
     * @param string               $cek
378
     * @param KeyWrappingInterface $keyEncryptionAlgorithm
379
     * @param JWK                  $recipientKey
380
     * @param array                $additionalHeaders
381
     *
382
     * @return string
383
     */
384
    private function getEncryptedKeyFromKeyWrappingAlgorithm(array $completeHeaders, string $cek, KeyWrappingInterface $keyEncryptionAlgorithm, JWK $recipientKey, array &$additionalHeaders): string
385
    {
386
        return $keyEncryptionAlgorithm->wrapKey($recipientKey, $cek, $completeHeaders, $additionalHeaders);
387
    }
388
389
    /**
390
     * @param KeyEncryptionAlgorithmInterface $keyEncryptionAlgorithm
391
     * @param JWK                             $recipientKey
392
     */
393
    private function checkKey(KeyEncryptionAlgorithmInterface $keyEncryptionAlgorithm, JWK $recipientKey)
394
    {
395
        KeyChecker::checkKeyUsage($recipientKey, 'encryption');
396
        if ('dir' !== $keyEncryptionAlgorithm->name()) {
397
            KeyChecker::checkKeyAlgorithm($recipientKey, $keyEncryptionAlgorithm->name());
398
        } else {
399
            KeyChecker::checkKeyAlgorithm($recipientKey, $this->contentEncryptionAlgorithm->name());
400
        }
401
    }
402
403
    /**
404
     * @param array $additionalHeaders
405
     *
406
     * @return string
407
     */
408
    private function determineCEK(array &$additionalHeaders): string
409
    {
410
        switch ($this->keyManagementMode) {
411
            case KeyEncryptionInterface::MODE_ENCRYPT:
412
            case KeyEncryptionInterface::MODE_WRAP:
413
                return $this->createCEK($this->contentEncryptionAlgorithm->getCEKSize());
414
            case KeyEncryptionInterface::MODE_AGREEMENT:
415
                if (1 !== count($this->recipients)) {
416
                    throw new \LogicException('Unable to encrypt for multiple recipients using key agreement algorithms.');
417
                }
418
                /** @var JWK $key */
419
                $key = $this->recipients[0]['key'];
420
                /** @var KeyAgreementInterface $algorithm */
421
                $algorithm = $this->recipients[0]['key_encryption_algorithm'];
422
                $completeHeaders = array_merge($this->sharedHeaders, $this->recipients[0]['headers'], $this->sharedProtectedHeaders);
423
424
                return $algorithm->getAgreementKey($this->contentEncryptionAlgorithm->getCEKSize(), $this->contentEncryptionAlgorithm->name(), $key, $completeHeaders, $additionalHeaders);
425
            case KeyEncryptionInterface::MODE_DIRECT:
426
                if (1 !== count($this->recipients)) {
427
                    throw new \LogicException('Unable to encrypt for multiple recipients using key agreement algorithms.');
428
                }
429
                /** @var JWK $key */
430
                $key = $this->recipients[0]['key'];
431
                if ('oct' !== $key->get('kty')) {
432
                    throw new \RuntimeException('Wrong key type.');
433
                }
434
435
                return Base64Url::decode($key->get('k'));
436
            default:
437
                throw new \InvalidArgumentException(sprintf('Unsupported key management mode "%s".', $this->keyManagementMode));
438
        }
439
    }
440
441
    /**
442
     * @param array $completeHeaders
443
     *
444
     * @return CompressionInterface|null
445
     */
446
    private function getCompressionMethod(array $completeHeaders): ?CompressionInterface
447
    {
448
        if (!array_key_exists('zip', $completeHeaders)) {
449
            return null;
450
        }
451
452
        return $this->compressionManager->get($completeHeaders['zip']);
453
    }
454
455
    /**
456
     * @param string $current
457
     * @param string $new
458
     *
459
     * @return bool
460
     */
461
    private function areKeyManagementModesCompatible(string $current, string $new): bool
462
    {
463
        $agree = KeyEncryptionAlgorithmInterface::MODE_AGREEMENT;
464
        $dir = KeyEncryptionAlgorithmInterface::MODE_DIRECT;
465
        $enc = KeyEncryptionAlgorithmInterface::MODE_ENCRYPT;
466
        $wrap = KeyEncryptionAlgorithmInterface::MODE_WRAP;
467
        $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];
468
469
        if (array_key_exists($current.$new, $supportedKeyManagementModeCombinations)) {
470
            return $supportedKeyManagementModeCombinations[$current.$new];
471
        }
472
473
        return false;
474
    }
475
476
    /**
477
     * @param int $size
478
     *
479
     * @return string
480
     */
481
    private function createCEK(int $size): string
482
    {
483
        return random_bytes($size / 8);
484
    }
485
486
    /**
487
     * @param int $size
488
     *
489
     * @return string
490
     */
491
    private function createIV(int $size): string
492
    {
493
        return random_bytes($size / 8);
494
    }
495
496
    /**
497
     * @param array $completeHeaders
498
     *
499
     * @return KeyEncryptionAlgorithmInterface
500
     */
501
    private function getKeyEncryptionAlgorithm(array $completeHeaders): KeyEncryptionAlgorithmInterface
502
    {
503
        if (!array_key_exists('alg', $completeHeaders)) {
504
            throw new \InvalidArgumentException('Parameter "alg" is missing.');
505
        }
506
        $keyEncryptionAlgorithm = $this->keyEncryptionAlgorithmManager->get($completeHeaders['alg']);
507
        if (!$keyEncryptionAlgorithm instanceof KeyEncryptionAlgorithmInterface) {
508
            throw new \InvalidArgumentException(sprintf('The key encryption algorithm "%s" is not supported or not a key encryption algorithm instance.', $completeHeaders['alg']));
509
        }
510
511
        return $keyEncryptionAlgorithm;
512
    }
513
514
    /**
515
     * @param array $completeHeaders
516
     *
517
     * @return ContentEncryptionAlgorithmInterface
518
     */
519
    private function getContentEncryptionAlgorithm(array $completeHeaders): ContentEncryptionAlgorithmInterface
520
    {
521
        if (!array_key_exists('enc', $completeHeaders)) {
522
            throw new \InvalidArgumentException('Parameter "enc" is missing.');
523
        }
524
        $contentEncryptionAlgorithm = $this->contentEncryptionAlgorithmManager->get($completeHeaders['enc']);
525
        if (!$contentEncryptionAlgorithm instanceof ContentEncryptionAlgorithmInterface) {
526
            throw new \InvalidArgumentException(sprintf('The content encryption algorithm "%s" is not supported or not a content encryption algorithm instance.', $completeHeaders['alg']));
527
        }
528
529
        return $contentEncryptionAlgorithm;
530
    }
531
}
532