zhaojs
2023-07-19 34be2c6feb1f8e3ac35ddeb96fcb809b9e185573
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
<?php
 
declare(strict_types=1);
 
/*
 * This file is part of the EasyWeChatComposer.
 *
 * (c) 张铭阳 <mingyoungcheung@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
 
namespace EasyWeChatComposer\Encryption;
 
use EasyWeChatComposer\Contracts\Encrypter;
use EasyWeChatComposer\Exceptions\DecryptException;
use EasyWeChatComposer\Exceptions\EncryptException;
 
class DefaultEncrypter implements Encrypter
{
    /**
     * @var string
     */
    protected $key;
 
    /**
     * @var string
     */
    protected $cipher;
 
    /**
     * @param string $key
     * @param string $cipher
     */
    public function __construct($key, $cipher = 'AES-256-CBC')
    {
        $this->key = $key;
        $this->cipher = $cipher;
    }
 
    /**
     * Encrypt the given value.
     *
     * @param string $value
     *
     * @return string
     *
     * @throws \EasyWeChatComposer\Exceptions\EncryptException
     */
    public function encrypt($value)
    {
        $iv = random_bytes(openssl_cipher_iv_length($this->cipher));
 
        $value = openssl_encrypt($value, $this->cipher, $this->key, 0, $iv);
 
        if ($value === false) {
            throw new EncryptException('Could not encrypt the data.');
        }
 
        $iv = base64_encode($iv);
 
        return base64_encode(json_encode(compact('iv', 'value')));
    }
 
    /**
     * Decrypt the given value.
     *
     * @param string $payload
     *
     * @return string
     *
     * @throws \EasyWeChatComposer\Exceptions\DecryptException
     */
    public function decrypt($payload)
    {
        $payload = json_decode(base64_decode($payload), true);
 
        $iv = base64_decode($payload['iv']);
 
        $decrypted = openssl_decrypt($payload['value'], $this->cipher, $this->key, 0, $iv);
 
        if ($decrypted === false) {
            throw new DecryptException('Could not decrypt the data.');
        }
 
        return $decrypted;
    }
}