forked from fall1600/newebpay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCryption.php
123 lines (107 loc) · 2.85 KB
/
Cryption.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php
namespace fall1600\Package\Newebpay;
use fall1600\Package\Newebpay\Constants\Cipher;
use fall1600\Package\Newebpay\Contracts\InfoInterface;
use fall1600\Package\Newebpay\Exceptions\TradeInfoException;
trait Cryption
{
protected $hashKey;
protected $hashIv;
/**
* @param InfoInterface $info
* @return string
*/
public function countTradeInfo(InfoInterface $info)
{
$infoPayload = $info->getInfo();
return $this->createEncryptedStr($infoPayload);
}
/**
* @param string $tradeInfo
* @return string
*/
public function countTradeSha(string $tradeInfo)
{
if (! $tradeInfo) {
throw new \LogicException('empty trade info');
}
return strtoupper(
hash(
"sha256",
"HashKey={$this->hashKey}&{$tradeInfo}&HashIV={$this->hashIv}"
)
);
}
/**
* @return string
*/
public function getHashKey()
{
return $this->hashKey;
}
/**
* @return string
*/
public function getHashIv()
{
return $this->hashIv;
}
public function createEncryptedStr(array $infoPayload = [])
{
return trim(
bin2hex(
openssl_encrypt(
$this->addPadding(http_build_query($infoPayload)),
Cipher::METHOD,
$this->hashKey,
OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,
$this->hashIv
)
)
);
}
/**
* 從藍新回傳的加密交易資訊解成可讀的字串
* @param string $tradeInfo
* @return string
* @throws TradeInfoException
*/
public function decryptTradeInfo(string $tradeInfo)
{
if (! $tradeInfo) {
throw new \LogicException('empty trade info');
}
return $this->stripPadding(
openssl_decrypt(
hex2bin($tradeInfo),
Cipher::METHOD,
$this->hashKey,
OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,
$this->hashIv
)
);
}
protected function addPadding(string $string, int $blockSize = 32)
{
$len = strlen($string);
$pad = $blockSize - ($len % $blockSize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
/**
* @param $string
* @return string
* @throws TradeInfoException
*/
protected function stripPadding($string)
{
$slast = ord(substr($string, -1));
$slastc = chr($slast);
$pcheck = substr($string, -$slast);
if (preg_match("/$slastc{" . $slast . "}/", $string)) {
$string = substr($string, 0, strlen($string) - $slast);
return $string;
}
throw new TradeInfoException();
}
}