Passed
Push — master ( bf6fa9...817f88 )
by Nikolaos
06:58
created

Hmac   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 61
rs 10
c 0
b 0
f 0
wmc 5

4 Methods

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