Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/KeyManagement/Analyzer/RsaAnalyzer.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\KeyManagement\Analyzer;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\JWK;
9 use Jose\Component\Core\Util\Base64UrlSafe;
10 use function is_array;
11 use function is_string;
12
13 final class RsaAnalyzer implements KeyAnalyzer
14 {
15 public function analyze(JWK $jwk, MessageBag $bag): void
16 {
17 if ($jwk->get('kty') !== 'RSA') {
18 return;
19 }
20
21 $this->checkExponent($jwk, $bag);
22 $this->checkModulus($jwk, $bag);
23 }
24
25 private function checkExponent(JWK $jwk, MessageBag $bag): void
26 {
27 $e = $jwk->get('e');
28 if (! is_string($e)) {
29 $bag->add(Message::high('The exponent is not valid.'));
30
31 return;
32 }
33 $exponent = unpack('l', str_pad(Base64UrlSafe::decodeNoPadding($e), 4, "\0"));
34 if (! is_array($exponent) || ! isset($exponent[1])) {
35 throw new InvalidArgumentException('Unable to get the private key');
36 }
37 if ($exponent[1] < 65537) {
38 $bag->add(Message::high('The exponent is too low. It should be at least 65537.'));
39 }
40 }
41
42 private function checkModulus(JWK $jwk, MessageBag $bag): void
43 {
44 $n = $jwk->get('n');
45 if (! is_string($n)) {
46 $bag->add(Message::high('The modulus is not valid.'));
47
48 return;
49 }
50 $n = 8 * mb_strlen(Base64UrlSafe::decodeNoPadding($n), '8bit');
51 if ($n < 2048) {
52 $bag->add(Message::high('The key length is less than 2048 bits.'));
53 }
54 if ($jwk->has('d') && (! $jwk->has('p') || ! $jwk->has('q') || ! $jwk->has('dp') || ! $jwk->has(
55 'dq'
56 ) || ! $jwk->has('qi'))) {
57 $bag->add(
58 Message::medium(
59 'The key is a private RSA key, but Chinese Remainder Theorem primes are missing. These primes are not mandatory, but signatures and decryption processes are faster when available.'
60 )
61 );
62 }
63 }
64 }