|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Starlit\Request\Authenticator\Hmac; |
|
4
|
|
|
|
|
5
|
|
|
use Starlit\Request\Authenticator\Hmac\Adapter\RequestAdapterInterface; |
|
6
|
|
|
use Starlit\Request\Authenticator\Hmac\Transformer\HmacDataTransformerInterface; |
|
7
|
|
|
use Starlit\Request\Authenticator\Hmac\Transformer\RequestHmacDataTransformer; |
|
8
|
|
|
|
|
9
|
|
|
class HmacGenerator |
|
10
|
|
|
{ |
|
11
|
|
|
// see https://secure.php.net/manual/en/function.hash-hmac-algos.php |
|
12
|
|
|
private const DEFAULT_HASHING_ALGORITHM = 'sha256'; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @var string |
|
16
|
|
|
*/ |
|
17
|
|
|
private $secretKey; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Transforms a request into a data string used by the hash_mac function. The default transfomer builds the |
|
21
|
|
|
* data string in the format "%method% %uri%\n%content%". Inject your own transformer if you want to support |
|
22
|
|
|
* a different data string. |
|
23
|
|
|
* |
|
24
|
|
|
* @var HmacDataTransformerInterface |
|
25
|
|
|
*/ |
|
26
|
|
|
private $hmacDataTransformer; |
|
27
|
|
|
|
|
28
|
3 |
|
public function __construct(string $key, HmacDataTransformerInterface $hmacDataTransformer = null) |
|
29
|
|
|
{ |
|
30
|
3 |
|
if (empty($key)) { |
|
31
|
1 |
|
throw new \InvalidArgumentException('The secret key can not be empty.'); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
3 |
|
$this->secretKey = $key; |
|
35
|
|
|
|
|
36
|
3 |
|
if ($hmacDataTransformer === null) { |
|
37
|
3 |
|
$hmacDataTransformer = new RequestHmacDataTransformer(); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
3 |
|
$this->hmacDataTransformer = $hmacDataTransformer; |
|
41
|
3 |
|
} |
|
42
|
|
|
|
|
43
|
3 |
|
public function generateHmac(string $data, string $hashingAlgorithm = self::DEFAULT_HASHING_ALGORITHM): string |
|
44
|
|
|
{ |
|
45
|
3 |
|
if (empty($data)) { |
|
46
|
1 |
|
throw new \InvalidArgumentException('Data can not be empty.'); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
2 |
|
if (!($hmac = @\hash_hmac($hashingAlgorithm, $data, $this->secretKey))) { |
|
50
|
1 |
|
throw new \LogicException("The hashing algorithm [$hashingAlgorithm] is not supported."); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
1 |
|
return $hmac; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
2 |
|
public function generateHmacForRequest(RequestAdapterInterface $request): string |
|
57
|
|
|
{ |
|
58
|
2 |
|
$data = $this->hmacDataTransformer->getDataForRequest($request); |
|
59
|
|
|
|
|
60
|
2 |
|
return $this->generateHmac($data); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|