1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the EasyWeChatComposer. |
7
|
|
|
* |
8
|
|
|
* (c) 张铭阳 <[email protected]> |
9
|
|
|
* |
10
|
|
|
* This source file is subject to the MIT license that is bundled |
11
|
|
|
* with this source code in the file LICENSE. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace EasyWeChatComposer\Encryption; |
15
|
|
|
|
16
|
|
|
use EasyWeChatComposer\Contracts\Encrypter; |
17
|
|
|
use EasyWeChatComposer\Exceptions\DecryptException; |
18
|
|
|
use EasyWeChatComposer\Exceptions\EncryptException; |
19
|
|
|
|
20
|
|
|
class DefaultEncrypter implements Encrypter |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var string |
24
|
|
|
*/ |
25
|
|
|
protected $key; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var string |
29
|
|
|
*/ |
30
|
|
|
protected $cipher; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param string $key |
34
|
|
|
* @param string $cipher |
35
|
|
|
*/ |
36
|
|
|
public function __construct($key, $cipher = 'AES-256-CBC') |
37
|
|
|
{ |
38
|
|
|
$this->key = $key; |
39
|
|
|
$this->cipher = $cipher; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Encrypt the given value. |
44
|
|
|
* |
45
|
|
|
* @param string $value |
46
|
|
|
* |
47
|
|
|
* @return string |
48
|
|
|
* |
49
|
|
|
* @throws \EasyWeChatComposer\Exceptions\EncryptException |
50
|
|
|
*/ |
51
|
|
|
public function encrypt($value) |
52
|
|
|
{ |
53
|
|
|
$iv = random_bytes(openssl_cipher_iv_length($this->cipher)); |
54
|
|
|
|
55
|
|
|
$value = openssl_encrypt($value, $this->cipher, $this->key, 0, $iv); |
56
|
|
|
|
57
|
|
|
if ($value === false) { |
58
|
|
|
throw new EncryptException('Could not encrypt the data.'); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$iv = base64_encode($iv); |
62
|
|
|
|
63
|
|
|
return base64_encode(json_encode(compact('iv', 'value'))); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Decrypt the given value. |
68
|
|
|
* |
69
|
|
|
* @param string $payload |
70
|
|
|
* |
71
|
|
|
* @return string |
72
|
|
|
* |
73
|
|
|
* @throws \EasyWeChatComposer\Exceptions\DecryptException |
74
|
|
|
*/ |
75
|
|
|
public function decrypt($payload) |
76
|
|
|
{ |
77
|
|
|
$payload = json_decode(base64_decode($payload), true); |
78
|
|
|
|
79
|
|
|
$iv = base64_decode($payload['iv']); |
80
|
|
|
|
81
|
|
|
$decrypted = openssl_decrypt($payload['value'], $this->cipher, $this->key, 0, $iv); |
82
|
|
|
|
83
|
|
|
if ($decrypted === false) { |
84
|
|
|
throw new DecryptException('Could not decrypt the data.'); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return $decrypted; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|