Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Core/Util/RSAKey.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Core\Util;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\JWK;
9 use RuntimeException;
10 use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
11 use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString;
12 use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
13 use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
14 use SpomkyLabs\Pki\CryptoEncoding\PEM;
15 use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Asymmetric\RSAEncryptionAlgorithmIdentifier;
16 use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RSA\RSAPrivateKey;
17 use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RSA\RSAPublicKey;
18 use function array_key_exists;
19 use function count;
20 use function is_array;
21
22 /**
23 * @internal
24 */
25 final class RSAKey
26 {
27 private null|Sequence $sequence = null;
28
29 private readonly array $values;
30
31 private BigInteger $modulus;
32
33 private int $modulus_length;
34
35 private BigInteger $public_exponent;
36
37 private ?BigInteger $private_exponent = null;
38
39 /**
40 * @var BigInteger[]
41 */
42 private array $primes = [];
43
44 /**
45 * @var BigInteger[]
46 */
47 private array $exponents = [];
48
49 private ?BigInteger $coefficient = null;
50
51 private function __construct(JWK $data)
52 {
53 $this->values = $data->all();
54 $this->populateBigIntegers();
55 }
56
57 public static function createFromJWK(JWK $jwk): self
58 {
59 return new self($jwk);
60 }
61
62 public function getModulus(): BigInteger
63 {
64 return $this->modulus;
65 }
66
67 public function getModulusLength(): int
68 {
69 return $this->modulus_length;
70 }
71
72 public function getExponent(): BigInteger
73 {
74 $d = $this->getPrivateExponent();
75 if ($d !== null) {
76 return $d;
77 }
78
79 return $this->getPublicExponent();
80 }
81
82 public function getPublicExponent(): BigInteger
83 {
84 return $this->public_exponent;
85 }
86
87 public function getPrivateExponent(): ?BigInteger
88 {
89 return $this->private_exponent;
90 }
91
92 /**
93 * @return BigInteger[]
94 */
95 public function getPrimes(): array
96 {
97 return $this->primes;
98 }
99
100 /**
101 * @return BigInteger[]
102 */
103 public function getExponents(): array
104 {
105 return $this->exponents;
106 }
107
108 public function getCoefficient(): ?BigInteger
109 {
110 return $this->coefficient;
111 }
112
113 public function isPublic(): bool
114 {
115 return ! array_key_exists('d', $this->values);
116 }
117
118 public static function toPublic(self $private): self
119 {
120 $data = $private->toArray();
121 $keys = ['p', 'd', 'q', 'dp', 'dq', 'qi'];
122 foreach ($keys as $key) {
123 if (array_key_exists($key, $data)) {
124 unset($data[$key]);
125 }
126 }
127
128 return new self(new JWK($data));
129 }
130
131 public function toArray(): array
132 {
133 return $this->values;
134 }
135
136 public function toPEM(): string
137 {
138 if (array_key_exists('d', $this->values)) {
139 $this->sequence = Sequence::create(
140 Integer::create(0),
141 RSAEncryptionAlgorithmIdentifier::create()->toASN1(),
142 OctetString::create(
143 RSAPrivateKey::create(
144 $this->fromBase64ToInteger($this->values['n']),
145 $this->fromBase64ToInteger($this->values['e']),
146 $this->fromBase64ToInteger($this->values['d']),
147 isset($this->values['p']) ? $this->fromBase64ToInteger($this->values['p']) : '0',
148 isset($this->values['q']) ? $this->fromBase64ToInteger($this->values['q']) : '0',
149 isset($this->values['dp']) ? $this->fromBase64ToInteger($this->values['dp']) : '0',
150 isset($this->values['dq']) ? $this->fromBase64ToInteger($this->values['dq']) : '0',
151 isset($this->values['qi']) ? $this->fromBase64ToInteger($this->values['qi']) : '0',
152 )->toDER()
153 )
154 );
155
156 return PEM::create(PEM::TYPE_PRIVATE_KEY, $this->sequence->toDER())
157 ->string();
158 }
159 $this->sequence = Sequence::create(
160 RSAEncryptionAlgorithmIdentifier::create()->toASN1(),
161 BitString::create(
162 RSAPublicKey::create(
163 $this->fromBase64ToInteger($this->values['n']),
164 $this->fromBase64ToInteger($this->values['e'])
165 )->toDER()
166 )
167 );
168
169 return PEM::create(PEM::TYPE_PUBLIC_KEY, $this->sequence->toDER())
170 ->string();
171 }
172
173 /**
174 * Exponentiate with or without Chinese Remainder Theorem. Operation with primes 'p' and 'q' is appox. 2x faster.
175 */
176 public static function exponentiate(self $key, BigInteger $c): BigInteger
177 {
178 if ($c->compare(BigInteger::createFromDecimal(0)) < 0 || $c->compare($key->getModulus()) > 0) {
179 throw new RuntimeException();
180 }
181 if ($key->isPublic() || $key->getCoefficient() === null || count($key->getPrimes()) === 0 || count(
182 $key->getExponents()
183 ) === 0) {
184 return $c->modPow($key->getExponent(), $key->getModulus());
185 }
186
187 $p = $key->getPrimes()[0];
188 $q = $key->getPrimes()[1];
189 $dP = $key->getExponents()[0];
190 $dQ = $key->getExponents()[1];
191 $qInv = $key->getCoefficient();
192
193 $m1 = $c->modPow($dP, $p);
194 $m2 = $c->modPow($dQ, $q);
195 $h = $qInv->multiply($m1->subtract($m2)->add($p))
196 ->mod($p);
197
198 return $m2->add($h->multiply($q));
199 }
200
201 private function populateBigIntegers(): void
202 {
203 $this->modulus = $this->convertBase64StringToBigInteger($this->values['n']);
204 $this->modulus_length = mb_strlen($this->getModulus()->toBytes(), '8bit');
205 $this->public_exponent = $this->convertBase64StringToBigInteger($this->values['e']);
206
207 if (! $this->isPublic()) {
208 $this->private_exponent = $this->convertBase64StringToBigInteger($this->values['d']);
209
210 if (array_key_exists('p', $this->values) && array_key_exists('q', $this->values)) {
211 $this->primes = [
212 $this->convertBase64StringToBigInteger($this->values['p']),
213 $this->convertBase64StringToBigInteger($this->values['q']),
214 ];
215 if (array_key_exists('dp', $this->values) && array_key_exists('dq', $this->values) && array_key_exists(
216 'qi',
217 $this->values
218 )) {
219 $this->exponents = [
220 $this->convertBase64StringToBigInteger($this->values['dp']),
221 $this->convertBase64StringToBigInteger($this->values['dq']),
222 ];
223 $this->coefficient = $this->convertBase64StringToBigInteger($this->values['qi']);
224 }
225 }
226 }
227 }
228
229 private function convertBase64StringToBigInteger(string $value): BigInteger
230 {
231 return BigInteger::createFromBinaryString(Base64UrlSafe::decodeNoPadding($value));
232 }
233
234 private function fromBase64ToInteger(string $value): string
235 {
236 $unpacked = unpack('H*', Base64UrlSafe::decodeNoPadding($value));
237 if (! is_array($unpacked) || count($unpacked) === 0) {
238 throw new InvalidArgumentException('Unable to get the private key');
239 }
240
241 return \Brick\Math\BigInteger::fromBase(current($unpacked), 16)->toBase(10);
242 }
243 }