Completed
Push — master ( bc7d7f...7a9596 )
by Théo
02:46
created

Hash::update()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Signature;
16
17
use KevinGH\Box\Exception\SignatureException;
18
19
/**
20
 * Uses the PHP hash library to verify a signature.
21
 *
22
 * @author Kevin Herrera <[email protected]>
23
 */
24
class Hash implements VerifyInterface
25
{
26
    /**
27
     * The hash context.
28
     *
29
     * @var resource
30
     */
31
    private $context;
32
33
    /**
34
     * @see VerifyInterface::init
35
     *
36
     * @param mixed $algorithm
37
     * @param mixed $path
38
     */
39
    public function init($algorithm, $path): void
40
    {
41
        $algorithm = strtolower(
42
            preg_replace(
43
                '/[^A-Za-z0-9]+/',
44
                '',
45
                $algorithm
46
            )
47
        );
48
49
        if (false === ($this->context = @hash_init($algorithm))) {
50
            $this->context = null;
51
52
            throw SignatureException::lastError();
53
        }
54
    }
55
56
    /**
57
     * @see VerifyInterface::update
58
     *
59
     * @param mixed $data
60
     */
61
    public function update($data): void
62
    {
63
        hash_update($this->context, $data);
64
    }
65
66
    /**
67
     * @see VerifyInterface::verify
68
     *
69
     * @param mixed $signature
70
     */
71
    public function verify($signature)
72
    {
73
        return $signature === strtoupper(hash_final($this->context));
74
    }
75
}
76