Passed
Push — master ( 67c0a2...6d4ce9 )
by ma
02:20
created

AES   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 12
c 1
b 0
f 0
dl 0
loc 45
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A validateKey() 0 4 2
A validateIv() 0 4 3
A decrypt() 0 6 2
A encrypt() 0 6 1
A getMode() 0 3 1
1
<?php
2
3
namespace tinymeng\OAuth2\Helper;
4
5
/**
6
 * Class AES.
7
 *
8
 * @author overtrue <[email protected]>
9
 */
10
class AES
11
{
12
    public static function encrypt(string $text, string $key, string $iv, int $option = OPENSSL_RAW_DATA): string
13
    {
14
        self::validateKey($key);
15
        self::validateIv($iv);
16
17
        return openssl_encrypt($text, self::getMode($key), $key, $option, $iv);
18
    }
19
20
    /**
21
     * @param string|null $method
22
     */
23
    public static function decrypt(string $cipherText, string $key, string $iv, int $option = OPENSSL_RAW_DATA, $method = null): string
24
    {
25
        self::validateKey($key);
26
        self::validateIv($iv);
27
28
        return openssl_decrypt($cipherText, $method ?: self::getMode($key), $key, $option, $iv);
29
    }
30
31
    /**
32
     * @param string $key
33
     *
34
     * @return string
35
     */
36
    public static function getMode($key)
37
    {
38
        return 'aes-'.(8 * strlen($key)).'-cbc';
39
    }
40
41
    public static function validateKey(string $key)
42
    {
43
        if (!in_array(strlen($key), [16, 24, 32], true)) {
44
            throw new \InvalidArgumentException(sprintf('Key length must be 16, 24, or 32 bytes; got key len (%s).', strlen($key)));
45
        }
46
    }
47
48
    /**
49
     * @throws \InvalidArgumentException
50
     */
51
    public static function validateIv(string $iv)
52
    {
53
        if (!empty($iv) && 16 !== strlen($iv)) {
54
            throw new \InvalidArgumentException('IV length must be 16 bytes.');
55
        }
56
    }
57
}
58