[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/libraries/vendor/web-token/jwt-signature-algorithm-ecdsa/ -> ECDSA.php (source)

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


Generated: Wed Sep 7 05:41:13 2022 Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer