-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Crypto.php
95 lines (77 loc) · 1.98 KB
/
Crypto.php
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
<?php
declare(strict_types=1);
/**
* Gazelle\Crypto
*/
namespace Gazelle;
class Crypto
{
# databse crypto cipher
private static string $cipher = "aes-256-cbc";
# the apcu key to use
private static string $key = "DBKEY";
/**
* encrypt
*
* Encrypts input text for use in database.
*
* @param string $plaintext
* @return encrypted string or false if DB key not accessible
*/
public static function encrypt(mixed $plaintext): string|bool
{
if (!self::apcuExists()) {
return false;
}
# fix null error: missing value
$plaintext = strval($plaintext);
$iv_size = openssl_cipher_iv_length(self::$cipher);
$iv = openssl_random_pseudo_bytes($iv_size);
return base64_encode(
$iv . openssl_encrypt(
$plaintext,
self::$cipher,
apcu_fetch(self::$key),
OPENSSL_RAW_DATA,
$iv
)
);
}
/**
* decrypt
*
* Decrypts input text from database.
*
* @param string $ciphertext
* @return decrypted string or false if DB key not accessible
*/
public static function decrypt(mixed $ciphertext): string|bool
{
if (!self::apcuExists()) {
return false;
}
# fix null error: missing value
$ciphertext = strval($ciphertext);
$iv_size = openssl_cipher_iv_length(self::$cipher);
$iv = substr(base64_decode($ciphertext), 0, $iv_size);
$ciphertext = substr(base64_decode($ciphertext), $iv_size);
return openssl_decrypt(
$ciphertext,
self::$cipher,
apcu_fetch(self::$key),
OPENSSL_RAW_DATA,
$iv
);
}
/**
* apcuExists
*
* Is self::$key present?
*
* @return bool
*/
public static function apcuExists(): bool
{
return apcu_exists(self::$key);
}
} # class