ES512KeyAnalyzer::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2019 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\KeyManagement\Analyzer;
15
16
use Base64Url\Base64Url;
17
use Jose\Component\Core\JWK;
18
use Jose\Component\Core\Util\Ecc\NistCurve;
19
use RuntimeException;
20
21
final class ES512KeyAnalyzer implements KeyAnalyzer
22
{
23
    /**
24
     * @throws RuntimeException if the component "web-token/jwt-util-ecc" is missing
25
     */
26
    public function __construct()
27
    {
28
        if (!class_exists(NistCurve::class)) {
29
            throw new RuntimeException('Please install web-token/jwt-util-ecc to use this key analyzer');
30
        }
31
    }
32
33
    public function analyze(JWK $jwk, MessageBag $bag): void
34
    {
35
        if ('EC' !== $jwk->get('kty')) {
36
            return;
37
        }
38
        if (!$jwk->has('crv')) {
39
            $bag->add(Message::high('Invalid key. The components "crv" is missing.'));
40
41
            return;
42
        }
43
        if ('P-521' !== $jwk->get('crv')) {
44
            return;
45
        }
46
        $x = Base64Url::decode($jwk->get('x'));
47
        $xLength = 8 * mb_strlen($x, '8bit');
48
        $y = Base64Url::decode($jwk->get('y'));
49
        $yLength = 8 * mb_strlen($y, '8bit');
50
        if ($yLength !== $xLength || 528 !== $yLength) {
51
            $bag->add(Message::high('Invalid key. The components "x" and "y" size shall be 528 bits.'));
52
        }
53
        $xGmp = gmp_init(bin2hex($x), 16);
54
        $yGmp = gmp_init(bin2hex($y), 16);
55
        $curve = NistCurve::curve521();
56
        if (!$curve->contains($xGmp, $yGmp)) {
57
            $bag->add(Message::high('Invalid key. The point is not on the curve.'));
58
        }
59
    }
60
}
61