GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

ECDSAAdapter::sign()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 18
nc 1
nop 3
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Gandung\JWT\Adapter;
4
5
use Mdanter\Ecc\EccFactory;
6
use Mdanter\Ecc\Crypto\Key\PrivateKeyInterface;
7
use Mdanter\Ecc\Crypto\Key\PublicKeyInterface;
8
use Mdanter\Ecc\Math\GmpMathInterface;
9
use Mdanter\Ecc\Crypto\Signature\Signer;
10
use Mdanter\Ecc\Curves\NistCurve;
11
use Mdanter\Ecc\Random\RandomGeneratorFactory;
12
use Mdanter\Ecc\Random\RandomNumberGeneratorInterface;
13
use Mdanter\Ecc\Crypto\Signature\Signature;
14
use Mdanter\Ecc\Crypto\Signature\SignatureInterface;
15
use Mdanter\Ecc\Crypto\Signature\SignHasher;
16
use Mdanter\Ecc\Primitives\GeneratorPoint;
17
18
/**
19
 * @author Paulus Gandung Prakosa <[email protected]>
20
 */
21
class ECDSAAdapter implements ECDSAAdapterInterface
22
{
23
    /**
24
     * @var GmpMathInterface
25
     */
26
    private $adapter;
27
28
    /**
29
     * @var Signer
30
     */
31
    private $signer;
32
33
    /**
34
     * @var NistCurves
35
     */
36
    private $curve;
37
38
    /**
39
     * @var RandomGeneratorInterface
40
     */
41
    private $random;
42
43
    /**
44
     * Signature hash length hashmap.
45
     */
46
    private const SIGNATURE_LENGTH = [
47
        'sha256' => 64,
48
        'sha384' => 96,
49
        'sha512' => 132
50
    ];
51
52
    /**
53
     * Generator point hashmap.
54
     */
55
    private const GENERATOR_POINTS = [
56
        'sha256' => 'generator256',
57
        'sha384' => 'generator384',
58
        'sha512' => 'generator521'
59
    ];
60
61
    public function __construct(
62
        GmpMathInterface $adapter
63
    ) {
64
        $this->adapter = $adapter;
65
        $this->signer = EccFactory::getSigner($this->adapter);
66
        $this->curve = EccFactory::getNistCurves($this->adapter);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Mdanter\Ecc\EccFactory:...tCurves($this->adapter) of type object<Mdanter\Ecc\Curves\NistCurve> is incompatible with the declared type object<Gandung\JWT\Adapter\NistCurves> of property $curve.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
67
        $this->random = RandomGeneratorFactory::getRandomGenerator();
0 ignored issues
show
Documentation Bug introduced by
It seems like \Mdanter\Ecc\Random\Rand...y::getRandomGenerator() of type object<Mdanter\Ecc\Rando...mberGeneratorInterface> is incompatible with the declared type object<Gandung\JWT\Adapt...ndomGeneratorInterface> of property $random.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
68
    }
69
70
    /**
71
     * For chainability purpose.
72
     */
73
    public static function create()
74
    {
75
        return new static(
76
            EccFactory::getAdapter()
77
        );
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function sign(
84
        PrivateKeyInterface $key,
85
        \GMP $hash,
86
        $algorithm
87
    ) {
88
        $signature = $this->signer->sign(
89
            $key,
90
            $hash,
91
            $this->random->generate($key->getPoint()->getOrder())
92
        );
93
94
        return \pack(
95
            'H*',
96
            \sprintf(
97
                "%s%s",
98
                $this->addSignaturePadding(
99
                    $signature->getR(),
100
                    self::SIGNATURE_LENGTH[$algorithm]
101
                ),
102
                $this->addSignaturePadding(
103
                    $signature->getS(),
104
                    self::SIGNATURE_LENGTH[$algorithm]
105
                )
106
            )
107
        );
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113
    public function verify(
114
        $expected,
115
        PublicKeyInterface $key,
116
        \GMP $hash,
117
        $algorithm
118
    ) {
119
        return $this->signer->verify(
120
            $key,
121
            $this->parseExpectedSignature($expected, $algorithm),
122
            $hash
123
        );
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    public function createSigningHash($payload, $algorithm)
130
    {
131
        $hasher = new SignHasher($algorithm, $this->adapter);
132
133
        return $hasher->makeHash(
134
            $payload,
135
            $this->determineGeneratorPoint($algorithm)
136
        );
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142
    public function getMathAdapter()
143
    {
144
        return $this->adapter;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->adapter; (Mdanter\Ecc\Math\GmpMathInterface) is incompatible with the return type declared by the interface Gandung\JWT\Adapter\ECDS...terface::getMathAdapter of type Gandung\JWT\Adapter\GmpMathInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
145
    }
146
147
    /**
148
     * Parse previous generated signature.
149
     *
150
     * @param string $expected
151
     * @param string $algorithm
152
     * @return SignatureInterface
153
     */
154
    private function parseExpectedSignature($expected, $algorithm)
155
    {
156
        [$pointR, $pointS] = \str_split(
0 ignored issues
show
Bug introduced by
The variable $pointR does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $pointS does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
157
            \unpack('H*', $expected)[1],
158
            self::SIGNATURE_LENGTH[$algorithm]
159
        );
160
161
        return new Signature(
162
            \gmp_init($this->adapter->hexDec($pointR), 10),
163
            \gmp_init($this->adapter->hexDec($pointS), 10)
164
        );
165
    }
166
167
    /**
168
     * Append zero char into given ECDSA signature.
169
     *
170
     * @param \GMP $point
171
     * @param integer $length
172
     * @return string
173
     */
174
    private function addSignaturePadding(\GMP $point, $length)
175
    {
176
        return \str_pad($this->adapter->decHex((string)$point), $length, '0', \STR_PAD_LEFT);
177
    }
178
179
    /**
180
     * Determine ECDSA generator point based on given algorithm.
181
     *
182
     * @param string $algorithm
183
     * @return GeneratorPoint
184
     */
185
    private function determineGeneratorPoint($algorithm)
186
    {
187
        if (!array_key_exists($algorithm, self::GENERATOR_POINTS)) {
188
            throw new \InvalidArgumentException(
189
                "Invalid ECDSA hashing algorithm."
190
            );
191
        }
192
193
        return \call_user_func(
194
            [$this->curve, self::GENERATOR_POINTS[$algorithm]],
195
            $this->random
196
        );
197
    }
198
}
199