| 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\Output\OutputInterface; |
| 14 | use function is_array; |
| 15 | use function is_string; |
| 16 | |
| 17 | #[AsCommand( |
| 18 | name: 'key:convert:public', |
| 19 | description: 'Convert a private key into public key. Symmetric keys (shared keys) are not changed.', |
| 20 | )] |
| 21 | final class PublicKeyCommand extends ObjectOutputCommand |
| 22 | { |
| 23 | protected static $defaultName = 'key:convert:public'; |
| 24 | |
| 25 | protected static $defaultDescription = 'Convert a private key into public key. Symmetric keys (shared keys) are not changed.'; |
| 26 | |
| 27 | protected function configure(): void |
| 28 | { |
| 29 | parent::configure(); |
| 30 | $this->setHelp('This command converts a private key into a public key.') |
| 31 | ->addArgument('jwk', InputArgument::REQUIRED, 'The JWK object'); |
| 32 | } |
| 33 | |
| 34 | protected function execute(InputInterface $input, OutputInterface $output): int |
| 35 | { |
| 36 | $jwk = $this->getKey($input); |
| 37 | $jwk = $jwk->toPublic(); |
| 38 | |
| 39 | $this->prepareJsonOutput($input, $output, $jwk); |
| 40 | |
| 41 | return self::SUCCESS; |
| 42 | } |
| 43 | |
| 44 | private function getKey(InputInterface $input): JWK |
| 45 | { |
| 46 | $jwk = $input->getArgument('jwk'); |
| 47 | if (! is_string($jwk)) { |
| 48 | throw new InvalidArgumentException('Invalid JWK'); |
| 49 | } |
| 50 | $json = JsonConverter::decode($jwk); |
| 51 | if (! is_array($json)) { |
| 52 | throw new InvalidArgumentException('Invalid JWK'); |
| 53 | } |
| 54 | |
| 55 | return new JWK($json); |
| 56 | } |
| 57 | } |