[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/libraries/vendor/web-token/jwt-signature-algorithm-rsa/ -> RSAPKCS1.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 in_array;
  17  use InvalidArgumentException;
  18  use Jose\Component\Core\JWK;
  19  use Jose\Component\Core\Util\RSAKey;
  20  use RuntimeException;
  21  
  22  abstract class RSAPKCS1 implements SignatureAlgorithm
  23  {
  24      public function allowedKeyTypes(): array
  25      {
  26          return ['RSA'];
  27      }
  28  
  29      public function verify(JWK $key, string $input, string $signature): bool
  30      {
  31          $this->checkKey($key);
  32          $pub = RSAKey::createFromJWK($key->toPublic());
  33  
  34          return 1 === openssl_verify($input, $signature, $pub->toPEM(), $this->getAlgorithm());
  35      }
  36  
  37      /**
  38       * @throws InvalidArgumentException if the key is not private
  39       * @throws InvalidArgumentException if the data cannot be signed
  40       */
  41      public function sign(JWK $key, string $input): string
  42      {
  43          $this->checkKey($key);
  44          if (!$key->has('d')) {
  45              throw new InvalidArgumentException('The key is not a private key.');
  46          }
  47  
  48          $priv = RSAKey::createFromJWK($key);
  49  
  50          $result = openssl_sign($input, $signature, $priv->toPEM(), $this->getAlgorithm());
  51          if (true !== $result) {
  52              throw new RuntimeException('Unable to sign');
  53          }
  54  
  55          return $signature;
  56      }
  57  
  58      abstract protected function getAlgorithm(): string;
  59  
  60      /**
  61       * @throws InvalidArgumentException if the key type is not allowed
  62       * @throws InvalidArgumentException if the key is not valid
  63       */
  64      private function checkKey(JWK $key): void
  65      {
  66          if (!in_array($key->get('kty'), $this->allowedKeyTypes(), true)) {
  67              throw new InvalidArgumentException('Wrong key type.');
  68          }
  69          foreach (['n', 'e'] as $k) {
  70              if (!$key->has($k)) {
  71                  throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k));
  72              }
  73          }
  74      }
  75  }


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