Failed Conditions
Push — v7 ( 722dd5...1e67af )
by Florent
03:17
created

RSAKey::toJwk()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 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'];
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
     * @return JWK
151
     */
152
    public function toJwk(): JWK
153
    {
154
        return JWK::create($this->values);
155
    }
156
157
    /**
158
     * This method will try to add Chinese Remainder Theorem (CRT) parameters.
159
     * With those primes, the decryption process is really fast.
160
     */
161
    public function optimize()
162
    {
163
        if (array_key_exists('d', $this->values)) {
164
            $this->populateCRT();
165
        }
166
    }
167
168
    /**
169
     * This method adds Chinese Remainder Theorem (CRT) parameters if primes 'p' and 'q' are available.
170
     */
171
    private function populateCRT()
172
    {
173
        if (!array_key_exists('p', $this->values) && !array_key_exists('q', $this->values)) {
174
            $d = BigInteger::createFromBinaryString(Base64Url::decode($this->values['d']));
175
            $e = BigInteger::createFromBinaryString(Base64Url::decode($this->values['e']));
176
            $n = BigInteger::createFromBinaryString(Base64Url::decode($this->values['n']));
177
178
            list($p, $q) = $this->findPrimeFactors($d, $e, $n);
179
            $this->values['p'] = Base64Url::encode($p->toBytes());
180
            $this->values['q'] = Base64Url::encode($q->toBytes());
181
        }
182
183
        if (array_key_exists('dp', $this->values) && array_key_exists('dq', $this->values) && array_key_exists('qi', $this->values)) {
184
            return;
185
        }
186
187
        $one = BigInteger::createFromDecimal(1);
188
        $d = BigInteger::createFromBinaryString(Base64Url::decode($this->values['d']));
189
        $p = BigInteger::createFromBinaryString(Base64Url::decode($this->values['p']));
190
        $q = BigInteger::createFromBinaryString(Base64Url::decode($this->values['q']));
191
192
        $this->values['dp'] = Base64Url::encode($d->mod($p->subtract($one))->toBytes());
193
        $this->values['dq'] = Base64Url::encode($d->mod($q->subtract($one))->toBytes());
194
        $this->values['qi'] = Base64Url::encode($q->modInverse($p)->toBytes());
195
    }
196
197
    /**
198
     * @param BigInteger $d
199
     * @param BigInteger $e
200
     * @param BigInteger $n
201
     *
202
     * @return BigInteger[]
203
     */
204
    private function findPrimeFactors(BigInteger $d, BigInteger $e, BigInteger $n): array
205
    {
206
        $zero = BigInteger::createFromDecimal(0);
207
        $one = BigInteger::createFromDecimal(1);
208
        $two = BigInteger::createFromDecimal(2);
209
210
        $k = $d->multiply($e)->subtract($one);
211
212
        if ($k->isEven()) {
213
            $r = $k;
214
            $t = $zero;
215
216
            do {
217
                $r = $r->divide($two);
218
                $t = $t->add($one);
219
            } while ($r->isEven());
220
221
            $found = false;
222
            $y = null;
223
224
            for ($i = 1; $i <= 100; ++$i) {
225
                $g = BigInteger::random($n->subtract($one));
226
                $y = $g->modPow($r, $n);
227
228
                if ($y->equals($one) || $y->equals($n->subtract($one))) {
229
                    continue;
230
                }
231
232
                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...
233
                    $x = $y->modPow($two, $n);
234
235
                    if ($x->equals($one)) {
236
                        $found = true;
237
238
                        break;
239
                    }
240
241
                    if ($x->equals($n->subtract($one))) {
242
                        continue;
243
                    }
244
245
                    $y = $x;
246
                }
247
248
                $x = $y->modPow($two, $n);
249
                if ($x->equals($one)) {
250
                    $found = true;
251
252
                    break;
253
                }
254
            }
255
256
            if (true === $found) {
257
                $p = $y->subtract($one)->gcd($n);
258
                $q = $n->divide($p);
259
260
                return [$p, $q];
261
            }
262
        }
263
264
        throw new \InvalidArgumentException('Unable to find prime factors.');
265
    }
266
}
267