Key.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Firebase\JWT;
  3. use InvalidArgumentException;
  4. use OpenSSLAsymmetricKey;
  5. use OpenSSLCertificate;
  6. use TypeError;
  7. class Key
  8. {
  9. /** @var string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate */
  10. private $keyMaterial;
  11. /** @var string */
  12. private $algorithm;
  13. /**
  14. * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial
  15. * @param string $algorithm
  16. */
  17. public function __construct(
  18. $keyMaterial,
  19. string $algorithm
  20. ) {
  21. if (
  22. !\is_string($keyMaterial)
  23. && !$keyMaterial instanceof OpenSSLAsymmetricKey
  24. && !$keyMaterial instanceof OpenSSLCertificate
  25. && !\is_resource($keyMaterial)
  26. ) {
  27. throw new TypeError('Key material must be a string, resource, or OpenSSLAsymmetricKey');
  28. }
  29. if (empty($keyMaterial)) {
  30. throw new InvalidArgumentException('Key material must not be empty');
  31. }
  32. if (empty($algorithm)) {
  33. throw new InvalidArgumentException('Algorithm must not be empty');
  34. }
  35. // TODO: Remove in PHP 8.0 in favor of class constructor property promotion
  36. $this->keyMaterial = $keyMaterial;
  37. $this->algorithm = $algorithm;
  38. }
  39. /**
  40. * Return the algorithm valid for this key
  41. *
  42. * @return string
  43. */
  44. public function getAlgorithm(): string
  45. {
  46. return $this->algorithm;
  47. }
  48. /**
  49. * @return string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate
  50. */
  51. public function getKeyMaterial()
  52. {
  53. return $this->keyMaterial;
  54. }
  55. }