Completed
Push — master ( 7b61ef...71e756 )
by Florent
08:30 queued 07:08
created

RSAKey::createFromPEM()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.9617
c 0
b 0
f 0
cc 6
nc 7
nop 1
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\KeyConverter;
15
16
use Base64Url\Base64Url;
17
use InvalidArgumentException;
18
use Jose\Component\Core\JWK;
19
use Jose\Component\Core\Util\BigInteger;
20
use RuntimeException;
21
22
/**
23
 * @internal
24
 */
25
class RSAKey
26
{
27
    /**
28
     * @var array
29
     */
30
    private $values = [];
31
32
    /**
33
     * RSAKey constructor.
34
     */
35
    private function __construct(array $data)
36
    {
37
        $this->loadJWK($data);
38
    }
39
40
    /**
41
     * @return RSAKey
42
     */
43
    public static function createFromKeyDetails(array $details): self
44
    {
45
        $values = ['kty' => 'RSA'];
46
        $keys = [
47
            'n' => 'n',
48
            'e' => 'e',
49
            'd' => 'd',
50
            'p' => 'p',
51
            'q' => 'q',
52
            'dp' => 'dmp1',
53
            'dq' => 'dmq1',
54
            'qi' => 'iqmp',
55
        ];
56
        foreach ($details as $key => $value) {
57
            if (\in_array($key, $keys, true)) {
58
                $value = Base64Url::encode($value);
59
                $values[array_search($key, $keys, true)] = $value;
60
            }
61
        }
62
63
        return new self($values);
64
    }
65
66
    /**
67
     * @return RSAKey
68
     */
69
    public static function createFromPEM(string $pem): self
70
    {
71
        if (!\extension_loaded('openssl')) {
72
            throw new RuntimeException('Please install the OpenSSL extension');
73
        }
74
        $res = openssl_pkey_get_private($pem);
75
        if (false === $res) {
76
            $res = openssl_pkey_get_public($pem);
77
        }
78
        if (false === $res) {
79
            throw new InvalidArgumentException('Unable to load the key.');
80
        }
81
82
        $details = openssl_pkey_get_details($res);
83
        openssl_free_key($res);
84
        if (!\is_array($details) || !isset($details['rsa'])) {
85
            throw new InvalidArgumentException('Unable to load the key.');
86
        }
87
88
        return self::createFromKeyDetails($details['rsa']);
89
    }
90
91
    /**
92
     * @return RSAKey
93
     */
94
    public static function createFromJWK(JWK $jwk): self
95
    {
96
        return new self($jwk->all());
97
    }
98
99
    public function isPublic(): bool
100
    {
101
        return !\array_key_exists('d', $this->values);
102
    }
103
104
    /**
105
     * @param RSAKey $private
106
     *
107
     * @return RSAKey
108
     */
109
    public static function toPublic(self $private): self
110
    {
111
        $data = $private->toArray();
112
        $keys = ['p', 'd', 'q', 'dp', 'dq', 'qi'];
113
        foreach ($keys as $key) {
114
            if (\array_key_exists($key, $data)) {
115
                unset($data[$key]);
116
            }
117
        }
118
119
        return new self($data);
120
    }
121
122
    public function toArray(): array
123
    {
124
        return $this->values;
125
    }
126
127
    public function toJwk(): JWK
128
    {
129
        return new JWK($this->values);
130
    }
131
132
    /**
133
     * This method will try to add Chinese Remainder Theorem (CRT) parameters.
134
     * With those primes, the decryption process is really fast.
135
     */
136
    public function optimize(): void
137
    {
138
        if (\array_key_exists('d', $this->values)) {
139
            $this->populateCRT();
140
        }
141
    }
142
143
    private function loadJWK(array $jwk): void
144
    {
145
        if (!\array_key_exists('kty', $jwk)) {
146
            throw new InvalidArgumentException('The key parameter "kty" is missing.');
147
        }
148
        if ('RSA' !== $jwk['kty']) {
149
            throw new InvalidArgumentException('The JWK is not a RSA key.');
150
        }
151
152
        $this->values = $jwk;
153
    }
154
155
    /**
156
     * This method adds Chinese Remainder Theorem (CRT) parameters if primes 'p' and 'q' are available.
157
     * If 'p' and 'q' are missing, they are computed and added to the key data.
158
     */
159
    private function populateCRT(): void
160
    {
161
        if (!\array_key_exists('p', $this->values) && !\array_key_exists('q', $this->values)) {
162
            $d = BigInteger::createFromBinaryString(Base64Url::decode($this->values['d']));
163
            $e = BigInteger::createFromBinaryString(Base64Url::decode($this->values['e']));
164
            $n = BigInteger::createFromBinaryString(Base64Url::decode($this->values['n']));
165
166
            list($p, $q) = $this->findPrimeFactors($d, $e, $n);
167
            $this->values['p'] = Base64Url::encode($p->toBytes());
168
            $this->values['q'] = Base64Url::encode($q->toBytes());
169
        }
170
171
        if (\array_key_exists('dp', $this->values) && \array_key_exists('dq', $this->values) && \array_key_exists('qi', $this->values)) {
172
            return;
173
        }
174
175
        $one = BigInteger::createFromDecimal(1);
176
        $d = BigInteger::createFromBinaryString(Base64Url::decode($this->values['d']));
177
        $p = BigInteger::createFromBinaryString(Base64Url::decode($this->values['p']));
178
        $q = BigInteger::createFromBinaryString(Base64Url::decode($this->values['q']));
179
180
        $this->values['dp'] = Base64Url::encode($d->mod($p->subtract($one))->toBytes());
181
        $this->values['dq'] = Base64Url::encode($d->mod($q->subtract($one))->toBytes());
182
        $this->values['qi'] = Base64Url::encode($q->modInverse($p)->toBytes());
183
    }
184
185
    /**
186
     * @return BigInteger[]
187
     */
188
    private function findPrimeFactors(BigInteger $d, BigInteger $e, BigInteger $n): array
189
    {
190
        $zero = BigInteger::createFromDecimal(0);
191
        $one = BigInteger::createFromDecimal(1);
192
        $two = BigInteger::createFromDecimal(2);
193
194
        $k = $d->multiply($e)->subtract($one);
0 ignored issues
show
Documentation introduced by
$e is of type object<Jose\Component\Core\Util\BigInteger>, but the function expects a object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
195
196
        if ($k->isEven()) {
197
            $r = $k;
198
            $t = $zero;
199
200
            do {
201
                $r = $r->divide($two);
202
                $t = $t->add($one);
203
            } while ($r->isEven());
204
205
            $found = false;
206
            $y = null;
207
208
            for ($i = 1; $i <= 100; ++$i) {
209
                $g = BigInteger::random($n->subtract($one));
210
                $y = $g->modPow($r, $n);
211
212
                if ($y->equals($one) || $y->equals($n->subtract($one))) {
213
                    continue;
214
                }
215
216
                for ($j = $one; $j->lowerThan($t->subtract($one)); $j = $j->add($one)) {
217
                    $x = $y->modPow($two, $n);
218
219
                    if ($x->equals($one)) {
220
                        $found = true;
221
222
                        break;
223
                    }
224
225
                    if ($x->equals($n->subtract($one))) {
226
                        continue;
227
                    }
228
229
                    $y = $x;
230
                }
231
232
                $x = $y->modPow($two, $n);
233
                if ($x->equals($one)) {
234
                    $found = true;
235
236
                    break;
237
                }
238
            }
239
            if (null === $y) {
240
                throw new InvalidArgumentException('Unable to find prime factors.');
241
            }
242
            if (true === $found) {
243
                $p = $y->subtract($one)->gcd($n);
244
                $q = $n->divide($p);
245
246
                return [$p, $q];
247
            }
248
        }
249
250
        throw new InvalidArgumentException('Unable to find prime factors.');
251
    }
252
}
253