1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* MIT License |
5
|
|
|
* For full license information, please view the LICENSE file that was distributed with this source code. |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace SprykerEco\Service\CrefoPayApi\HashCalculator; |
9
|
|
|
|
10
|
|
|
use SprykerEco\Service\CrefoPayApi\CrefoPayApiConfig; |
11
|
|
|
|
12
|
|
|
class MacHashCalculator implements MacHashCalculatorInterface |
13
|
|
|
{ |
14
|
|
|
protected const HASHING_ALGORITHM = 'sha1'; |
15
|
|
|
protected const CHARS_TO_REPLACE = [" ", "\t", "\s", "\r", "\n"]; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var \SprykerEco\Service\CrefoPayApi\CrefoPayApiConfig |
19
|
|
|
*/ |
20
|
|
|
protected $config; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param \SprykerEco\Service\CrefoPayApi\CrefoPayApiConfig $config |
24
|
|
|
*/ |
25
|
|
|
public function __construct(CrefoPayApiConfig $config) |
26
|
|
|
{ |
27
|
|
|
$this->config = $config; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param array $data |
32
|
|
|
* |
33
|
|
|
* @return string |
34
|
|
|
*/ |
35
|
|
|
public function calculateMac(array $data): string |
36
|
|
|
{ |
37
|
|
|
$macString = $this->createMacString($data); |
38
|
|
|
|
39
|
|
|
return $this->hashValue($macString); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param array $responseData |
44
|
|
|
* @param string $mac |
45
|
|
|
* |
46
|
|
|
* @return bool |
47
|
|
|
*/ |
48
|
|
|
public function validateMac(array $responseData, string $mac): bool |
49
|
|
|
{ |
50
|
|
|
return $this->calculateMac($responseData) === $mac; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param array $data |
55
|
|
|
* |
56
|
|
|
* @return string |
57
|
|
|
*/ |
58
|
|
|
protected function createMacString(array $data): string |
59
|
|
|
{ |
60
|
|
|
ksort($data); |
61
|
|
|
|
62
|
|
|
return $this->removeDelimiters(implode('', $data)); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $value |
67
|
|
|
* |
68
|
|
|
* @return string |
69
|
|
|
*/ |
70
|
|
|
protected function hashValue(string $value): string |
71
|
|
|
{ |
72
|
|
|
return hash_hmac(static::HASHING_ALGORITHM, $value, $this->getPrivateKey()); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @param string $macString |
77
|
|
|
* |
78
|
|
|
* @return string |
79
|
|
|
*/ |
80
|
|
|
protected function removeDelimiters(string $macString): string |
81
|
|
|
{ |
82
|
|
|
return str_replace(static::CHARS_TO_REPLACE, '', $macString); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @return string |
87
|
|
|
*/ |
88
|
|
|
protected function getPrivateKey(): string |
89
|
|
|
{ |
90
|
|
|
return $this->config->getPrivateKey(); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|