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