Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Signature/Algorithm/ECDSA.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Signature\Algorithm;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\JWK;
9 use Jose\Component\Core\Util\ECKey;
10 use Jose\Component\Core\Util\ECSignature;
11 use LogicException;
12 use RuntimeException;
13 use Throwable;
14 use function defined;
15 use function extension_loaded;
16 use function in_array;
17
18 abstract class ECDSA implements SignatureAlgorithm
19 {
20 public function __construct()
21 {
22 if (! extension_loaded('openssl')) {
23 throw new RuntimeException('Please install the OpenSSL extension');
24 }
25 if (! defined('OPENSSL_KEYTYPE_EC')) {
26 throw new LogicException('Elliptic Curve key type not supported by your environment.');
27 }
28 }
29
30 public function allowedKeyTypes(): array
31 {
32 return ['EC'];
33 }
34
35 public function sign(JWK $key, string $input): string
36 {
37 $this->checkKey($key);
38 if (! $key->has('d')) {
39 throw new InvalidArgumentException('The EC key is not private');
40 }
41 $pem = ECKey::convertPrivateKeyToPEM($key);
42 openssl_sign($input, $signature, $pem, $this->getHashAlgorithm());
43
44 return ECSignature::fromAsn1($signature, $this->getSignaturePartLength());
45 }
46
47 public function verify(JWK $key, string $input, string $signature): bool
48 {
49 $this->checkKey($key);
50
51 try {
52 $der = ECSignature::toAsn1($signature, $this->getSignaturePartLength());
53 $pem = ECKey::convertPublicKeyToPEM($key);
54
55 return openssl_verify($input, $der, $pem, $this->getHashAlgorithm()) === 1;
56 } catch (Throwable) {
57 return false;
58 }
59 }
60
61 abstract protected function getHashAlgorithm(): string;
62
63 abstract protected function getSignaturePartLength(): int;
64
65 private function checkKey(JWK $key): void
66 {
67 if (! in_array($key->get('kty'), $this->allowedKeyTypes(), true)) {
68 throw new InvalidArgumentException('Wrong key type.');
69 }
70 foreach (['x', 'y', 'crv'] as $k) {
71 if (! $key->has($k)) {
72 throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k));
73 }
74 }
75 }
76 }