Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/KeyManagement/KeyConverter/RSAKey.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\KeyManagement\KeyConverter;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\JWK;
9 use Jose\Component\Core\Util\Base64UrlSafe;
10 use Jose\Component\Core\Util\BigInteger;
11 use RuntimeException;
12 use function array_key_exists;
13 use function extension_loaded;
14 use function in_array;
15 use function is_array;
16
17 /**
18 * @internal
19 */
20 final class RSAKey
21 {
22 private array $values = [];
23
24 private function __construct(array $data)
25 {
26 $this->loadJWK($data);
27 }
28
29 public static function createFromKeyDetails(array $details): self
30 {
31 $values = [
32 'kty' => 'RSA',
33 ];
34 $keys = [
35 'n' => 'n',
36 'e' => 'e',
37 'd' => 'd',
38 'p' => 'p',
39 'q' => 'q',
40 'dp' => 'dmp1',
41 'dq' => 'dmq1',
42 'qi' => 'iqmp',
43 ];
44 foreach ($details as $key => $value) {
45 if (in_array($key, $keys, true)) {
46 $value = Base64UrlSafe::encodeUnpadded($value);
47 $values[array_search($key, $keys, true)] = $value;
48 }
49 }
50
51 return new self($values);
52 }
53
54 public static function createFromPEM(string $pem): self
55 {
56 if (! extension_loaded('openssl')) {
57 throw new RuntimeException('Please install the OpenSSL extension');
58 }
59 $res = openssl_pkey_get_private($pem);
60 if ($res === false) {
61 $res = openssl_pkey_get_public($pem);
62 }
63 if ($res === false) {
64 throw new InvalidArgumentException('Unable to load the key.');
65 }
66
67 $details = openssl_pkey_get_details($res);
68 if (! is_array($details) || ! isset($details['rsa'])) {
69 throw new InvalidArgumentException('Unable to load the key.');
70 }
71
72 return self::createFromKeyDetails($details['rsa']);
73 }
74
75 public static function createFromJWK(JWK $jwk): self
76 {
77 return new self($jwk->all());
78 }
79
80 public function isPublic(): bool
81 {
82 return ! array_key_exists('d', $this->values);
83 }
84
85 public static function toPublic(self $private): self
86 {
87 $data = $private->toArray();
88 $keys = ['p', 'd', 'q', 'dp', 'dq', 'qi'];
89 foreach ($keys as $key) {
90 if (array_key_exists($key, $data)) {
91 unset($data[$key]);
92 }
93 }
94
95 return new self($data);
96 }
97
98 public function toArray(): array
99 {
100 return $this->values;
101 }
102
103 public function toJwk(): JWK
104 {
105 return new JWK($this->values);
106 }
107
108 /**
109 * This method will try to add Chinese Remainder Theorem (CRT) parameters. With those primes, the decryption process
110 * is really fast.
111 */
112 public function optimize(): void
113 {
114 if (array_key_exists('d', $this->values)) {
115 $this->populateCRT();
116 }
117 }
118
119 private function loadJWK(array $jwk): void
120 {
121 if (! array_key_exists('kty', $jwk)) {
122 throw new InvalidArgumentException('The key parameter "kty" is missing.');
123 }
124 if ($jwk['kty'] !== 'RSA') {
125 throw new InvalidArgumentException('The JWK is not a RSA key.');
126 }
127
128 $this->values = $jwk;
129 }
130
131 /**
132 * This method adds Chinese Remainder Theorem (CRT) parameters if primes 'p' and 'q' are available. If 'p' and 'q'
133 * are missing, they are computed and added to the key data.
134 */
135 private function populateCRT(): void
136 {
137 if (! array_key_exists('p', $this->values) && ! array_key_exists('q', $this->values)) {
138 $d = BigInteger::createFromBinaryString(Base64UrlSafe::decodeNoPadding($this->values['d']));
139 $e = BigInteger::createFromBinaryString(Base64UrlSafe::decodeNoPadding($this->values['e']));
140 $n = BigInteger::createFromBinaryString(Base64UrlSafe::decodeNoPadding($this->values['n']));
141
142 [$p, $q] = $this->findPrimeFactors($d, $e, $n);
143 $this->values['p'] = Base64UrlSafe::encodeUnpadded($p->toBytes());
144 $this->values['q'] = Base64UrlSafe::encodeUnpadded($q->toBytes());
145 }
146
147 if (array_key_exists('dp', $this->values) && array_key_exists('dq', $this->values) && array_key_exists(
148 'qi',
149 $this->values
150 )) {
151 return;
152 }
153
154 $one = BigInteger::createFromDecimal(1);
155 $d = BigInteger::createFromBinaryString(Base64UrlSafe::decodeNoPadding($this->values['d']));
156 $p = BigInteger::createFromBinaryString(Base64UrlSafe::decodeNoPadding($this->values['p']));
157 $q = BigInteger::createFromBinaryString(Base64UrlSafe::decodeNoPadding($this->values['q']));
158
159 $this->values['dp'] = Base64UrlSafe::encodeUnpadded($d->mod($p->subtract($one))->toBytes());
160 $this->values['dq'] = Base64UrlSafe::encodeUnpadded($d->mod($q->subtract($one))->toBytes());
161 $this->values['qi'] = Base64UrlSafe::encodeUnpadded($q->modInverse($p)->toBytes());
162 }
163
164 /**
165 * @return BigInteger[]
166 */
167 private function findPrimeFactors(BigInteger $d, BigInteger $e, BigInteger $n): array
168 {
169 $zero = BigInteger::createFromDecimal(0);
170 $one = BigInteger::createFromDecimal(1);
171 $two = BigInteger::createFromDecimal(2);
172
173 $k = $d->multiply($e)
174 ->subtract($one);
175
176 if ($k->isEven()) {
177 $r = $k;
178 $t = $zero;
179
180 do {
181 $r = $r->divide($two);
182 $t = $t->add($one);
183 } while ($r->isEven());
184
185 $found = false;
186 $y = null;
187
188 for ($i = 1; $i <= 100; ++$i) {
189 $g = BigInteger::random($n->subtract($one));
190 $y = $g->modPow($r, $n);
191
192 if ($y->equals($one) || $y->equals($n->subtract($one))) {
193 continue;
194 }
195
196 for ($j = $one; $j->lowerThan($t->subtract($one)); $j = $j->add($one)) {
197 $x = $y->modPow($two, $n);
198
199 if ($x->equals($one)) {
200 $found = true;
201
202 break;
203 }
204
205 if ($x->equals($n->subtract($one))) {
206 continue;
207 }
208
209 $y = $x;
210 }
211
212 $x = $y->modPow($two, $n);
213 if ($x->equals($one)) {
214 $found = true;
215
216 break;
217 }
218 }
219 if ($y === null) {
220 throw new InvalidArgumentException('Unable to find prime factors.');
221 }
222 if ($found === true) {
223 $p = $y->subtract($one)
224 ->gcd($n);
225 $q = $n->divide($p);
226
227 return [$p, $q];
228 }
229 }
230
231 throw new InvalidArgumentException('Unable to find prime factors.');
232 }
233 }