<?php
 declare(strict_types=1); namespace SpomkyLabs\Pki\CryptoTypes\Asymmetric; use SpomkyLabs\Pki\CryptoEncoding\PEM; use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\AlgorithmIdentifierType; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\EC\ECPrivateKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RSA\RSAPrivateKey; use UnexpectedValueException; abstract class PrivateKey { abstract public function algorithmIdentifier(): AlgorithmIdentifierType; abstract public function publicKey(): PublicKey; abstract public function toDER(): string; abstract public function toPEM(): PEM; public function privateKeyData(): string { return $this->toDER(); } public function privateKeyInfo(): PrivateKeyInfo { return PrivateKeyInfo::fromPrivateKey($this); } public static function fromPEM(PEM $pem) { return match ($pem->type()) { PEM::TYPE_RSA_PRIVATE_KEY => RSAPrivateKey::fromDER($pem->data()), PEM::TYPE_EC_PRIVATE_KEY => ECPrivateKey::fromDER($pem->data()), PEM::TYPE_PRIVATE_KEY => PrivateKeyInfo::fromDER($pem->data())->privateKey(), default => throw new UnexpectedValueException('PEM type ' . $pem->type() . ' is not a valid private key.'), }; } } 