1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://github.com/yiiviet/yii2-payment |
4
|
|
|
* @copyright Copyright (c) 2017 Yii Viet |
5
|
|
|
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php) |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yiiviet\payment; |
9
|
|
|
|
10
|
|
|
use yii\base\InvalidConfigException; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Lớp HmacDataSignature dùng cho việc tạo và kiểm tra chữ ký theo chuẩn HMAC. |
14
|
|
|
* |
15
|
|
|
* @author Vuong Minh <[email protected]> |
16
|
|
|
* @since 1.0 |
17
|
|
|
*/ |
18
|
|
|
class HmacDataSignature extends DataSignature |
19
|
|
|
{ |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Tên loại mã hóa. Ví dụ: md5, sha1, sha256... |
23
|
|
|
* |
24
|
|
|
* @var string |
25
|
|
|
*/ |
26
|
|
|
public $hmacAlgo; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Khóa mã hóa. Độ phức tạp càng cao thì dữ liệu càng được an toàn. |
30
|
|
|
* |
31
|
|
|
* @var string |
32
|
|
|
*/ |
33
|
|
|
public $key; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var bool phân biệt ký tự hoa thường khi xác minh chữ ký. |
37
|
|
|
* @since 1.0.3 |
38
|
|
|
*/ |
39
|
|
|
public $caseSensitive = true; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @inheritdoc |
43
|
|
|
* @throws InvalidConfigException |
44
|
|
|
*/ |
45
|
6 |
|
public function init() |
46
|
|
|
{ |
47
|
6 |
|
if ($this->key === null) { |
48
|
|
|
throw new InvalidConfigException('Property `key` must be set for generate signature!'); |
49
|
6 |
|
} elseif ($this->hmacAlgo === null) { |
50
|
|
|
throw new InvalidConfigException('Property `hmacAlgo` must be set for generate signature!'); |
51
|
|
|
} |
52
|
|
|
|
53
|
6 |
|
parent::init(); |
54
|
6 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @inheritdoc |
58
|
|
|
*/ |
59
|
6 |
|
public function generate(): string |
60
|
|
|
{ |
61
|
6 |
|
return hash_hmac($this->hmacAlgo, $this->getData(), $this->key); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @inheritdoc |
66
|
|
|
* @throws InvalidConfigException |
67
|
|
|
*/ |
68
|
1 |
View Code Duplication |
public function validate(string $expect): bool |
|
|
|
|
69
|
|
|
{ |
70
|
1 |
|
$actual = $this->generate(); |
71
|
|
|
|
72
|
1 |
|
if ($this->caseSensitive) { |
73
|
|
|
return strcmp($expect, $actual) === 0; |
74
|
|
|
} else { |
75
|
1 |
|
return strcasecmp($expect, $actual) === 0; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
} |
80
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.