|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Jose\Component\Signature\Algorithm; |
| 6 | + |
| 7 | +use function in_array; |
| 8 | +use InvalidArgumentException; |
| 9 | +use function is_string; |
| 10 | +use Jose\Component\Core\JWK; |
| 11 | +use ParagonIE\ConstantTime\Base64UrlSafe; |
| 12 | + |
| 13 | +/** |
| 14 | + * @see \Jose\Tests\Component\Signature\Algorithm\Blake2bTest |
| 15 | + */ |
| 16 | +final class Blake2b implements MacAlgorithm |
| 17 | +{ |
| 18 | + private const MINIMUM_KEY_LENGTH = 32; |
| 19 | + |
| 20 | + public function allowedKeyTypes(): array |
| 21 | + { |
| 22 | + return ['oct']; |
| 23 | + } |
| 24 | + |
| 25 | + public function name(): string |
| 26 | + { |
| 27 | + return 'BLAKE2B'; |
| 28 | + } |
| 29 | + |
| 30 | + public function verify(JWK $key, string $input, string $signature): bool |
| 31 | + { |
| 32 | + return hash_equals($this->hash($key, $input), $signature); |
| 33 | + } |
| 34 | + |
| 35 | + public function hash(JWK $key, string $input): string |
| 36 | + { |
| 37 | + $k = $this->getKey($key); |
| 38 | + |
| 39 | + return sodium_crypto_generichash($input, $k); |
| 40 | + } |
| 41 | + |
| 42 | + private function getKey(JWK $key): string |
| 43 | + { |
| 44 | + if (! in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { |
| 45 | + throw new InvalidArgumentException('Wrong key type.'); |
| 46 | + } |
| 47 | + if (! $key->has('k')) { |
| 48 | + throw new InvalidArgumentException('The key parameter "k" is missing.'); |
| 49 | + } |
| 50 | + $k = $key->get('k'); |
| 51 | + if (! is_string($k)) { |
| 52 | + throw new InvalidArgumentException('The key parameter "k" is invalid.'); |
| 53 | + } |
| 54 | + $key = Base64UrlSafe::decode($k); |
| 55 | + if (mb_strlen($key, '8bit') < self::MINIMUM_KEY_LENGTH) { |
| 56 | + throw new InvalidArgumentException('Key provided is shorter than 256 bits.'); |
| 57 | + } |
| 58 | + |
| 59 | + return $key; |
| 60 | + } |
| 61 | +} |
0 commit comments