Failed Conditions
Push — v7 ( d25f5c...477009 )
by Florent
02:07
created

RSAKey::toPublic()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
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\KeyManagement\KeyConverter;
15
16
use Base64Url\Base64Url;
17
use Jose\Component\Core\JWK;
18
use Jose\Component\Core\Util\BigInteger;
19
20
final class RSAKey
21
{
22
    /**
23
     * @var array
24
     */
25
    private $values = [];
26
27
    /**
28
     * RSAKey constructor.
29
     *
30
     * @param array $data
31
     */
32
    private function __construct(array $data)
33
    {
34
        $this->loadJWK($data);
35
    }
36
37
    /**
38
     * @param string $pem
39
     *
40
     * @return RSAKey
41
     */
42
    public static function createFromPEM(string $pem): RSAKey
43
    {
44
        $data = self::loadPEM($pem);
45
46
        return new self($data);
47
    }
48
49
    /**
50
     * @param JWK $jwk
51
     *
52
     * @return RSAKey
53
     */
54
    public static function createFromJWK(JWK $jwk): RSAKey
55
    {
56
        return new self($jwk->all());
57
    }
58
59
    /**
60
     * @param string $data
61
     *
62
     * @return array
63
     */
64
    private static function loadPEM(string $data): array
65
    {
66
        $res = openssl_pkey_get_private($data);
67
        if (false === $res) {
68
            $res = openssl_pkey_get_public($data);
69
        }
70
        if (false === $res) {
71
            throw new \InvalidArgumentException('Unable to load the key.');
72
        }
73
74
        $details = openssl_pkey_get_details($res);
75
        if (!array_key_exists('rsa', $details)) {
76
            throw new \InvalidArgumentException('Unable to load the key.');
77
        }
78
79
        $values['kty'] = 'RSA';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$values was never initialized. Although not strictly required by PHP, it is generally a good practice to add $values = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
80
        $keys = [
81
            'n' => 'n',
82
            'e' => 'e',
83
            'd' => 'd',
84
            'p' => 'p',
85
            'q' => 'q',
86
            'dp' => 'dmp1',
87
            'dq' => 'dmq1',
88
            'qi' => 'iqmp',
89
        ];
90
        foreach ($details['rsa'] as $key => $value) {
91
            if (in_array($key, $keys)) {
92
                $value = Base64Url::encode($value);
93
                $values[array_search($key, $keys)] = $value;
94
            }
95
        }
96
97
        return $values;
98
    }
99
100
    /**
101
     * @return bool
102
     */
103
    public function isPublic(): bool
104
    {
105
        return !array_key_exists('d', $this->values);
106
    }
107
108
    /**
109
     * @param RSAKey $private
110
     *
111
     * @return RSAKey
112
     */
113
    public static function toPublic(RSAKey $private): RSAKey
114
    {
115
        $data = $private->toArray();
116
        $keys = ['p', 'd', 'q', 'dp', 'dq', 'qi'];
117
        foreach ($keys as $key) {
118
            if (array_key_exists($key, $data)) {
119
                unset($data[$key]);
120
            }
121
        }
122
123
        return new self($data);
124
    }
125
126
    /**
127
     * @return array
128
     */
129
    public function toArray(): array
130
    {
131
        return $this->values;
132
    }
133
134
    /**
135
     * @param array $jwk
136
     */
137
    private function loadJWK(array $jwk)
138
    {
139
        if (!array_key_exists('kty', $jwk)) {
140
            throw new \InvalidArgumentException('The key parameter "kty" is missing.');
141
        }
142
        if ('RSA' !== $jwk['kty']) {
143
            throw new \InvalidArgumentException('The JWK is not a RSA key.');
144
        }
145
146
        $this->values = $jwk;
147
    }
148
149
    /**
150
     * This method will try to add Chinese Remainder Theorem (CRT) parameters.
151
     * With those primes, the decryption process is really fast.
152
     */
153
    public function optimize()
154
    {
155
        if (array_key_exists('d', $this->values)) {
156
            $this->populateCRT();
157
        }
158
    }
159
160
    /**
161
     * This method adds Chinese Remainder Theorem (CRT) parameters if primes 'p' and 'q' are available.
162
     */
163
    private function populateCRT()
164
    {
165
        if (!array_key_exists('p', $this->values) && !array_key_exists('q', $this->values)) {
166
            $d = BigInteger::createFromBinaryString(Base64Url::decode($this->values['d']));
167
            $e = BigInteger::createFromBinaryString(Base64Url::decode($this->values['e']));
168
            $n = BigInteger::createFromBinaryString(Base64Url::decode($this->values['n']));
169
170
            list($p, $q) = $this->findPrimeFactors($d, $e, $n);
171
            $this->values['p'] = Base64Url::encode($p->toBytes());
172
            $this->values['q'] = Base64Url::encode($q->toBytes());
173
        }
174
175
        if (array_key_exists('dp', $this->values) && array_key_exists('dq', $this->values) && array_key_exists('qi', $this->values)) {
176
            return;
177
        }
178
179
        $one = BigInteger::createFromDecimal(1);
180
        $d = BigInteger::createFromBinaryString(Base64Url::decode($this->values['d']));
181
        $p = BigInteger::createFromBinaryString(Base64Url::decode($this->values['p']));
182
        $q = BigInteger::createFromBinaryString(Base64Url::decode($this->values['q']));
183
184
        $this->values['dp'] = Base64Url::encode($d->mod($p->subtract($one))->toBytes());
185
        $this->values['dq'] = Base64Url::encode($d->mod($q->subtract($one))->toBytes());
186
        $this->values['qi'] = Base64Url::encode($q->modInverse($p)->toBytes());
187
    }
188
189
    /**
190
     * @param BigInteger $d
191
     * @param BigInteger $e
192
     * @param BigInteger $n
193
     *
194
     * @return BigInteger[]
195
     */
196
    private function findPrimeFactors(BigInteger $d, BigInteger $e, BigInteger $n): array
197
    {
198
        $zero = BigInteger::createFromDecimal(0);
199
        $one = BigInteger::createFromDecimal(1);
200
        $two = BigInteger::createFromDecimal(2);
201
202
        $k = $d->multiply($e)->subtract($one);
203
204
        if ($k->isEven()) {
205
            $r = $k;
206
            $t = $zero;
207
208
            do {
209
                $r = $r->divide($two);
210
                $t = $t->add($one);
211
            } while ($r->isEven());
212
213
            $found = false;
214
            $y = null;
215
216
            for ($i = 1; $i <= 100; ++$i) {
217
                $g = BigInteger::random($n->subtract($one));
218
                $y = $g->modPow($r, $n);
219
220
                if ($y->equals($one) || $y->equals($n->subtract($one))) {
221
                    continue;
222
                }
223
224
                for ($j = $one; $j->lowerThan($t->subtract($one)); $j = $j->add($one)) {
0 ignored issues
show
Performance Best Practice introduced by
Consider avoiding function calls on each iteration of the for loop.

If you have a function call in the test part of a for loop, this function is executed on each iteration. Often such a function, can be moved to the initialization part and be cached.

// count() is called on each iteration
for ($i=0; $i < count($collection); $i++) { }

// count() is only called once
for ($i=0, $c=count($collection); $i<$c; $i++) { }
Loading history...
225
                    $x = $y->modPow($two, $n);
226
227
                    if ($x->equals($one)) {
228
                        $found = true;
229
230
                        break;
231
                    }
232
233
                    if ($x->equals($n->subtract($one))) {
234
                        continue;
235
                    }
236
237
                    $y = $x;
238
                }
239
240
                $x = $y->modPow($two, $n);
241
                if ($x->equals($one)) {
242
                    $found = true;
243
244
                    break;
245
                }
246
            }
247
248
            if (true === $found) {
249
                $p = $y->subtract($one)->gcd($n);
250
                $q = $n->divide($p);
251
252
                return [$p, $q];
253
            }
254
        }
255
256
        throw new \InvalidArgumentException('Unable to find prime factors.');
257
    }
258
}
259