diff --git a/src/Exception/CreateKeyException.php b/src/Exception/CreateKeyException.php new file mode 100644 index 0000000..6ecb6c2 --- /dev/null +++ b/src/Exception/CreateKeyException.php @@ -0,0 +1,8 @@ +privateKey = \openssl_pkey_get_private('file://' . $privateKey); - $this->publicKey = \openssl_pkey_get_public('file://' . $publicKey); + $this->privateKeyFile = $privateKey; + $this->publicKeyFile = $publicKey; } + /** + * @throws \Pd\PublicAccess\Exception\CreateKeyException + */ public function create(\Pd\PublicAccess\PublicAccess $object): string { - return \Firebase\JWT\JWT::encode($object->jsonSerialize(), $this->privateKey, self::ALGORITHM); + return \Firebase\JWT\JWT::encode($object->jsonSerialize(), $this->privateKey(), self::ALGORITHM); } + /** + * @throws \Pd\PublicAccess\Exception\CreateKeyException + */ public function decode(string $token): \stdClass { /** @var \stdClass $decode */ - $decode = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key($this->publicKey, self::ALGORITHM)); + $decode = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key($this->publicKey(), self::ALGORITHM)); return $decode; } + + /** + * @return mixed + * @throws \Pd\PublicAccess\Exception\CreateKeyException + */ + #[\ReturnTypeWillChange] + private function privateKey() + { + if ($this->privateKey === NULL) { + $privateKey = \openssl_pkey_get_private('file://' . $this->privateKeyFile); + + if ($privateKey === FALSE) { + throw new \Pd\PublicAccess\Exception\CreateKeyException('Invalid private key for JWT tokenizer'); + } + + $this->privateKey = $privateKey; + } + + return $this->privateKey; + } + + + /** + * @return mixed + * @throws \Pd\PublicAccess\Exception\CreateKeyException + */ + #[\ReturnTypeWillChange] + private function publicKey() + { + if ($this->publicKey === NULL) { + $publicKey = \openssl_pkey_get_public('file://' . $this->publicKeyFile); + + if ($publicKey === FALSE) { + throw new \Pd\PublicAccess\Exception\CreateKeyException('Invalid public key for JWT tokenizer'); + } + + $this->publicKey = $publicKey; + } + + return $this->publicKey; + } + }