AESEncoder   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 57.14%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 69
ccs 12
cts 21
cp 0.5714
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A encrypt() 0 7 1
A decrypt() 0 7 1
A getMode() 0 4 1
A validateKey() 0 9 2
A validateIv() 0 6 2
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 6
    public static function decrypt($cipherText, $key, $iv, $option = OPENSSL_RAW_DATA)
33
    {
34 6
        self::validateKey($key);
35 6
        self::validateIv($iv);
36
37 6
        return openssl_decrypt($cipherText, self::getMode($key), $key, $option, $iv);
38
    }
39
40
    /**
41
     * @param string $key
42
     *
43
     * @return string
44
     */
45 6
    public static function getMode($key)
46
    {
47 6
        return 'aes-'.(8 * strlen($key)).'-cbc';
48
    }
49
50
    /**
51
     * @param string $key
52
     */
53 6
    public static function validateKey($key)
54
    {
55 6
        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 6
    }
62
63
    /**
64
     * @param string $iv
65
     *
66
     * @throws \InvalidArgumentException
67
     */
68 6
    public static function validateIv($iv)
69
    {
70 6
        if (strlen($iv) !== 16) {
71
            throw new \InvalidArgumentException('IV length must be 16 bytes.');
72
        }
73 6
    }
74
}
75