| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Jose\Component\Console; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | use Jose\Component\Core\JWK; |
| 9 | use Jose\Component\Core\Util\JsonConverter; |
| 10 | use Symfony\Component\Console\Attribute\AsCommand; |
| 11 | use Symfony\Component\Console\Input\InputArgument; |
| 12 | use Symfony\Component\Console\Input\InputInterface; |
| 13 | use Symfony\Component\Console\Input\InputOption; |
| 14 | use Symfony\Component\Console\Output\OutputInterface; |
| 15 | use function is_array; |
| 16 | use function is_string; |
| 17 | |
| 18 | #[AsCommand(name: 'key:thumbprint', description: 'Get the thumbprint of a JWK key.',)] |
| 19 | final class GetThumbprintCommand extends ObjectOutputCommand |
| 20 | { |
| 21 | protected static $defaultName = 'key:thumbprint'; |
| 22 | |
| 23 | protected static $defaultDescription = 'Get the thumbprint of a JWK key.'; |
| 24 | |
| 25 | protected function configure(): void |
| 26 | { |
| 27 | parent::configure(); |
| 28 | $this->addArgument('jwk', InputArgument::REQUIRED, 'The JWK key.') |
| 29 | ->addOption('hash', null, InputOption::VALUE_OPTIONAL, 'The hashing algorithm.', 'sha256'); |
| 30 | } |
| 31 | |
| 32 | protected function execute(InputInterface $input, OutputInterface $output): int |
| 33 | { |
| 34 | $jwk = $input->getArgument('jwk'); |
| 35 | if (! is_string($jwk)) { |
| 36 | throw new InvalidArgumentException('Invalid JWK'); |
| 37 | } |
| 38 | $hash = $input->getOption('hash'); |
| 39 | if (! is_string($hash)) { |
| 40 | throw new InvalidArgumentException('Invalid hash algorithm'); |
| 41 | } |
| 42 | $json = JsonConverter::decode($jwk); |
| 43 | if (! is_array($json)) { |
| 44 | throw new InvalidArgumentException('Invalid input.'); |
| 45 | } |
| 46 | $key = new JWK($json); |
| 47 | $output->write($key->thumbprint($hash)); |
| 48 | |
| 49 | return self::SUCCESS; |
| 50 | } |
| 51 | } |