Passed
Push — master ( 85c6cc...2afdeb )
by Nikolaos
04:50 queued 10s
created

Hmac::getHash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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