-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPIKeyEncryption.inc.php
More file actions
80 lines (65 loc) · 2.12 KB
/
Copy pathAPIKeyEncryption.inc.php
File metadata and controls
80 lines (65 loc) · 2.12 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
<?php
use Illuminate\Encryption\Encrypter;
use Exception;
class APIKeyEncryption
{
private const ENCRYPTION_CIPHER = 'AES-256-CBC';
private const BASE64_PREFIX = 'base64:';
public function secretConfigExists(): bool
{
try {
$this->getSecretFromConfig();
} catch (Exception $e) {
return false;
}
return true;
}
private function getSecretFromConfig(): string
{
$secret = Config::getVar('security', 'api_key_secret');
if ($secret === "") {
throw new Exception("A secret must be set in the config file ('api_key_secret') so that keys can be encrypted and decrypted");
}
return $this->normalizeSecret($secret);
}
private function normalizeSecret(string $secret): string
{
return hash('sha256', $secret, true);
}
public function textIsEncrypted(string $text): bool
{
if (!str_starts_with($text, self::BASE64_PREFIX)) {
return false;
}
try {
$this->decryptString($text);
return true;
} catch (Exception $e) {
return false;
}
}
public function encryptString(string $plainText): string
{
$secret = $this->getSecretFromConfig();
$encrypter = new Encrypter($secret, self::ENCRYPTION_CIPHER);
try {
$encryptedString = $encrypter->encrypt($plainText);
} catch (Exception $e) {
throw new Exception("Failed to encrypt string");
}
return self::BASE64_PREFIX . base64_encode($encryptedString);
}
public function decryptString(string $encryptedText): string
{
$secret = $this->getSecretFromConfig();
$encrypter = new Encrypter($secret, self::ENCRYPTION_CIPHER);
$encryptedText = str_replace(self::BASE64_PREFIX, '', $encryptedText);
$payload = base64_decode($encryptedText);
try {
$decryptedString = $encrypter->decrypt($payload);
} catch (Exception $e) {
throw new Exception("Failed to decrypt string");
}
return $decryptedString;
}
}