| 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\RSAKey; |
| 10 | use RuntimeException; |
| 11 | use function extension_loaded; |
| 12 | use function in_array; |
| 13 | |
| 14 | abstract class RSAPKCS1 implements SignatureAlgorithm |
| 15 | { |
| 16 | public function __construct() |
| 17 | { |
| 18 | if (! extension_loaded('openssl')) { |
| 19 | throw new RuntimeException('Please install the OpenSSL extension'); |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | public function allowedKeyTypes(): array |
| 24 | { |
| 25 | return ['RSA']; |
| 26 | } |
| 27 | |
| 28 | public function verify(JWK $key, string $input, string $signature): bool |
| 29 | { |
| 30 | $this->checkKey($key); |
| 31 | $pub = RSAKey::createFromJWK($key->toPublic()); |
| 32 | |
| 33 | return openssl_verify($input, $signature, $pub->toPEM(), $this->getAlgorithm()) === 1; |
| 34 | } |
| 35 | |
| 36 | public function sign(JWK $key, string $input): string |
| 37 | { |
| 38 | $this->checkKey($key); |
| 39 | if (! $key->has('d')) { |
| 40 | throw new InvalidArgumentException('The key is not a private key.'); |
| 41 | } |
| 42 | |
| 43 | $priv = RSAKey::createFromJWK($key); |
| 44 | |
| 45 | $result = openssl_sign($input, $signature, $priv->toPEM(), $this->getAlgorithm()); |
| 46 | if ($result !== true) { |
| 47 | throw new RuntimeException('Unable to sign'); |
| 48 | } |
| 49 | |
| 50 | return $signature; |
| 51 | } |
| 52 | |
| 53 | abstract protected function getAlgorithm(): string; |
| 54 | |
| 55 | private function checkKey(JWK $key): void |
| 56 | { |
| 57 | if (! in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { |
| 58 | throw new InvalidArgumentException('Wrong key type.'); |
| 59 | } |
| 60 | foreach (['n', 'e'] as $k) { |
| 61 | if (! $key->has($k)) { |
| 62 | throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k)); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |