-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathHMac.php
41 lines (35 loc) · 1.33 KB
/
HMac.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
declare(strict_types=1);
namespace axios\tools;
class HMac
{
public array $algos = [];
public function count(string $algorithm, $data = null, $secret = null, bool $raw_output = false): string
{
if (\in_array($algorithm, hash_algos())) {
return hash_hmac($algorithm, $data, $secret, $raw_output);
}
if (!isset($this->algos[$algorithm])) {
throw new \RuntimeException('Unsupported algorithm: ' . $algorithm);
}
$callback = $this->algos[$algorithm];
$size = \strlen($callback('test'));
$pack = 'H' . (string) $size;
if (\strlen($secret) > $size) {
$secret = pack($pack, $callback($secret));
}
$key = str_pad($secret, $size, \chr(0x00));
$ipad = $key ^ str_repeat(\chr(0x36), $size);
$opad = $key ^ str_repeat(\chr(0x5C), $size);
$hmac = $callback($opad . pack($pack, $callback($ipad . $data)));
return $raw_output ? pack($pack, $hmac) : $hmac;
}
/**
* @param string $algorithm_name some custom algorithm name or others in hash_hmac_algos()
* @param \Closure $callback custom implement
*/
public function registerAlgorithm(string $algorithm_name, \Closure $callback)
{
$this->algos[$algorithm_name] = $callback;
}
}