| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Jose\Component\Signature\Algorithm; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | use Jose\Component\Core\JWK; |
| 9 | use Jose\Component\Core\Util\Base64UrlSafe; |
| 10 | use function in_array; |
| 11 | use function is_string; |
| 12 | |
| 13 | abstract class HMAC implements MacAlgorithm |
| 14 | { |
| 15 | public function allowedKeyTypes(): array |
| 16 | { |
| 17 | return ['oct']; |
| 18 | } |
| 19 | |
| 20 | public function verify(JWK $key, string $input, string $signature): bool |
| 21 | { |
| 22 | return hash_equals($this->hash($key, $input), $signature); |
| 23 | } |
| 24 | |
| 25 | public function hash(JWK $key, string $input): string |
| 26 | { |
| 27 | $k = $this->getKey($key); |
| 28 | |
| 29 | return hash_hmac($this->getHashAlgorithm(), $input, $k, true); |
| 30 | } |
| 31 | |
| 32 | protected function getKey(JWK $key): string |
| 33 | { |
| 34 | if (! in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { |
| 35 | throw new InvalidArgumentException('Wrong key type.'); |
| 36 | } |
| 37 | if (! $key->has('k')) { |
| 38 | throw new InvalidArgumentException('The key parameter "k" is missing.'); |
| 39 | } |
| 40 | $k = $key->get('k'); |
| 41 | if (! is_string($k)) { |
| 42 | throw new InvalidArgumentException('The key parameter "k" is invalid.'); |
| 43 | } |
| 44 | |
| 45 | return Base64UrlSafe::decodeNoPadding($k); |
| 46 | } |
| 47 | |
| 48 | abstract protected function getHashAlgorithm(): string; |
| 49 | } |