Completed
Push — master ( 7c0e89...5c9864 )
by Wang
13:40
created

AESEncoder::decrypt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 4
1
<?php
2
3
4
namespace Oakhope\OAuth2\Client\Support\Common;
5
6
class AESEncoder
7
{
8
    /**
9
     * @param string $text
10
     * @param string $key
11
     * @param string $iv
12
     * @param int    $option
13
     *
14
     * @return string
15
     */
16
    public static function encrypt($text, $key, $iv, $option = OPENSSL_RAW_DATA)
17
    {
18
        self::validateKey($key);
19
        self::validateIv($iv);
20
21
        return openssl_encrypt($text, self::getMode($key), $key, $option, $iv);
22
    }
23
24
    /**
25
     * @param string $cipherText
26
     * @param string $key
27
     * @param string $iv
28
     * @param int    $option
29
     *
30
     * @return string
31
     */
32
    public static function decrypt($cipherText, $key, $iv, $option = OPENSSL_RAW_DATA)
33
    {
34
        self::validateKey($key);
35
        self::validateIv($iv);
36
37
        return openssl_decrypt($cipherText, self::getMode($key), $key, $option, $iv);
38
    }
39
40
    /**
41
     * @param string $key
42
     *
43
     * @return string
44
     */
45
    public static function getMode($key)
46
    {
47
        return 'aes-'.(8 * strlen($key)).'-cbc';
48
    }
49
50
    /**
51
     * @param string $key
52
     */
53
    public static function validateKey($key)
54
    {
55
        if (!in_array(strlen($key), [16, 24, 32], true)) {
56
            throw new \InvalidArgumentException(
57
                sprintf('Key length must be 16, 24, or 32 bytes; got key len (%s)
58
                .', strlen($key))
59
            );
60
        }
61
    }
62
63
    /**
64
     * @param string $iv
65
     *
66
     * @throws \InvalidArgumentException
67
     */
68
    public static function validateIv($iv)
69
    {
70
        if (strlen($iv) !== 16) {
71
            throw new \InvalidArgumentException('IV length must be 16 bytes.');
72
        }
73
    }
74
}
75