AbstractHmac::algorithm()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MiladRahimi\Jwt\Cryptography\Algorithms\Hmac;
6
7
use MiladRahimi\Jwt\Cryptography\Keys\HmacKey;
8
use MiladRahimi\Jwt\Cryptography\Signer;
9
use MiladRahimi\Jwt\Cryptography\Verifier;
10
use MiladRahimi\Jwt\Exceptions\InvalidKeyException;
11
use MiladRahimi\Jwt\Exceptions\InvalidSignatureException;
12
use MiladRahimi\Jwt\Exceptions\SigningException;
13
use ValueError;
14
15
abstract class AbstractHmac implements Signer, Verifier
16
{
17
    protected static string $name;
18
19
    protected HmacKey $key;
20
21
    public function __construct(HmacKey $key)
22
    {
23
        $this->key = $key;
24
    }
25
26
    /**
27
     * @inheritdoc
28
     */
29
    public function sign(string $message): string
30
    {
31
        try {
32
            if (strlen($this->key->getContent()) < 32 || strlen($this->key->getContent()) > 6144) {
33
                throw new InvalidKeyException('Key length must be between 32 and 6144.');
34
            }
35
            return hash_hmac($this->algorithm(), $message, $this->key->getContent(), true);
36
        } catch (ValueError | InvalidKeyException $e) {
37
            throw new SigningException('Cannot sign the signature.', 0, $e);
38
        }
39
    }
40
41
    /**
42
     * @inheritDoc
43
     */
44
    public function verify(string $plain, string $signature): void
45
    {
46
        if ($signature !== $this->sign($plain)) {
47
            throw new InvalidSignatureException();
48
        }
49
    }
50
51
    /**
52
     * Generate algorithm name based on the key name
53
     */
54
    protected function algorithm(): string
55
    {
56
        return 'sha' . substr($this->name(), 2);
57
    }
58
59
    /**
60
     * @inheritDoc
61
     */
62
    public function name(): string
63
    {
64
        return static::$name;
65
    }
66
67
    /**
68
     * @inheritDoc
69
     */
70
    public function kid(): ?string
71
    {
72
        return $this->key->getId();
73
    }
74
75
    public function getKey(): HmacKey
76
    {
77
        return $this->key;
78
    }
79
}
80