diff --git a/src/JWT.php b/src/JWT.php index e9d75639..cb3579ab 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -185,8 +185,8 @@ public static function decode( * Converts and signs a PHP array into a JWT string. * * @param array $payload PHP array - * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. - * @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256', + * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate|Key $key The secret key. + * @param ?string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256', * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' * @param string $keyId * @param array $head An array with header elements to attach @@ -199,10 +199,16 @@ public static function decode( public static function encode( array $payload, $key, - string $alg, + ?string $alg = null, string $keyId = null, array $head = null ): string { + if (is_a($key, Key::class)) { + $alg = $key->getAlgorithm(); + $key = $key->getKeyMaterial(); + } elseif ($alg === null) { + throw new InvalidArgumentException('alg cannot be null unless key is instance of Key'); + } $header = ['typ' => 'JWT']; if (isset($head) && \is_array($head)) { $header = \array_merge($header, $head); @@ -226,8 +232,8 @@ public static function encode( * Sign a string with a given key and algorithm. * * @param string $msg The message to sign - * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. - * @param string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256', + * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate|Key $key The secret key. + * @param ?string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256', * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' * * @return string An encrypted message @@ -237,8 +243,14 @@ public static function encode( public static function sign( string $msg, $key, - string $alg + ?string $alg = null ): string { + if (is_a($key, Key::class)) { + $alg = $key->getAlgorithm(); + $key = $key->getKeyMaterial(); + } elseif ($alg === null) { + throw new InvalidArgumentException('alg cannot be null unless key is instance of Key'); + } if (empty(static::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); }