| 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\ECKey; |
| 10 | use Jose\Component\Core\Util\JsonConverter; |
| 11 | use Jose\Component\Core\Util\RSAKey; |
| 12 | use Symfony\Component\Console\Attribute\AsCommand; |
| 13 | use Symfony\Component\Console\Input\InputArgument; |
| 14 | use Symfony\Component\Console\Input\InputInterface; |
| 15 | use Symfony\Component\Console\Output\OutputInterface; |
| 16 | use function is_array; |
| 17 | use function is_string; |
| 18 | |
| 19 | #[AsCommand(name: 'key:convert:pkcs1', description: 'Converts a RSA or EC key into PKCS#1 key.',)] |
| 20 | final class PemConverterCommand extends ObjectOutputCommand |
| 21 | { |
| 22 | protected static $defaultName = 'key:convert:pkcs1'; |
| 23 | |
| 24 | protected static $defaultDescription = 'Converts a RSA or EC key into PKCS#1 key.'; |
| 25 | |
| 26 | protected function configure(): void |
| 27 | { |
| 28 | parent::configure(); |
| 29 | $this->addArgument('jwk', InputArgument::REQUIRED, 'The key'); |
| 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 | $json = JsonConverter::decode($jwk); |
| 39 | if (! is_array($json)) { |
| 40 | throw new InvalidArgumentException('Invalid JWK.'); |
| 41 | } |
| 42 | $key = new JWK($json); |
| 43 | |
| 44 | $pem = match ($key->get('kty')) { |
| 45 | 'RSA' => RSAKey::createFromJWK($key)->toPEM(), |
| 46 | 'EC' => ECKey::convertToPEM($key), |
| 47 | default => throw new InvalidArgumentException('Not a RSA or EC key.'), |
| 48 | }; |
| 49 | $output->write($pem); |
| 50 | |
| 51 | return self::SUCCESS; |
| 52 | } |
| 53 | } |