Completed
Push — master ( 01e786...1268b6 )
by Dan
03:36
created

HashHmac::setPrivateKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Ds\Authenticate;
4
5
/**
6
 * Hmac hashing functions.
7
 *
8
 * PHP version 5
9
 *
10
 * @package Ds\Authenticate
11
 * @author  Dan Smith <[email protected]>
12
 * @license MIT
13
 * @license https://opensource.org/licenses/MIT
14
 * @version v0.0.1
15
 * @link    https://github.com/djsmithme/Authenticate
16
 */
17
class HashHmac
18
{
19
20
    /**
21
     * Hashing Algorithm.
22
     *
23
     * @var string
24
     */
25
    private $algorithm;
26
27
    /**
28
     * Private Key.
29
     *
30
     * @var string
31
     */
32
    private $privateKey;
33
34
    /**
35
     * Payload Data.
36
     *
37
     * @var array
38
     */
39
    private $payload = [];
40
41
    /**
42
     * Date Time Zone.
43
     *
44
     * @var \DateTimeZone
45
     */
46
    private $timezone;
47
48
    /**
49
     * @param string $privateKey
50
     * @param string $algo
51
     * @param string $timezone
52
     */
53 13
    public function __construct($privateKey, $algo = 'sha512', $timezone = 'UTC')
54
    {
55 13
        $this->privateKey = $privateKey;
56 13
        $this->algorithm = $algo;
57 13
        $this->timezone = new \DateTimeZone($timezone);
58 13
    }
59
60
    /**
61
     * Creates hash from payload.
62
     * @param  array $payload
63
     * @return mixed
64
     */
65 4
    public function create($algorithm, array $payload = [], $privateKey)
66
    {
67
68 4
        $this->payload = json_encode($payload);
0 ignored issues
show
Documentation Bug introduced by
It seems like json_encode($payload) of type string is incompatible with the declared type array of property $payload.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
69
70 4
        return hash_hmac(
71 4
            $algorithm,
72 4
            $this->payload,
73
            $privateKey
74 4
        );
75
    }
76
77 2
    public function getEncodedHash(array $payload = []){
78 2
        $hash = $this->create($this->algorithm, $payload, $this->privateKey);
79 2
        return base64_encode($this->algorithm.'='.$hash);
80
    }
81
82
83
    /**
84
     * Compare received hash against payload.
85
     *
86
     * @param  $encodedHash
87
     * @param  array       $payload
88
     * @return bool
89
     * @throws \Exception
90
     */
91 3
    public function compareHash($encodedHash, array $payload = [])
92
    {
93 3
        $decodedHash = base64_decode($encodedHash);
94
95 3
        list($algo, $hash) = array_pad( explode('=', $decodedHash), 4, $this->algorithm);
96 3
        $payloadHash = $this->create($this->algorithm, $payload, $this->privateKey);
97
98
        try {
99 3
            $this->verifyAlgorithm($algo);
100 2
            $this->verify($hash, $payloadHash);
101 3
        } catch (\Exception $e) {
102 2
            throw new \Exception($e->getMessage());
103
        }
104
105 1
        return true;
106
107
    }
108
109
110
    /**
111
     * @param $key
112
     * @return $this
113
     */
114 1
    public function setPrivateKey($key)
115
    {
116 1
        $new = clone $this;
117 1
        $new->privateKey = $key;
118 1
        return $new;
119
    }
120
121
    /**
122
     * Return current Algorithm
123
     *
124
     * @return string
125
     */
126 1
    public function getAlgorithm()
127
    {
128 1
        return $this->algorithm;
129
    }
130
131
132
    public function getPayload(){
133
        return $this->payload;
134
    }
135
136
    /**
137
     * Returns Current Private Key
138
     *
139
     * @return string
140
     */
141 2
    public function getPrivateKey()
142
    {
143 2
        return $this->privateKey;
144
    }
145
146
    /**
147
     * @param string $hash
148
     * @param string $payloadHash
149
     * @return bool
150
     * @throws \Exception
151
     */
152 7
    public function verify($hash = '', $payloadHash = '')
153
    {
154 7
        if (!is_string($hash) || !is_string($payloadHash)) {
155 1
            throw new \Exception('hashes are not of the same type');
156
        }
157 6
        if (\md5($hash) === \md5($payloadHash)
158 6
            && strlen($hash) === strlen($payloadHash)
159 6
        ) {
160 3
            return true;
161
        }
162 3
        throw new \Exception('hashes do not match');
163
    }
164
165 5
    protected function verifyAlgorithm($algo)
166
    {
167 5
        foreach (hash_algos() as $validAlgo) {
168 5
            if ($algo === $validAlgo) {
169 3
                $this->algorithm = $validAlgo;
170 3
                return $this->algorithm;
171
            }
172 5
        }
173 2
        throw new \Exception('Algorithm is not valid');
174
    }
175
}
176