AbstractHmac   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 16
c 2
b 0
f 0
dl 0
loc 63
rs 10
wmc 11

7 Methods

Rating   Name   Duplication   Size   Complexity  
A algorithm() 0 3 1
A kid() 0 3 1
A sign() 0 9 4
A verify() 0 4 2
A name() 0 3 1
A getKey() 0 3 1
A __construct() 0 3 1
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