HMAC::hash()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2019 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Component\Signature\Algorithm;
15
16
use Base64Url\Base64Url;
17
use InvalidArgumentException;
18
use Jose\Component\Core\JWK;
19
20
abstract class HMAC implements MacAlgorithm
21
{
22
    public function allowedKeyTypes(): array
23
    {
24
        return ['oct'];
25
    }
26
27
    public function verify(JWK $key, string $input, string $signature): bool
28
    {
29
        return hash_equals($this->hash($key, $input), $signature);
30
    }
31
32
    public function hash(JWK $key, string $input): string
33
    {
34
        $k = $this->getKey($key);
35
36
        return hash_hmac($this->getHashAlgorithm(), $input, $k, true);
37
    }
38
39
    /**
40
     * @throws InvalidArgumentException if the key is invalid
41
     */
42
    protected 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
55
        return Base64Url::decode($k);
56
    }
57
58
    abstract protected function getHashAlgorithm(): string;
59
}
60