PluginProbe
Auto Alt Text / 1.3.1
Auto Alt Text v1.3.1
3.0.3 2.8.2 1.3.1 1.3.2 2.0.0 2.1.0 2.1.1 2.2.0 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4 2.4.0 2.4.1 2.4.2 2.5.0 2.5.1 2.5.2 2.5.3 2.6.0 2.6.1 2.7.0 2.8.0 2.8.1 All 28 releases
auto-alt-text / src / App / Utilities / Encryption.php

Encryption.php in Auto Alt Text 1.3.1, at src/App/Utilities/Encryption.php

109 lines 2.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace AATXT\App\Utilities;
4
5 use RuntimeException;
6
7 final class Encryption
8 {
9 private string $key;
10 private string $salt;
11
12 public function __construct()
13 {
14 $this->key = $this->getKey();
15 $this->salt = $this->getSalt();
16 }
17
18 /**
19 * @return Encryption
20 */
21 public static function make(): Encryption
22 {
23 return new self();
24 }
25
26 /**
27 * @param string $value
28 * @return string|bool
29 */
30 public function encrypt(string $value): string
31 {
32 if (empty($value)) {
33 return '';
34 }
35
36 if (!extension_loaded('openssl')) {
37 return $value;
38 }
39
40 $method = 'aes-256-ctr';
41 $ivLength = openssl_cipher_iv_length($method);
42 $iv = openssl_random_pseudo_bytes($ivLength);
43 $raw_value = openssl_encrypt($value . $this->salt, $method, $this->key, 0, $iv);
44 if (!$raw_value) {
45 throw new RuntimeException('Encryption failed.');
46 }
47
48 return base64_encode($iv . $raw_value);
49 }
50
51 /**
52 * @param string $rawValue
53 * @return string|bool
54 */
55 public function decrypt(string $rawValue): string
56 {
57 if (empty($rawValue)) {
58 return '';
59 }
60
61 /** @noinspection DuplicatedCode */
62 if (!extension_loaded('openssl')) {
63 return $rawValue;
64 }
65
66 $rawValue = base64_decode($rawValue, true);
67
68 $method = 'aes-256-ctr';
69 $ivLength = openssl_cipher_iv_length($method);
70 $iv = substr($rawValue, 0, $ivLength);
71
72 $rawValue = substr($rawValue, $ivLength);
73
74 $value = openssl_decrypt($rawValue, $method, $this->key, 0, $iv);
75
76 if (!$value || substr($value, -strlen($this->salt)) !== $this->salt) {
77 throw new RuntimeException('Encryption failed.');
78 }
79
80 return substr($value, 0, -strlen($this->salt));
81 }
82
83 /**
84 * Get key from WordPress Authentication Unique Keys and Salts
85 */
86 private function getKey(): string
87 {
88 if (defined('LOGGED_IN_KEY') && '' !== LOGGED_IN_KEY) {
89 return LOGGED_IN_KEY;
90 }
91
92 // If this is reached, you're either not on a live site or have a serious security issue.
93 return 'warning-not-logged-in-key-constant-defined';
94 }
95
96 /**
97 * Get salt from WordPress Authentication Unique Keys and Salts
98 */
99 public function getSalt(): string
100 {
101 if (defined('LOGGED_IN_SALT') && '' !== LOGGED_IN_SALT) {
102 return LOGGED_IN_SALT;
103 }
104
105 // If this is reached, you're either not on a live site or have a serious security issue.
106 return 'warning-not-logged-in-salt-constant-defined';
107 }
108 }
109