-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncryption.php
More file actions
349 lines (305 loc) · 8.16 KB
/
Encryption.php
File metadata and controls
349 lines (305 loc) · 8.16 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<?php
/**
* @author : Jakiboy
* @package : FloatPHP
* @subpackage : Classes Security Component
* @version : 1.5.x
* @copyright : (c) 2018 - 2025 Jihad Sinnaour <me@jihadsinnaour.com>
* @link : https://floatphp.com
* @license : MIT
*
* This file is a part of FloatPHP Framework.
*/
declare(strict_types=1);
namespace FloatPHP\Classes\Security;
use FloatPHP\Classes\Filesystem\{Stringify, TypeCheck};
/**
* Built-in cryptography class,
* JWT is recommended for external use.
*/
class Encryption
{
/**
* @access public
* @var string PREFIX Default encryption prefix
*/
public const PREFIX = '[FloatCrypt]';
/**
* @access private
* @var string SECRET Default secret key (Passphrase)
* @var string VECTOR Default initialzation vector
* @var int LENGTH Default encryption vector length
* @var string ALGO Default hash algorithm
* @var int OPTIONS Default openssl options
* @var string CIPHER Default openssl cipher algorithm
*/
private const SECRET = 'v6t1pQ97JS';
private const VECTOR = 'XRtvQPlFs';
private const LENGTH = 16;
private const ALGO = 'sha256';
private const OPTIONS = 0;
private const CIPHER = 'AES-256-CBC';
/**
* @access private
* @var mixed $data
* @var string $secret, Secret key (Passphrase)
* @var string $vector, Initialzation vector
* @var int $length, Encryption vector length
* @var string $prefix, Encryption prefix
* @var int $options, OpenSSL options
* @var string $cipher, OpenSSL cipher algorithm
* @var bool $asString, Decrypted data as string
* @var bool $bypass, Bypass encrypted string
*/
private $data;
private $secret;
private $vector;
private $length;
private $prefix;
private $options;
private $cipher;
private $asString = false;
private $bypass = false;
/**
* Init encryption (Encrypt / Decrypt).
*
* @param mixed $data
* @param string $secret
* @param string $vector
* @param int $length
*/
public function __construct($data, ?string $secret = self::SECRET, ?string $vector = self::VECTOR, ?int $length = self::LENGTH)
{
// Input validation
if ( $secret !== null && trim($secret) === '' ) {
throw new \InvalidArgumentException('Secret key cannot be empty');
}
if ( $vector !== null && trim($vector) === '' ) {
throw new \InvalidArgumentException('Vector cannot be empty');
}
if ( $length !== null && ($length < 1 || $length > 64) ) {
throw new \InvalidArgumentException('Vector length must be between 1 and 64');
}
// Set data
$this->data = $data;
// Set secret key
$this->secret = $secret;
// Set vector
$this->vector = $vector;
$this->length = $length;
// Initialize
$this->setPrefix(self::PREFIX);
$this->setOptions();
$this->setCipher();
$this->initialize();
}
/**
* Set OpenSSL options.
*
* @access public
* @param int $options
* @param object
*/
public function setOptions(int $options = self::OPTIONS) : self
{
// Validate options are within reasonable range
if ( $options < 0 || $options > 15 ) {
throw new \InvalidArgumentException('OpenSSL options must be between 0 and 15');
}
$this->options = $options;
return $this;
}
/**
* Set OpenSSL cipher algorithm.
*
* @access public
* @param string $options
* @param object
*/
public function setCipher(string $cipher = self::CIPHER) : self
{
// Input validation
if ( trim($cipher) === '' ) {
throw new \InvalidArgumentException('Cipher algorithm cannot be empty');
}
// Validate cipher is supported
if ( !in_array($cipher, openssl_get_cipher_methods()) ) {
throw new \InvalidArgumentException("Unsupported cipher algorithm: {$cipher}");
}
$this->cipher = $cipher;
return $this;
}
/**
* Set encryption prefix.
*
* @access public
* @param string $prefix
* @param object
*/
public function setPrefix(?string $prefix = null) : self
{
$this->prefix = (string)$prefix;
return $this;
}
/**
* Initialize hash.
*
* @access public
* @param string $algo
* @return object
*/
public function initialize(string $algo = self::ALGO) : self
{
// Input validation
if ( trim($algo) === '' ) {
throw new \InvalidArgumentException('Hash algorithm cannot be empty');
}
// Validate hash algorithm is supported
if ( !in_array($algo, hash_algos()) ) {
throw new \InvalidArgumentException("Unsupported hash algorithm: {$algo}");
}
$this->secret = hash($algo, $this->secret);
$this->vector = substr(hash($algo, $this->vector), 0, $this->length);
return $this;
}
/**
* Encrypt data.
*
* @access public
* @param int $loop, Base64 loop (Max 5)
* @param string
*/
public function encrypt(int $loop = 1) : string
{
// Input validation
if ( $loop < 1 || $loop > 5 ) {
throw new \InvalidArgumentException('Loop count must be between 1 and 5');
}
try {
if ( TypeCheck::isString($this->data) ) {
if ( $this->bypass && $this->isCrypted() ) {
return $this->data;
}
} else {
$this->data = Stringify::serialize($this->data);
}
$loop = ($loop <= 3) ? $loop : 3;
// Clear any previous OpenSSL errors
while (openssl_error_string() !== false) {
}
$encrypt = openssl_encrypt(
$this->data,
$this->cipher,
$this->secret,
$this->options,
$this->vector
);
// Check for OpenSSL errors
if ( $encrypt === false ) {
$error = openssl_error_string();
$errorMsg = $error ? "OpenSSL encryption failed: {$error}" : 'OpenSSL encryption failed with unknown error';
throw new \RuntimeException($errorMsg);
}
$crypted = Tokenizer::base64($encrypt, $loop);
unset($this->data);
return "{$this->prefix}{$crypted}";
} catch (\Exception $e) {
// Clean up and re-throw with context
unset($this->data);
throw new \RuntimeException("Encryption failed: " . $e->getMessage(), 0, $e);
}
}
/**
* Decrypt data.
*
* @access public
* @param int $loop, Base64 loop (Max 5)
* @param mixed
*/
public function decrypt(int $loop = 1)
{
// Input validation
if ( $loop < 1 || $loop > 5 ) {
throw new \InvalidArgumentException('Loop count must be between 1 and 5');
}
if ( !TypeCheck::isString($this->data) ) {
return false;
}
try {
$loop = ($loop <= 3) ? $loop : 3;
$crypted = Stringify::remove($this->prefix, $this->data);
// Validate that we have data to decrypt after removing prefix
if ( trim($crypted) === '' ) {
throw new \InvalidArgumentException('No encrypted data found after removing prefix');
}
// Clear any previous OpenSSL errors
while (openssl_error_string() !== false) {
}
$decrypted = openssl_decrypt(
Tokenizer::unbase64($crypted, $loop),
$this->cipher,
$this->secret,
$this->options,
$this->vector
);
// Check for OpenSSL errors
if ( $decrypted === false ) {
$error = openssl_error_string();
$errorMsg = $error ? "OpenSSL decryption failed: {$error}" : 'OpenSSL decryption failed - possibly invalid key or corrupted data';
throw new \RuntimeException($errorMsg);
}
if ( !$this->asString ) {
$unserialized = Stringify::unserialize($decrypted);
// If unserialization fails, return the string data
$decrypted = ($unserialized !== false) ? $unserialized : $decrypted;
}
unset($this->data);
return $decrypted;
} catch (\Exception $e) {
// Clean up and re-throw with context
unset($this->data);
throw new \RuntimeException("Decryption failed: " . $e->getMessage(), 0, $e);
}
}
/**
* Get decrypted data as string.
*
* @access public
* @return object
*/
public function asString() : self
{
$this->asString = true;
return $this;
}
/**
* Bypass encrypted string.
*
* @access public
* @return object
*/
public function bypass() : self
{
$this->bypass = true;
return $this;
}
/**
* Check whether data is crypted using prefix.
*
* @access public
* @param bool
*/
public function isCrypted() : bool
{
// Validate that data is a string and not empty
if ( !TypeCheck::isString($this->data) || trim($this->data) === '' ) {
return false;
}
// Check if data is long enough to contain the prefix
if ( strlen($this->data) < strlen($this->prefix) ) {
return false;
}
$prefix = substr($this->data, 0, strlen($this->prefix));
return $prefix === $this->prefix;
}
}