|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace GeminiLabs\SiteReviews\Modules; |
|
4
|
|
|
|
|
5
|
|
|
class Encryption |
|
6
|
|
|
{ |
|
7
|
|
|
public function decode(string $string): string |
|
8
|
|
|
{ |
|
9
|
|
|
return base64_decode(str_replace(['-', '_'], ['+', '/'], $string)); |
|
10
|
|
|
} |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @return string|false |
|
14
|
|
|
*/ |
|
15
|
|
|
public function decrypt(string $message) |
|
16
|
|
|
{ |
|
17
|
|
|
try { |
|
18
|
|
|
$ciphertext = $this->decode($message); |
|
19
|
|
|
return sodium_crypto_secretbox_open($ciphertext, $this->nonce(), $this->key()); |
|
20
|
|
|
} catch (\Exception $e) { |
|
21
|
|
|
glsr_log()->error($e->getMessage()); |
|
22
|
|
|
return false; |
|
23
|
|
|
} |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function decryptRequest(string $message): array |
|
27
|
|
|
{ |
|
28
|
|
|
if ($message = $this->decrypt($message)) { |
|
29
|
|
|
$data = explode('|', $message); |
|
30
|
|
|
$data = array_map('sanitize_text_field', $data); |
|
31
|
|
|
$action = array_shift($data); |
|
32
|
|
|
return compact('action', 'data'); |
|
33
|
|
|
} |
|
34
|
|
|
return []; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
24 |
|
public function encode(string $string): string |
|
38
|
|
|
{ |
|
39
|
24 |
|
return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($string)); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @return string|false |
|
44
|
|
|
*/ |
|
45
|
24 |
|
public function encrypt(string $message) |
|
46
|
|
|
{ |
|
47
|
|
|
try { |
|
48
|
24 |
|
$ciphertext = sodium_crypto_secretbox($message, $this->nonce(), $this->key()); |
|
49
|
24 |
|
return $this->encode($ciphertext); |
|
50
|
|
|
} catch (\Exception $e) { |
|
51
|
|
|
glsr_log()->error($e->getMessage()); |
|
52
|
|
|
return false; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
24 |
|
public function encryptRequest(string $action, array $data): string |
|
57
|
|
|
{ |
|
58
|
24 |
|
$values = array_values(array_map('sanitize_text_field', $data)); |
|
59
|
24 |
|
$message = implode('|', $values); |
|
60
|
24 |
|
$message = sprintf('%s|%s', $action, $message); |
|
61
|
24 |
|
return (string) $this->encrypt($message); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
24 |
|
protected function key(): string |
|
65
|
|
|
{ |
|
66
|
24 |
|
if (!defined('NONCE_KEY')) { |
|
67
|
|
|
return ''; |
|
68
|
|
|
} |
|
69
|
24 |
|
$key = substr(NONCE_KEY, 0, SODIUM_CRYPTO_SECRETBOX_KEYBYTES); |
|
70
|
24 |
|
return str_pad($key, SODIUM_CRYPTO_SECRETBOX_KEYBYTES, '#'); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
24 |
|
protected function nonce(): string |
|
74
|
|
|
{ |
|
75
|
24 |
|
if (!defined('NONCE_SALT')) { |
|
76
|
|
|
return ''; |
|
77
|
|
|
} |
|
78
|
24 |
|
$nonce = substr(NONCE_SALT, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); |
|
79
|
24 |
|
return str_pad($nonce, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '#'); |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|