2019-08-01 14:47:12 +05:30
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace api\components\Tokens\Algorithms;
|
|
|
|
|
|
|
|
use Lcobucci\JWT\Signer;
|
|
|
|
use Lcobucci\JWT\Signer\Ecdsa\Sha256;
|
|
|
|
use Lcobucci\JWT\Signer\Key;
|
2024-12-02 15:40:55 +05:30
|
|
|
use Lcobucci\JWT\Signer\Key\InMemory;
|
2019-08-01 14:47:12 +05:30
|
|
|
|
2024-06-14 06:33:10 +05:30
|
|
|
final class ES256 implements AlgorithmInterface {
|
2019-08-01 14:47:12 +05:30
|
|
|
|
2024-06-14 06:33:10 +05:30
|
|
|
private ?Key $privateKey = null;
|
2019-08-01 14:47:12 +05:30
|
|
|
|
2024-06-14 06:33:10 +05:30
|
|
|
private ?Key $publicKey = null;
|
2019-08-01 14:47:12 +05:30
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
private readonly Sha256 $signer;
|
2019-08-01 14:47:12 +05:30
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function __construct(
|
|
|
|
private readonly string $privateKeyPath,
|
|
|
|
private readonly ?string $privateKeyPass = null,
|
|
|
|
) {
|
2024-06-14 06:33:10 +05:30
|
|
|
$this->signer = new Sha256();
|
2019-08-01 14:47:12 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function getSigner(): Signer {
|
2024-06-14 06:33:10 +05:30
|
|
|
return $this->signer;
|
2019-08-01 14:47:12 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function getPrivateKey(): Key {
|
2024-06-14 06:33:10 +05:30
|
|
|
if ($this->privateKey === null) {
|
2024-12-02 15:40:55 +05:30
|
|
|
$this->privateKey = InMemory::plainText($this->privateKeyPath, $this->privateKeyPass ?? '');
|
2019-08-01 14:47:12 +05:30
|
|
|
}
|
|
|
|
|
2024-06-14 06:33:10 +05:30
|
|
|
return $this->privateKey;
|
2019-08-01 14:47:12 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
public function getPublicKey(): Key {
|
2024-06-14 06:33:10 +05:30
|
|
|
if ($this->publicKey === null) {
|
|
|
|
$privateKey = $this->getPrivateKey();
|
2024-12-02 15:40:55 +05:30
|
|
|
$privateKeyOpenSSL = openssl_pkey_get_private($privateKey->contents(), $privateKey->passphrase());
|
2024-06-14 06:33:10 +05:30
|
|
|
$publicPem = openssl_pkey_get_details($privateKeyOpenSSL)['key'];
|
2024-12-02 15:40:55 +05:30
|
|
|
$this->publicKey = InMemory::plainText($publicPem);
|
2019-08-01 14:47:12 +05:30
|
|
|
}
|
|
|
|
|
2024-06-14 06:33:10 +05:30
|
|
|
return $this->publicKey;
|
2019-08-01 14:47:12 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
}
|