Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 www 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Library;
6
 
7
class AesCipher
8
{
9
    const CIPHER = 'AES-128-CBC';
10
    const INIT_VECTOR_LENGTH = 16;
11
 
12
    /**
13
     * Encoded/Decoded data
14
     *
15
     * @var null|string
16
     */
17
    protected $data;
18
    /**
19
     * Initialization vector value
20
     *
21
     * @var string
22
     */
23
    protected $initVector;
24
    /**
25
     * Error message if operation failed
26
     *
27
     * @var null|string
28
     */
29
    protected $errorMessage;
30
 
31
    /**
32
     * AesCipher constructor.
33
     *
34
     * @param string $initVector        Initialization vector value
35
     * @param string|null $data         Encoded/Decoded data
36
     * @param string|null $errorMessage Error message if operation failed
37
     */
38
    public function __construct($initVector, $data = null, $errorMessage = null)
39
    {
40
        $this->initVector = $initVector;
41
        $this->data = $data;
42
        $this->errorMessage = $errorMessage;
43
    }
44
 
45
    /**
46
     * Encrypt input text by AES-128-CBC algorithm
47
     *
48
     * @param string $secretKey 16/24/32 -characters secret password
49
     * @param string $plainText Text for encryption
50
     *
51
     * @return self Self object instance with data or error message
52
     */
53
    public static function encrypt($secretKey, $plainText)
54
    {
55
        try {
56
            // Check secret length
57
            if (!static::isKeyLengthValid($secretKey)) {
58
                throw new \InvalidArgumentException("Secret key's length must be 128, 192 or 256 bits");
59
            }
60
 
61
            // Get random initialization vector
62
            $initVector = bin2hex(openssl_random_pseudo_bytes(static::INIT_VECTOR_LENGTH / 2));
63
 
64
            // Encrypt input text
65
            $raw = openssl_encrypt(
66
                $plainText,
67
                static::CIPHER,
68
                $secretKey,
69
                OPENSSL_RAW_DATA,
70
                $initVector
71
                );
72
 
73
            // Return base64-encoded string: initVector + encrypted result
74
            $result = base64_encode($initVector . $raw);
75
 
76
            if ($result === false) {
77
                // Operation failed
78
                return new static($initVector, null, openssl_error_string());
79
            }
80
 
81
            // Return successful encoded object
82
            return new static($initVector, $result);
83
        } catch (\Exception $e) {
84
            // Operation failed
85
            return new static(isset($initVector), null, $e->getMessage());
86
        }
87
    }
88
 
89
    /**
90
     * Decrypt encoded text by AES-128-CBC algorithm
91
     *
92
     * @param string $secretKey  16/24/32 -characters secret password
93
     * @param string $cipherText Encrypted text
94
     *
95
     * @return self Self object instance with data or error message
96
     */
97
    public static function decrypt($secretKey, $cipherText)
98
    {
99
        try {
100
            // Check secret length
101
            if (!static::isKeyLengthValid($secretKey)) {
102
                throw new \InvalidArgumentException("Secret key's length must be 128, 192 or 256 bits");
103
            }
104
 
105
            // Get raw encoded data
106
            $encoded = base64_decode($cipherText);
107
            // Slice initialization vector
108
            $initVector = substr($encoded, 0, static::INIT_VECTOR_LENGTH);
109
            // Slice encoded data
110
            $data = substr($encoded, static::INIT_VECTOR_LENGTH);
111
 
112
            // Trying to get decrypted text
113
            $decoded = openssl_decrypt(
114
                $data,
115
                static::CIPHER,
116
                $secretKey,
117
                OPENSSL_RAW_DATA,
118
                $initVector
119
                );
120
 
121
            if ($decoded === false) {
122
                // Operation failed
123
                return new static(isset($initVector), null, openssl_error_string());
124
            }
125
 
126
            // Return successful decoded object
127
            return new static($initVector, $decoded);
128
        } catch (\Exception $e) {
129
            // Operation failed
130
            return new static(isset($initVector), null, $e->getMessage());
131
        }
132
    }
133
 
134
    /**
135
     * Check that secret password length is valid
136
     *
137
     * @param string $secretKey 16/24/32 -characters secret password
138
     *
139
     * @return bool
140
     */
141
    public static function isKeyLengthValid($secretKey)
142
    {
143
        $length = strlen($secretKey);
144
 
145
        return $length == 16 || $length == 24 || $length == 32;
146
    }
147
 
148
    /**
149
     * Get encoded/decoded data
150
     *
151
     * @return string|null
152
     */
153
    public function getData()
154
    {
155
        return $this->data;
156
    }
157
 
158
    /**
159
     * Get initialization vector value
160
     *
161
     * @return string|null
162
     */
163
    public function getInitVector()
164
    {
165
        return $this->initVector;
166
    }
167
 
168
    /**
169
     * Get error message
170
     *
171
     * @return string|null
172
     */
173
    public function getErrorMessage()
174
    {
175
        return $this->errorMessage;
176
    }
177
 
178
    /**
179
     * Check that operation failed
180
     *
181
     * @return bool
182
     */
183
    public function hasError()
184
    {
185
        return $this->errorMessage !== null;
186
    }
187
 
188
    /**
189
     * To string return resulting data
190
     *
191
     * @return null|string
192
     */
193
    public function __toString()
194
    {
195
        return $this->getData();
196
    }
197
}
198