|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of the Phalcon Framework. |
|
5
|
|
|
* |
|
6
|
|
|
* For the full copyright and license information, please view the LICENSE.md |
|
7
|
|
|
* file that was distributed with this source code. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
declare(strict_types=1); |
|
11
|
|
|
|
|
12
|
|
|
namespace Phalcon\Http\JWT\Signer; |
|
13
|
|
|
|
|
14
|
|
|
use Phalcon\Http\JWT\Exceptions\UnsupportedAlgorithmException; |
|
15
|
|
|
|
|
16
|
|
|
use function hash_equals; |
|
17
|
|
|
use function hash_hmac; |
|
18
|
|
|
use function str_replace; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Class Hmac |
|
22
|
|
|
*/ |
|
23
|
|
|
class Hmac extends AbstractSigner |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* Hmac constructor. |
|
27
|
|
|
* |
|
28
|
|
|
* @param string $algo |
|
29
|
|
|
* |
|
30
|
|
|
* @throws UnsupportedAlgorithmException |
|
31
|
|
|
*/ |
|
32
|
47 |
|
public function __construct(string $algo = "sha512") |
|
33
|
|
|
{ |
|
34
|
|
|
$supported = [ |
|
35
|
47 |
|
"sha512" => 1, |
|
36
|
|
|
"sha384" => 1, |
|
37
|
|
|
"sha256" => 1, |
|
38
|
|
|
]; |
|
39
|
|
|
|
|
40
|
47 |
|
if (!isset($supported[$algo])) { |
|
41
|
1 |
|
throw new UnsupportedAlgorithmException( |
|
42
|
1 |
|
"Unsupported HMAC algorithm" |
|
43
|
|
|
); |
|
44
|
|
|
}; |
|
45
|
|
|
|
|
46
|
46 |
|
$this->algo = $algo; |
|
47
|
46 |
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Return the value that is used for the "alg" header |
|
51
|
|
|
* |
|
52
|
|
|
* @return string |
|
53
|
|
|
*/ |
|
54
|
42 |
|
public function getAlgHeader(): string |
|
55
|
|
|
{ |
|
56
|
42 |
|
return "HS" . str_replace("sha", "", $this->algo); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Sign a payload using the passphrase |
|
61
|
|
|
* |
|
62
|
|
|
* @param string $payload |
|
63
|
|
|
* @param string $passphrase |
|
64
|
|
|
* |
|
65
|
|
|
* @return string |
|
66
|
|
|
*/ |
|
67
|
25 |
|
public function sign(string $payload, string $passphrase): string |
|
68
|
|
|
{ |
|
69
|
25 |
|
return hash_hmac($this->getAlgorithm(), $payload, $passphrase, true); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* Verify a passed source with a payload and passphrase |
|
74
|
|
|
* |
|
75
|
|
|
* @param string $source |
|
76
|
|
|
* @param string $payload |
|
77
|
|
|
* @param string $passphrase |
|
78
|
|
|
* |
|
79
|
|
|
* @return bool |
|
80
|
|
|
*/ |
|
81
|
3 |
|
public function verify(string $source, string $payload, string $passphrase): bool |
|
82
|
|
|
{ |
|
83
|
3 |
|
return hash_equals($source, $this->sign($payload, $passphrase)); |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|