chengkun
2025-09-15 35c7b841f41398ab270d9316e41e841ec6bfd9c0
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
<?php declare(strict_types=1);
 
namespace WeChatPay\Crypto;
 
use function openssl_encrypt;
use function base64_encode;
use function openssl_decrypt;
use function base64_decode;
 
use const OPENSSL_RAW_DATA;
 
use UnexpectedValueException;
 
/**
 * Aes encrypt/decrypt using `aes-256-ecb` algorithm with pkcs7padding.
 */
class AesEcb implements AesInterface
{
    /**
     * @inheritDoc
     */
    public static function encrypt(
        #[\SensitiveParameter]
        string $plaintext,
        #[\SensitiveParameter]
        string $key,
        string $iv = ''
    ): string
    {
        $ciphertext = openssl_encrypt($plaintext, static::ALGO_AES_256_ECB, $key, OPENSSL_RAW_DATA, $iv = '');
 
        if (false === $ciphertext) {
            throw new UnexpectedValueException('Encrypting the input $plaintext failed, please checking your $key and $iv whether or nor correct.');
        }
 
        return base64_encode($ciphertext);
    }
 
    /**
     * @inheritDoc
     */
    public static function decrypt(
        #[\SensitiveParameter]
        string $ciphertext,
        #[\SensitiveParameter]
        string $key,
        string $iv = ''
    ): string
    {
        $plaintext = openssl_decrypt(base64_decode($ciphertext), static::ALGO_AES_256_ECB, $key, OPENSSL_RAW_DATA, $iv = '');
 
        if (false === $plaintext) {
            throw new UnexpectedValueException('Decrypting the input $ciphertext failed, please checking your $key and $iv whether or nor correct.');
        }
 
        return $plaintext;
    }
}