|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace BPT\tools; |
|
4
|
|
|
|
|
5
|
|
|
use BPT\constants\cryptoAction; |
|
6
|
|
|
use BPT\constants\loggerTypes; |
|
7
|
|
|
use BPT\exception\bptException; |
|
8
|
|
|
use BPT\logger; |
|
9
|
|
|
|
|
10
|
|
|
trait encrypt { |
|
11
|
|
|
/** |
|
12
|
|
|
* encrypt or decrypt a text with really high security |
|
13
|
|
|
* |
|
14
|
|
|
* action parameter must be encrypt or decrypt |
|
15
|
|
|
* |
|
16
|
|
|
* string parameter is your hash(received when use encrypt) or the text you want to encrypt |
|
17
|
|
|
* |
|
18
|
|
|
* for decrypt , you must have key and iv parameter. you can found them in result of encrypt |
|
19
|
|
|
* |
|
20
|
|
|
* e.g. => tools::crypto(action: 'decrypt', text: '9LqUf9DSuRRwfo03RnA5Kw==', key: '39aaadf402f9b921b1d44e33ee3b022716a518e97d6a7b55de8231de501b4f34', iv: 'a2e5904a4110169e'); |
|
21
|
|
|
* |
|
22
|
|
|
* e.g. => tools::crypto(cryptoAction::ENCRYPT,'hello world'); |
|
23
|
|
|
* |
|
24
|
|
|
* @param string $action e.g. => cryptoAction::ENCRYPT | 'encrypt' |
|
25
|
|
|
* @param string $text e.g. => 'hello world' |
|
26
|
|
|
* @param null|string $key e.g. => Optional, 39aaadf402f9b921b1d44e33ee3b022716a518e97d6a7b55de8231de501b4f34 |
|
27
|
|
|
* @param null|string $iv e.g. => Optional, a2e5904a4110169e |
|
28
|
|
|
* |
|
29
|
|
|
* @return array|string|bool |
|
30
|
|
|
* @throws bptException |
|
31
|
|
|
*/ |
|
32
|
|
|
public static function crypto (string $action, string $text, string $key = null, string $iv = null): bool|array|string { |
|
33
|
|
|
|
|
34
|
|
|
if (extension_loaded('openssl')) { |
|
35
|
|
|
if ($action === cryptoAction::ENCRYPT) { |
|
36
|
|
|
$key = self::randomString(64); |
|
37
|
|
|
$iv = self::randomString(); |
|
38
|
|
|
$output = base64_encode(openssl_encrypt($text, 'AES-256-CBC', $key, 1, $iv)); |
|
39
|
|
|
return ['hash' => $output, 'key' => $key, 'iv' => $iv]; |
|
40
|
|
|
} |
|
41
|
|
|
elseif ($action === cryptoAction::DECRYPT) { |
|
42
|
|
|
if (empty($key)) { |
|
43
|
|
|
logger::write("tools::crypto function used\nkey parameter is not set",loggerTypes::ERROR); |
|
44
|
|
|
throw new bptException('ARGUMENT_NOT_FOUND_KEY'); |
|
45
|
|
|
} |
|
46
|
|
|
if (empty($iv)) { |
|
47
|
|
|
logger::write("tools::crypto function used\niv parameter is not set",loggerTypes::ERROR); |
|
48
|
|
|
throw new bptException('ARGUMENT_NOT_FOUND_IV'); |
|
49
|
|
|
} |
|
50
|
|
|
return openssl_decrypt(base64_decode($text), 'AES-256-CBC', $key, 1, $iv); |
|
51
|
|
|
} |
|
52
|
|
|
else { |
|
53
|
|
|
logger::write("tools::crypto function used\naction is not right, its must be `encode` or `decode`"); |
|
54
|
|
|
return false; |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
else { |
|
58
|
|
|
logger::write("tools::crypto function used\nopenssl extension is not found , It may not be installed or enabled",loggerTypes::ERROR); |
|
59
|
|
|
throw new bptException('OPENSSL_EXTENSION_MISSING'); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
} |