1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace MiladRahimi\Jwt\Cryptography\Algorithms\Hmac; |
4
|
|
|
|
5
|
|
|
use MiladRahimi\Jwt\Cryptography\Signer; |
6
|
|
|
use MiladRahimi\Jwt\Cryptography\Verifier; |
7
|
|
|
use MiladRahimi\Jwt\Exceptions\InvalidKeyException; |
8
|
|
|
use MiladRahimi\Jwt\Exceptions\InvalidSignatureException; |
9
|
|
|
use MiladRahimi\Jwt\Exceptions\SigningException; |
10
|
|
|
use ValueError; |
11
|
|
|
|
12
|
|
|
abstract class AbstractHmac implements Signer, Verifier |
13
|
|
|
{ |
14
|
|
|
protected static string $name; |
15
|
|
|
|
16
|
|
|
protected string $key; |
17
|
|
|
|
18
|
|
|
protected ?string $kid; |
19
|
|
|
|
20
|
|
|
public function __construct(string $key, ?string $kid = null) |
21
|
|
|
{ |
22
|
|
|
$this->key = $key; |
23
|
|
|
$this->kid = $kid; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @inheritdoc |
28
|
|
|
*/ |
29
|
|
|
public function sign(string $message): string |
30
|
|
|
{ |
31
|
|
|
try { |
32
|
|
|
if (strlen($this->key) < 32 || strlen($this->key) > 6144) { |
33
|
|
|
throw new InvalidKeyException('Key length must be between 32 and 6144'); |
34
|
|
|
} |
35
|
|
|
return hash_hmac($this->algorithm(), $message, "$this->key", 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; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function getKey(): string |
76
|
|
|
{ |
77
|
|
|
return $this->key; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|