Completed
Branch FET/enhanced-encryption (5ab2a7)
by
unknown
04:27 queued 02:36
created
core/services/encryption/EncryptionKeyManager.php 1 patch
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -17,231 +17,231 @@
 block discarded – undo
17 17
 class EncryptionKeyManager implements EncryptionKeyManagerInterface
18 18
 {
19 19
 
20
-    /**
21
-     * name used for a default encryption key in case no others are set
22
-     *
23
-     * @var string
24
-     */
25
-    private $default_encryption_key_id;
26
-
27
-    /**
28
-     * name used for saving encryption keys to the wp_options table
29
-     *
30
-     * @var string
31
-     */
32
-    private $encryption_keys_option_name;
33
-
34
-    /**
35
-     * @var array
36
-     */
37
-    private $encryption_keys = null;
38
-
39
-    /**
40
-     * number of bits used when generating cryptographically secure keys
41
-     *
42
-     * @var int
43
-     */
44
-    private $bit_depth = 128;
45
-
46
-    /**
47
-     * @var int[]
48
-     */
49
-    private $bit_depth_options = [64, 128, 192, 256];
50
-
51
-    /**
52
-     * number of characters used when generating cryptographically weak keys
53
-     *
54
-     * @var int
55
-     */
56
-    private $key_length = 40;
57
-
58
-
59
-    /**
60
-     * @param string $default_encryption_key_id
61
-     * @param string $encryption_keys_option_name
62
-     */
63
-    public function __construct($default_encryption_key_id, $encryption_keys_option_name)
64
-    {
65
-        $this->default_encryption_key_id   = $default_encryption_key_id;
66
-        $this->encryption_keys_option_name = $encryption_keys_option_name;
67
-    }
68
-
69
-
70
-    /**
71
-     * add an encryption key
72
-     *
73
-     * @param string $encryption_key_identifier - name of the encryption key to use
74
-     * @param string $encryption_key            - cryptographically secure passphrase. will generate if necessary
75
-     * @param bool   $overwrite                 - prevents accidental overwriting of an existing key which would be bad
76
-     * @return bool
77
-     * @throws Exception
78
-     */
79
-    public function addEncryptionKey($encryption_key_identifier, $encryption_key = '', $overwrite = false)
80
-    {
81
-        // ensure keys are loaded
82
-        $this->retrieveEncryptionKeys();
83
-        if (isset($this->encryption_keys[ $encryption_key_identifier ]) && ! $overwrite) {
84
-            // WOAH!!! that key already exists and we don't want to overwrite it
85
-            throw new RuntimeException (
86
-                sprintf(
87
-                    esc_html__(
88
-                        'The "%1$s" encryption key already exists and can not be overwritten because previously encrypted values would no longer be capable of being decrypted.',
89
-                        'event_espresso'
90
-                    ),
91
-                    $encryption_key_identifier
92
-                )
93
-            );
94
-        }
95
-        $this->encryption_keys[ $encryption_key_identifier ] = $encryption_key ?: $this->generateEncryptionKey();
96
-        return $this->saveEncryptionKeys();
97
-    }
98
-
99
-
100
-    /**
101
-     * returns cryptographically secure passphrase. will use default if necessary
102
-     *
103
-     * @param string $encryption_key_identifier - used for saving encryption key. will use default if necessary
104
-     * @param string $generate                  - will generate a new key if the requested one does not exist
105
-     * @return string
106
-     * @throws Exception
107
-     */
108
-    public function getEncryptionKey($encryption_key_identifier = '', $generate = false)
109
-    {
110
-        $encryption_key_identifier = $encryption_key_identifier ?: $this->default_encryption_key_id;
111
-        // ensure keys are loaded
112
-        $this->retrieveEncryptionKeys();
113
-        // if encryption key has not been set
114
-        if (! isset($this->encryption_keys[ $encryption_key_identifier ])) {
115
-            if ($generate) {
116
-                $this->addEncryptionKey($encryption_key_identifier);
117
-            } else {
118
-                throw new OutOfBoundsException(
119
-                    sprintf(
120
-                        esc_html__('The "%1$s" encryption key was not found or is invalid.', 'event_espresso'),
121
-                        $encryption_key_identifier
122
-                    )
123
-                );
124
-            }
125
-        }
126
-        return $this->encryption_keys[ $encryption_key_identifier ];
127
-    }
128
-
129
-
130
-    /**
131
-     * creates a new encryption key
132
-     *
133
-     * @param bool $strong if true (default) will attempt to generate a cryptographically secure key
134
-     * @return string
135
-     * @throws Exception
136
-     */
137
-    public function generateEncryptionKey($strong = true)
138
-    {
139
-        return $strong && PHP_VERSION_ID >= 70100
140
-            ? $this->generateStrongEncryptionKey()
141
-            : $this->generateWeakEncryptionKey();
142
-    }
143
-
144
-
145
-    /**
146
-     * creates a new cryptographically secure encryption key
147
-     *
148
-     * @return string
149
-     * @throws Exception
150
-     */
151
-    protected function generateStrongEncryptionKey()
152
-    {
153
-        // bit_depth needs to be divided by 8
154
-        return random_bytes($this->bit_depth / 8);
155
-    }
156
-
157
-
158
-    /**
159
-     * creates a new encryption key that should not be trusted to be cryptographically secure
160
-     *
161
-     * @return string
162
-     * @throws Exception
163
-     */
164
-    protected function generateWeakEncryptionKey()
165
-    {
166
-        // @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
167
-        $iterations    = ceil($this->key_length / 40);
168
-        $random_string = '';
169
-        for ($i = 0; $i < $iterations; $i++) {
170
-            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
171
-        }
172
-        return substr($random_string, 0, $this->key_length);
173
-    }
174
-
175
-
176
-    /**
177
-     * @return int
178
-     */
179
-    public function bitDepth()
180
-    {
181
-        return $this->bit_depth;
182
-    }
183
-
184
-
185
-    /**
186
-     * @param int $bit_depth options are 64, 128, 192, or 256
187
-     */
188
-    public function setBitDepth($bit_depth)
189
-    {
190
-        $bit_depth       = absint($bit_depth);
191
-        $this->bit_depth = in_array($bit_depth, $this->bit_depth_options) ? $bit_depth : 128;
192
-    }
193
-
194
-
195
-    /**
196
-     * @return int
197
-     */
198
-    public function keyLength()
199
-    {
200
-        return $this->key_length;
201
-    }
202
-
203
-
204
-    /**
205
-     * @param int $key_length
206
-     */
207
-    public function setKeyLength($key_length)
208
-    {
209
-        // let's not let the key length go below 8 or above 128
210
-        $this->key_length = min(max($key_length, 8), 128);
211
-    }
212
-
213
-
214
-    /**
215
-     * retrieves encryption keys from db
216
-     *
217
-     * @return string
218
-     * @throws Exception
219
-     */
220
-    protected function retrieveEncryptionKeys()
221
-    {
222
-        // if encryption key has not been set
223
-        if (! empty($this->encryption_keys)) {
224
-            // retrieve encryption_key from db
225
-            $this->encryption_keys = get_option($this->encryption_keys_option_name, null);
226
-            // WHAT?? No encryption_key in the db ??
227
-            if ($this->encryption_keys === null) {
228
-                // let's make one. And md5 it to make it just the right size for a key
229
-                $this->addEncryptionKey($this->default_encryption_key_id);
230
-            }
231
-        }
232
-        return $this->encryption_keys;
233
-    }
234
-
235
-
236
-    /**
237
-     * saves encryption keys from db
238
-     *
239
-     * @return bool
240
-     */
241
-    protected function saveEncryptionKeys()
242
-    {
243
-        return $this->encryption_keys === null
244
-            ? add_option($this->encryption_keys_option_name, $this->encryption_keys)
245
-            : update_option($this->encryption_keys_option_name, $this->encryption_keys);
246
-    }
20
+	/**
21
+	 * name used for a default encryption key in case no others are set
22
+	 *
23
+	 * @var string
24
+	 */
25
+	private $default_encryption_key_id;
26
+
27
+	/**
28
+	 * name used for saving encryption keys to the wp_options table
29
+	 *
30
+	 * @var string
31
+	 */
32
+	private $encryption_keys_option_name;
33
+
34
+	/**
35
+	 * @var array
36
+	 */
37
+	private $encryption_keys = null;
38
+
39
+	/**
40
+	 * number of bits used when generating cryptographically secure keys
41
+	 *
42
+	 * @var int
43
+	 */
44
+	private $bit_depth = 128;
45
+
46
+	/**
47
+	 * @var int[]
48
+	 */
49
+	private $bit_depth_options = [64, 128, 192, 256];
50
+
51
+	/**
52
+	 * number of characters used when generating cryptographically weak keys
53
+	 *
54
+	 * @var int
55
+	 */
56
+	private $key_length = 40;
57
+
58
+
59
+	/**
60
+	 * @param string $default_encryption_key_id
61
+	 * @param string $encryption_keys_option_name
62
+	 */
63
+	public function __construct($default_encryption_key_id, $encryption_keys_option_name)
64
+	{
65
+		$this->default_encryption_key_id   = $default_encryption_key_id;
66
+		$this->encryption_keys_option_name = $encryption_keys_option_name;
67
+	}
68
+
69
+
70
+	/**
71
+	 * add an encryption key
72
+	 *
73
+	 * @param string $encryption_key_identifier - name of the encryption key to use
74
+	 * @param string $encryption_key            - cryptographically secure passphrase. will generate if necessary
75
+	 * @param bool   $overwrite                 - prevents accidental overwriting of an existing key which would be bad
76
+	 * @return bool
77
+	 * @throws Exception
78
+	 */
79
+	public function addEncryptionKey($encryption_key_identifier, $encryption_key = '', $overwrite = false)
80
+	{
81
+		// ensure keys are loaded
82
+		$this->retrieveEncryptionKeys();
83
+		if (isset($this->encryption_keys[ $encryption_key_identifier ]) && ! $overwrite) {
84
+			// WOAH!!! that key already exists and we don't want to overwrite it
85
+			throw new RuntimeException (
86
+				sprintf(
87
+					esc_html__(
88
+						'The "%1$s" encryption key already exists and can not be overwritten because previously encrypted values would no longer be capable of being decrypted.',
89
+						'event_espresso'
90
+					),
91
+					$encryption_key_identifier
92
+				)
93
+			);
94
+		}
95
+		$this->encryption_keys[ $encryption_key_identifier ] = $encryption_key ?: $this->generateEncryptionKey();
96
+		return $this->saveEncryptionKeys();
97
+	}
98
+
99
+
100
+	/**
101
+	 * returns cryptographically secure passphrase. will use default if necessary
102
+	 *
103
+	 * @param string $encryption_key_identifier - used for saving encryption key. will use default if necessary
104
+	 * @param string $generate                  - will generate a new key if the requested one does not exist
105
+	 * @return string
106
+	 * @throws Exception
107
+	 */
108
+	public function getEncryptionKey($encryption_key_identifier = '', $generate = false)
109
+	{
110
+		$encryption_key_identifier = $encryption_key_identifier ?: $this->default_encryption_key_id;
111
+		// ensure keys are loaded
112
+		$this->retrieveEncryptionKeys();
113
+		// if encryption key has not been set
114
+		if (! isset($this->encryption_keys[ $encryption_key_identifier ])) {
115
+			if ($generate) {
116
+				$this->addEncryptionKey($encryption_key_identifier);
117
+			} else {
118
+				throw new OutOfBoundsException(
119
+					sprintf(
120
+						esc_html__('The "%1$s" encryption key was not found or is invalid.', 'event_espresso'),
121
+						$encryption_key_identifier
122
+					)
123
+				);
124
+			}
125
+		}
126
+		return $this->encryption_keys[ $encryption_key_identifier ];
127
+	}
128
+
129
+
130
+	/**
131
+	 * creates a new encryption key
132
+	 *
133
+	 * @param bool $strong if true (default) will attempt to generate a cryptographically secure key
134
+	 * @return string
135
+	 * @throws Exception
136
+	 */
137
+	public function generateEncryptionKey($strong = true)
138
+	{
139
+		return $strong && PHP_VERSION_ID >= 70100
140
+			? $this->generateStrongEncryptionKey()
141
+			: $this->generateWeakEncryptionKey();
142
+	}
143
+
144
+
145
+	/**
146
+	 * creates a new cryptographically secure encryption key
147
+	 *
148
+	 * @return string
149
+	 * @throws Exception
150
+	 */
151
+	protected function generateStrongEncryptionKey()
152
+	{
153
+		// bit_depth needs to be divided by 8
154
+		return random_bytes($this->bit_depth / 8);
155
+	}
156
+
157
+
158
+	/**
159
+	 * creates a new encryption key that should not be trusted to be cryptographically secure
160
+	 *
161
+	 * @return string
162
+	 * @throws Exception
163
+	 */
164
+	protected function generateWeakEncryptionKey()
165
+	{
166
+		// @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
167
+		$iterations    = ceil($this->key_length / 40);
168
+		$random_string = '';
169
+		for ($i = 0; $i < $iterations; $i++) {
170
+			$random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
171
+		}
172
+		return substr($random_string, 0, $this->key_length);
173
+	}
174
+
175
+
176
+	/**
177
+	 * @return int
178
+	 */
179
+	public function bitDepth()
180
+	{
181
+		return $this->bit_depth;
182
+	}
183
+
184
+
185
+	/**
186
+	 * @param int $bit_depth options are 64, 128, 192, or 256
187
+	 */
188
+	public function setBitDepth($bit_depth)
189
+	{
190
+		$bit_depth       = absint($bit_depth);
191
+		$this->bit_depth = in_array($bit_depth, $this->bit_depth_options) ? $bit_depth : 128;
192
+	}
193
+
194
+
195
+	/**
196
+	 * @return int
197
+	 */
198
+	public function keyLength()
199
+	{
200
+		return $this->key_length;
201
+	}
202
+
203
+
204
+	/**
205
+	 * @param int $key_length
206
+	 */
207
+	public function setKeyLength($key_length)
208
+	{
209
+		// let's not let the key length go below 8 or above 128
210
+		$this->key_length = min(max($key_length, 8), 128);
211
+	}
212
+
213
+
214
+	/**
215
+	 * retrieves encryption keys from db
216
+	 *
217
+	 * @return string
218
+	 * @throws Exception
219
+	 */
220
+	protected function retrieveEncryptionKeys()
221
+	{
222
+		// if encryption key has not been set
223
+		if (! empty($this->encryption_keys)) {
224
+			// retrieve encryption_key from db
225
+			$this->encryption_keys = get_option($this->encryption_keys_option_name, null);
226
+			// WHAT?? No encryption_key in the db ??
227
+			if ($this->encryption_keys === null) {
228
+				// let's make one. And md5 it to make it just the right size for a key
229
+				$this->addEncryptionKey($this->default_encryption_key_id);
230
+			}
231
+		}
232
+		return $this->encryption_keys;
233
+	}
234
+
235
+
236
+	/**
237
+	 * saves encryption keys from db
238
+	 *
239
+	 * @return bool
240
+	 */
241
+	protected function saveEncryptionKeys()
242
+	{
243
+		return $this->encryption_keys === null
244
+			? add_option($this->encryption_keys_option_name, $this->encryption_keys)
245
+			: update_option($this->encryption_keys_option_name, $this->encryption_keys);
246
+	}
247 247
 }
Please login to merge, or discard this patch.
core/services/encryption/EncryptionKeyManagerInterface.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -12,55 +12,55 @@
 block discarded – undo
12 12
  */
13 13
 interface EncryptionKeyManagerInterface
14 14
 {
15
-    /**
16
-     * add an encryption key
17
-     *
18
-     * @param string $encryption_key_identifier - name of the encryption key to use
19
-     * @param string $encryption_key            - cryptographically secure passphrase. will generate if necessary
20
-     * @param bool   $overwrite                 - prevents accidental overwriting of an existing key which would be bad
21
-     * @return bool
22
-     */
23
-    public function addEncryptionKey($encryption_key_identifier, $encryption_key = '', $overwrite = false);
15
+	/**
16
+	 * add an encryption key
17
+	 *
18
+	 * @param string $encryption_key_identifier - name of the encryption key to use
19
+	 * @param string $encryption_key            - cryptographically secure passphrase. will generate if necessary
20
+	 * @param bool   $overwrite                 - prevents accidental overwriting of an existing key which would be bad
21
+	 * @return bool
22
+	 */
23
+	public function addEncryptionKey($encryption_key_identifier, $encryption_key = '', $overwrite = false);
24 24
 
25 25
 
26
-    /**
27
-     * returns cryptographically secure passphrase. will use default if necessary
28
-     *
29
-     * @param string $encryption_key_identifier - used for saving encryption key. will use default if necessary
30
-     * @param string $generate                  - will generate a new key if the requested one does not exist
31
-     * @return string
32
-     */
33
-    public function getEncryptionKey($encryption_key_identifier = '', $generate = false);
26
+	/**
27
+	 * returns cryptographically secure passphrase. will use default if necessary
28
+	 *
29
+	 * @param string $encryption_key_identifier - used for saving encryption key. will use default if necessary
30
+	 * @param string $generate                  - will generate a new key if the requested one does not exist
31
+	 * @return string
32
+	 */
33
+	public function getEncryptionKey($encryption_key_identifier = '', $generate = false);
34 34
 
35 35
 
36
-    /**
37
-     * creates a new encryption key
38
-     *
39
-     * @return string
40
-     */
41
-    public function generateEncryptionKey();
36
+	/**
37
+	 * creates a new encryption key
38
+	 *
39
+	 * @return string
40
+	 */
41
+	public function generateEncryptionKey();
42 42
 
43 43
 
44
-    /**
45
-     * @return int
46
-     */
47
-    public function bitDepth();
44
+	/**
45
+	 * @return int
46
+	 */
47
+	public function bitDepth();
48 48
 
49 49
 
50
-    /**
51
-     * @param int $bit_depth options are 128, 192, or 256
52
-     */
53
-    public function setBitDepth($bit_depth);
50
+	/**
51
+	 * @param int $bit_depth options are 128, 192, or 256
52
+	 */
53
+	public function setBitDepth($bit_depth);
54 54
 
55 55
 
56
-    /**
57
-     * @return int
58
-     */
59
-    public function keyLength();
56
+	/**
57
+	 * @return int
58
+	 */
59
+	public function keyLength();
60 60
 
61 61
 
62
-    /**
63
-     * @param int $key_length
64
-     */
65
-    public function setKeyLength($key_length);
62
+	/**
63
+	 * @param int $key_length
64
+	 */
65
+	public function setKeyLength($key_length);
66 66
 }
Please login to merge, or discard this patch.
core/services/encryption/EncryptionMethodInterface.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -12,46 +12,46 @@
 block discarded – undo
12 12
  */
13 13
 interface EncryptionMethodInterface
14 14
 {
15
-    /**
16
-     * returns true if the encryption method is cryptographically secure
17
-     *
18
-     * @return bool
19
-     */
20
-    public function isCryptographicallySecure();
21
-
22
-
23
-    /**
24
-     * returns true if the method can be used on the current server
25
-     *
26
-     * @return bool
27
-     */
28
-    public function canUse();
29
-
30
-
31
-    /**
32
-     * returns a message explaining why the encryption method in question can or can not be used
33
-     *
34
-     * @return string
35
-     */
36
-    public function canUseNotice();
37
-
38
-
39
-    /**
40
-     * encrypts data
41
-     *
42
-     * @param string $text_to_encrypt           - the text to be encrypted
43
-     * @param string $encryption_key_identifier - name of the encryption key to use
44
-     * @return string
45
-     */
46
-    public function encrypt($text_to_encrypt, $encryption_key_identifier = '');
47
-
48
-
49
-    /**
50
-     * decrypts data
51
-     *
52
-     * @param string $encrypted_text            - the text to be decrypted
53
-     * @param string $encryption_key_identifier - name of the encryption key to use
54
-     * @return string
55
-     */
56
-    public function decrypt($encrypted_text, $encryption_key_identifier = '');
15
+	/**
16
+	 * returns true if the encryption method is cryptographically secure
17
+	 *
18
+	 * @return bool
19
+	 */
20
+	public function isCryptographicallySecure();
21
+
22
+
23
+	/**
24
+	 * returns true if the method can be used on the current server
25
+	 *
26
+	 * @return bool
27
+	 */
28
+	public function canUse();
29
+
30
+
31
+	/**
32
+	 * returns a message explaining why the encryption method in question can or can not be used
33
+	 *
34
+	 * @return string
35
+	 */
36
+	public function canUseNotice();
37
+
38
+
39
+	/**
40
+	 * encrypts data
41
+	 *
42
+	 * @param string $text_to_encrypt           - the text to be encrypted
43
+	 * @param string $encryption_key_identifier - name of the encryption key to use
44
+	 * @return string
45
+	 */
46
+	public function encrypt($text_to_encrypt, $encryption_key_identifier = '');
47
+
48
+
49
+	/**
50
+	 * decrypts data
51
+	 *
52
+	 * @param string $encrypted_text            - the text to be decrypted
53
+	 * @param string $encryption_key_identifier - name of the encryption key to use
54
+	 * @return string
55
+	 */
56
+	public function decrypt($encrypted_text, $encryption_key_identifier = '');
57 57
 }
Please login to merge, or discard this patch.
core/services/encryption/Base64Encoder.php 2 patches
Indentation   +148 added lines, -148 removed lines patch added patch discarded remove patch
@@ -15,152 +15,152 @@
 block discarded – undo
15 15
 class Base64Encoder
16 16
 {
17 17
 
18
-    /**
19
-     * @var boolean
20
-     */
21
-    protected $use_base64_encode;
22
-
23
-
24
-    public function __construct()
25
-    {
26
-        $this->use_base64_encode = function_exists('base64_encode');
27
-    }
28
-
29
-
30
-    /**
31
-     * encodes string with PHP's base64 encoding
32
-     *
33
-     * @see http://php.net/manual/en/function.base64-encode.php
34
-     * @param string $text_string the text to be encoded
35
-     * @return string
36
-     */
37
-    public function encodeString($text_string = '')
38
-    {
39
-        // you give me nothing??? GET OUT !
40
-        if (empty($text_string) || ! $this->use_base64_encode) {
41
-            return $text_string;
42
-        }
43
-        // encode
44
-        return base64_encode($text_string);
45
-    }
46
-
47
-
48
-    /**
49
-     * decodes string that has been encoded with PHP's base64 encoding
50
-     *
51
-     * @see http://php.net/manual/en/function.base64-encode.php
52
-     * @param string $encoded_string the text to be decoded
53
-     * @return string
54
-     * @throws RuntimeException
55
-     */
56
-    public function decodeString($encoded_string = '')
57
-    {
58
-        // you give me nothing??? GET OUT !
59
-        if (empty($encoded_string)) {
60
-            return $encoded_string;
61
-        }
62
-        $this->isValidBase64OrFail($encoded_string);
63
-        return $this->decode($encoded_string);
64
-    }
65
-
66
-
67
-    /**
68
-     * @param string $encoded_string the text to be decoded
69
-     * @return string
70
-     * @throws RuntimeException
71
-     */
72
-    private function decode($encoded_string)
73
-    {
74
-        $decoded_string = base64_decode($encoded_string);
75
-        if ($decoded_string === false) {
76
-            throw new RuntimeException(
77
-                esc_html__('Base 64 decoding failed.', 'event_espresso')
78
-            );
79
-        }
80
-        return $decoded_string;
81
-    }
82
-
83
-
84
-    /**
85
-     * encodes  url string with PHP's base64 encoding
86
-     *
87
-     * @see http://php.net/manual/en/function.base64-encode.php
88
-     * @param string $text_string the text to be encoded
89
-     * @return string
90
-     */
91
-    public function encodeUrl($text_string = '')
92
-    {
93
-        // you give me nothing??? GET OUT !
94
-        if (empty($text_string) || ! $this->use_base64_encode) {
95
-            return $text_string;
96
-        }
97
-        // encode
98
-        $encoded_string = base64_encode($text_string);
99
-        // remove some chars to make encoding more URL friendly
100
-        return rtrim(strtr($encoded_string, '+/', '-_'), '=');
101
-    }
102
-
103
-
104
-    /**
105
-     * decodes  url string that has been encoded with PHP's base64 encoding
106
-     *
107
-     * @see http://php.net/manual/en/function.base64-encode.php
108
-     * @param string $encoded_string the text to be decoded
109
-     * @return string
110
-     * @throws RuntimeException
111
-     */
112
-    public function decodeUrl($encoded_string = '')
113
-    {
114
-        // you give me nothing??? GET OUT !
115
-        if (empty($encoded_string)) {
116
-            return $encoded_string;
117
-        }
118
-        // replace previously removed characters
119
-        $encoded_string = strtr($encoded_string, '-_', '+/');
120
-        $encoded_string .= str_repeat('=', 3 - (3 + strlen($encoded_string)) % 4);
121
-        $this->isValidBase64OrFail($encoded_string);
122
-        return $this->decode($encoded_string);
123
-    }
124
-
125
-
126
-    /**
127
-     * @param string $encoded_string the text to be decoded
128
-     * @throws RuntimeException
129
-     */
130
-    public function isValidBase64OrFail($encoded_string)
131
-    {
132
-        if (! $this->isValidBase64($encoded_string)) {
133
-            throw new RuntimeException(
134
-                esc_html__(
135
-                    'Base 64 decoding failed because the supplied string is not valid or was not base64 encoded.',
136
-                    'event_espresso'
137
-                )
138
-            );
139
-        }
140
-    }
141
-
142
-
143
-    /**
144
-     * @see https://stackoverflow.com/a/51877882
145
-     * @param $string
146
-     * @param array $encodings
147
-     * @return bool
148
-     */
149
-    public function isValidBase64($string, $encodings = [])
150
-    {
151
-        // ensure data is a string
152
-        if (! is_string($string) || ! $this->use_base64_encode) {
153
-            return false;
154
-        }
155
-        // first check if we're dealing with an actual valid base64 encoded string
156
-        $decoded = base64_decode($string, true);
157
-        // also re-encode and compare it to original one
158
-        if ($decoded === false || base64_encode($decoded) !== $string) {
159
-            return false;
160
-        }
161
-        // finally, check whether the decoded data is actual text
162
-        $encodings = ! empty($encodings) ?: ['UTF-8', 'ASCII'];
163
-        $encoding = mb_detect_encoding($decoded);
164
-        return in_array($encoding, $encodings);
165
-    }
18
+	/**
19
+	 * @var boolean
20
+	 */
21
+	protected $use_base64_encode;
22
+
23
+
24
+	public function __construct()
25
+	{
26
+		$this->use_base64_encode = function_exists('base64_encode');
27
+	}
28
+
29
+
30
+	/**
31
+	 * encodes string with PHP's base64 encoding
32
+	 *
33
+	 * @see http://php.net/manual/en/function.base64-encode.php
34
+	 * @param string $text_string the text to be encoded
35
+	 * @return string
36
+	 */
37
+	public function encodeString($text_string = '')
38
+	{
39
+		// you give me nothing??? GET OUT !
40
+		if (empty($text_string) || ! $this->use_base64_encode) {
41
+			return $text_string;
42
+		}
43
+		// encode
44
+		return base64_encode($text_string);
45
+	}
46
+
47
+
48
+	/**
49
+	 * decodes string that has been encoded with PHP's base64 encoding
50
+	 *
51
+	 * @see http://php.net/manual/en/function.base64-encode.php
52
+	 * @param string $encoded_string the text to be decoded
53
+	 * @return string
54
+	 * @throws RuntimeException
55
+	 */
56
+	public function decodeString($encoded_string = '')
57
+	{
58
+		// you give me nothing??? GET OUT !
59
+		if (empty($encoded_string)) {
60
+			return $encoded_string;
61
+		}
62
+		$this->isValidBase64OrFail($encoded_string);
63
+		return $this->decode($encoded_string);
64
+	}
65
+
66
+
67
+	/**
68
+	 * @param string $encoded_string the text to be decoded
69
+	 * @return string
70
+	 * @throws RuntimeException
71
+	 */
72
+	private function decode($encoded_string)
73
+	{
74
+		$decoded_string = base64_decode($encoded_string);
75
+		if ($decoded_string === false) {
76
+			throw new RuntimeException(
77
+				esc_html__('Base 64 decoding failed.', 'event_espresso')
78
+			);
79
+		}
80
+		return $decoded_string;
81
+	}
82
+
83
+
84
+	/**
85
+	 * encodes  url string with PHP's base64 encoding
86
+	 *
87
+	 * @see http://php.net/manual/en/function.base64-encode.php
88
+	 * @param string $text_string the text to be encoded
89
+	 * @return string
90
+	 */
91
+	public function encodeUrl($text_string = '')
92
+	{
93
+		// you give me nothing??? GET OUT !
94
+		if (empty($text_string) || ! $this->use_base64_encode) {
95
+			return $text_string;
96
+		}
97
+		// encode
98
+		$encoded_string = base64_encode($text_string);
99
+		// remove some chars to make encoding more URL friendly
100
+		return rtrim(strtr($encoded_string, '+/', '-_'), '=');
101
+	}
102
+
103
+
104
+	/**
105
+	 * decodes  url string that has been encoded with PHP's base64 encoding
106
+	 *
107
+	 * @see http://php.net/manual/en/function.base64-encode.php
108
+	 * @param string $encoded_string the text to be decoded
109
+	 * @return string
110
+	 * @throws RuntimeException
111
+	 */
112
+	public function decodeUrl($encoded_string = '')
113
+	{
114
+		// you give me nothing??? GET OUT !
115
+		if (empty($encoded_string)) {
116
+			return $encoded_string;
117
+		}
118
+		// replace previously removed characters
119
+		$encoded_string = strtr($encoded_string, '-_', '+/');
120
+		$encoded_string .= str_repeat('=', 3 - (3 + strlen($encoded_string)) % 4);
121
+		$this->isValidBase64OrFail($encoded_string);
122
+		return $this->decode($encoded_string);
123
+	}
124
+
125
+
126
+	/**
127
+	 * @param string $encoded_string the text to be decoded
128
+	 * @throws RuntimeException
129
+	 */
130
+	public function isValidBase64OrFail($encoded_string)
131
+	{
132
+		if (! $this->isValidBase64($encoded_string)) {
133
+			throw new RuntimeException(
134
+				esc_html__(
135
+					'Base 64 decoding failed because the supplied string is not valid or was not base64 encoded.',
136
+					'event_espresso'
137
+				)
138
+			);
139
+		}
140
+	}
141
+
142
+
143
+	/**
144
+	 * @see https://stackoverflow.com/a/51877882
145
+	 * @param $string
146
+	 * @param array $encodings
147
+	 * @return bool
148
+	 */
149
+	public function isValidBase64($string, $encodings = [])
150
+	{
151
+		// ensure data is a string
152
+		if (! is_string($string) || ! $this->use_base64_encode) {
153
+			return false;
154
+		}
155
+		// first check if we're dealing with an actual valid base64 encoded string
156
+		$decoded = base64_decode($string, true);
157
+		// also re-encode and compare it to original one
158
+		if ($decoded === false || base64_encode($decoded) !== $string) {
159
+			return false;
160
+		}
161
+		// finally, check whether the decoded data is actual text
162
+		$encodings = ! empty($encodings) ?: ['UTF-8', 'ASCII'];
163
+		$encoding = mb_detect_encoding($decoded);
164
+		return in_array($encoding, $encodings);
165
+	}
166 166
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
      */
130 130
     public function isValidBase64OrFail($encoded_string)
131 131
     {
132
-        if (! $this->isValidBase64($encoded_string)) {
132
+        if ( ! $this->isValidBase64($encoded_string)) {
133 133
             throw new RuntimeException(
134 134
                 esc_html__(
135 135
                     'Base 64 decoding failed because the supplied string is not valid or was not base64 encoded.',
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
     public function isValidBase64($string, $encodings = [])
150 150
     {
151 151
         // ensure data is a string
152
-        if (! is_string($string) || ! $this->use_base64_encode) {
152
+        if ( ! is_string($string) || ! $this->use_base64_encode) {
153 153
             return false;
154 154
         }
155 155
         // first check if we're dealing with an actual valid base64 encoded string
Please login to merge, or discard this patch.
core/services/encryption/openssl/CipherMethod.php 1 patch
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -15,154 +15,154 @@
 block discarded – undo
15 15
 class CipherMethod
16 16
 {
17 17
 
18
-    /**
19
-     * @var string
20
-     */
21
-    private $cipher_method_option_name;
22
-
23
-    /**
24
-     * @var array
25
-     */
26
-    private $cipher_methods = [];
27
-
28
-    /**
29
-     * @var string
30
-     */
31
-    private $default_cipher_method;
32
-
33
-    /**
34
-     * the OpenSSL cipher method to use. default: AES-128-CBC
35
-     *
36
-     * @var string
37
-     */
38
-    private $validated_cipher_method;
39
-
40
-    /**
41
-     * as early as Aug 2016, Openssl declared the following weak: RC2, RC4, DES, 3DES, MD5 based
42
-     * and ECB mode should be avoided
43
-     *
44
-     * @var array
45
-     */
46
-    private $weak_algorithms = ['des', 'ecb', 'md5', 'rc2', 'rc4'];
47
-
48
-
49
-    /**
50
-     * @param string $default_cipher_method
51
-     * @param string $cipher_method_option_name
52
-     */
53
-    public function __construct($default_cipher_method, $cipher_method_option_name)
54
-    {
55
-        $this->default_cipher_method     = $default_cipher_method;
56
-        $this->cipher_method_option_name = $cipher_method_option_name;
57
-    }
58
-
59
-
60
-    /**
61
-     * Returns a cipher method that has been verified to work.
62
-     * First checks if the cached cipher has been set already and if so, returns that.
63
-     * Then tests the incoming default and returns that if it's good.
64
-     * If not, then it retrieves the previously tested and saved cipher method.
65
-     * But if that doesn't exist, then calls getAvailableCipherMethod()
66
-     * to see what is available on the server, and returns the results.
67
-     *
68
-     * @param string $cipher_method
69
-     * @return string
70
-     * @throws RuntimeException
71
-     */
72
-    public function getCipherMethod($cipher_method = null)
73
-    {
74
-        $cipher_method = $cipher_method ?: $this->default_cipher_method;
75
-        if ($this->validated_cipher_method === null) {
76
-            // verify that the default cipher method can produce an initialization vector
77
-            if (openssl_cipher_iv_length($cipher_method) === false) {
78
-                // nope? okay let's get what we found in the past to work
79
-                $cipher_method = get_option($this->cipher_method_option_name, '');
80
-                // oops... haven't tested available cipher methods yet
81
-                if ($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
82
-                    $cipher_method = $this->getAvailableCipherMethod($cipher_method);
83
-                }
84
-            }
85
-            $this->validated_cipher_method = $cipher_method;
86
-        }
87
-        return $this->validated_cipher_method;
88
-    }
89
-
90
-
91
-    /**
92
-     * returns true if the selected cipher method either uses Galois/Counter Mode (GCM)
93
-     * or Counter with CBC-MAC (CCM) authenticated encryption modes
94
-     * (also need to be using PHP 7.1 or greater to actually use authenticated encryption modes)
95
-     *
96
-     * @return bool
97
-     */
98
-    public function usesAuthenticatedEncryptionMode()
99
-    {
100
-        return PHP_VERSION_ID >= 70100
101
-               && (
102
-                   stripos($this->validated_cipher_method, 'gcm') !== false
103
-                   || stripos($this->validated_cipher_method, 'ccm') !== false
104
-               );
105
-    }
106
-
107
-
108
-    /**
109
-     * @param string $cipher_method
110
-     * @return string
111
-     * @throws RuntimeException
112
-     */
113
-    private function getAvailableCipherMethod($cipher_method)
114
-    {
115
-        // verify that the incoming cipher method can produce an initialization vector
116
-        if (openssl_cipher_iv_length($cipher_method) === false) {
117
-            // what? there's no list?
118
-            if (empty($this->cipher_methods)) {
119
-                // generate that list and cache it
120
-                $this->cipher_methods = $this->getAvailableStrongCipherMethods();
121
-                // then grab the first item from the list
122
-                $cipher_method = reset($this->cipher_methods);
123
-            } else {
124
-                // check the next cipher in the list of available cipher methods
125
-                $cipher_method = next($this->cipher_methods);
126
-            }
127
-            if ($cipher_method === false) {
128
-                throw new RuntimeException(
129
-                    esc_html__(
130
-                        'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
131
-                        'event_espresso'
132
-                    )
133
-                );
134
-            }
135
-            // verify that the next cipher method works
136
-            return $this->getAvailableCipherMethod($cipher_method);
137
-        }
138
-        // if we've gotten this far, then we found an available cipher method that works
139
-        // so save that for next time
140
-        update_option($this->cipher_method_option_name, $cipher_method);
141
-        return $cipher_method;
142
-    }
143
-
144
-
145
-    /**
146
-     * @return array
147
-     */
148
-    private function getAvailableStrongCipherMethods()
149
-    {
150
-        $cipher_methods = openssl_get_cipher_methods();
151
-        return array_filter($cipher_methods, [$this, 'weakAlgorithmFilter']);
152
-    }
153
-
154
-
155
-    /**
156
-     * @see https://www.php.net/manual/en/function.openssl-get-cipher-methods.php#example-890
157
-     * @param string $cipher_method
158
-     */
159
-    private function weakAlgorithmFilter($cipher_method)
160
-    {
161
-        foreach ($this->weak_algorithms as $weak_algorithm) {
162
-            if (stripos($cipher_method, $weak_algorithm) !== false) {
163
-                return false;
164
-            }
165
-        }
166
-        return true;
167
-    }
18
+	/**
19
+	 * @var string
20
+	 */
21
+	private $cipher_method_option_name;
22
+
23
+	/**
24
+	 * @var array
25
+	 */
26
+	private $cipher_methods = [];
27
+
28
+	/**
29
+	 * @var string
30
+	 */
31
+	private $default_cipher_method;
32
+
33
+	/**
34
+	 * the OpenSSL cipher method to use. default: AES-128-CBC
35
+	 *
36
+	 * @var string
37
+	 */
38
+	private $validated_cipher_method;
39
+
40
+	/**
41
+	 * as early as Aug 2016, Openssl declared the following weak: RC2, RC4, DES, 3DES, MD5 based
42
+	 * and ECB mode should be avoided
43
+	 *
44
+	 * @var array
45
+	 */
46
+	private $weak_algorithms = ['des', 'ecb', 'md5', 'rc2', 'rc4'];
47
+
48
+
49
+	/**
50
+	 * @param string $default_cipher_method
51
+	 * @param string $cipher_method_option_name
52
+	 */
53
+	public function __construct($default_cipher_method, $cipher_method_option_name)
54
+	{
55
+		$this->default_cipher_method     = $default_cipher_method;
56
+		$this->cipher_method_option_name = $cipher_method_option_name;
57
+	}
58
+
59
+
60
+	/**
61
+	 * Returns a cipher method that has been verified to work.
62
+	 * First checks if the cached cipher has been set already and if so, returns that.
63
+	 * Then tests the incoming default and returns that if it's good.
64
+	 * If not, then it retrieves the previously tested and saved cipher method.
65
+	 * But if that doesn't exist, then calls getAvailableCipherMethod()
66
+	 * to see what is available on the server, and returns the results.
67
+	 *
68
+	 * @param string $cipher_method
69
+	 * @return string
70
+	 * @throws RuntimeException
71
+	 */
72
+	public function getCipherMethod($cipher_method = null)
73
+	{
74
+		$cipher_method = $cipher_method ?: $this->default_cipher_method;
75
+		if ($this->validated_cipher_method === null) {
76
+			// verify that the default cipher method can produce an initialization vector
77
+			if (openssl_cipher_iv_length($cipher_method) === false) {
78
+				// nope? okay let's get what we found in the past to work
79
+				$cipher_method = get_option($this->cipher_method_option_name, '');
80
+				// oops... haven't tested available cipher methods yet
81
+				if ($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
82
+					$cipher_method = $this->getAvailableCipherMethod($cipher_method);
83
+				}
84
+			}
85
+			$this->validated_cipher_method = $cipher_method;
86
+		}
87
+		return $this->validated_cipher_method;
88
+	}
89
+
90
+
91
+	/**
92
+	 * returns true if the selected cipher method either uses Galois/Counter Mode (GCM)
93
+	 * or Counter with CBC-MAC (CCM) authenticated encryption modes
94
+	 * (also need to be using PHP 7.1 or greater to actually use authenticated encryption modes)
95
+	 *
96
+	 * @return bool
97
+	 */
98
+	public function usesAuthenticatedEncryptionMode()
99
+	{
100
+		return PHP_VERSION_ID >= 70100
101
+			   && (
102
+				   stripos($this->validated_cipher_method, 'gcm') !== false
103
+				   || stripos($this->validated_cipher_method, 'ccm') !== false
104
+			   );
105
+	}
106
+
107
+
108
+	/**
109
+	 * @param string $cipher_method
110
+	 * @return string
111
+	 * @throws RuntimeException
112
+	 */
113
+	private function getAvailableCipherMethod($cipher_method)
114
+	{
115
+		// verify that the incoming cipher method can produce an initialization vector
116
+		if (openssl_cipher_iv_length($cipher_method) === false) {
117
+			// what? there's no list?
118
+			if (empty($this->cipher_methods)) {
119
+				// generate that list and cache it
120
+				$this->cipher_methods = $this->getAvailableStrongCipherMethods();
121
+				// then grab the first item from the list
122
+				$cipher_method = reset($this->cipher_methods);
123
+			} else {
124
+				// check the next cipher in the list of available cipher methods
125
+				$cipher_method = next($this->cipher_methods);
126
+			}
127
+			if ($cipher_method === false) {
128
+				throw new RuntimeException(
129
+					esc_html__(
130
+						'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
131
+						'event_espresso'
132
+					)
133
+				);
134
+			}
135
+			// verify that the next cipher method works
136
+			return $this->getAvailableCipherMethod($cipher_method);
137
+		}
138
+		// if we've gotten this far, then we found an available cipher method that works
139
+		// so save that for next time
140
+		update_option($this->cipher_method_option_name, $cipher_method);
141
+		return $cipher_method;
142
+	}
143
+
144
+
145
+	/**
146
+	 * @return array
147
+	 */
148
+	private function getAvailableStrongCipherMethods()
149
+	{
150
+		$cipher_methods = openssl_get_cipher_methods();
151
+		return array_filter($cipher_methods, [$this, 'weakAlgorithmFilter']);
152
+	}
153
+
154
+
155
+	/**
156
+	 * @see https://www.php.net/manual/en/function.openssl-get-cipher-methods.php#example-890
157
+	 * @param string $cipher_method
158
+	 */
159
+	private function weakAlgorithmFilter($cipher_method)
160
+	{
161
+		foreach ($this->weak_algorithms as $weak_algorithm) {
162
+			if (stripos($cipher_method, $weak_algorithm) !== false) {
163
+				return false;
164
+			}
165
+		}
166
+		return true;
167
+	}
168 168
 }
Please login to merge, or discard this patch.
core/services/encryption/openssl/OpenSSL.php 2 patches
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -18,222 +18,222 @@
 block discarded – undo
18 18
 abstract class OpenSSL implements EncryptionMethodInterface
19 19
 {
20 20
 
21
-    /**
22
-     * the default OPENSSL digest method to use
23
-     */
24
-    const DEFAULT_DIGEST_METHOD = 'sha512';
25
-
26
-    /**
27
-     * separates the encrypted text from the initialization vector
28
-     */
29
-    const IV_DELIMITER = ':iv:';
30
-
31
-    /**
32
-     * @var Base64Encoder
33
-     */
34
-    protected $base64_encoder;
35
-
36
-    /**
37
-     * @var CipherMethod
38
-     */
39
-    protected $cipher_method;
40
-
41
-    /**
42
-     * @var array $digest_methods
43
-     */
44
-    private $digest_methods = [];
45
-
46
-    /**
47
-     * @var EncryptionKeyManagerInterface
48
-     */
49
-    protected $encryption_key_manager;
50
-
51
-    /**
52
-     * @var boolean
53
-     */
54
-    private $openssl_installed;
55
-
56
-    /**
57
-     * @var string
58
-     */
59
-    private $min_php_version;
60
-
61
-    /**
62
-     * @var string
63
-     */
64
-    private $hash_algorithm;
65
-
66
-
67
-    /**
68
-     * To use custom a cipher method and/or encryption keys:
69
-     *  - extend this class
70
-     *  - configure a new CipherMethod / EncryptionKeyManager in the constructor
71
-     *  - pass those to this constructor, like so:
72
-     *
73
-     *      public function __construct(Base64Encoder $base64_encoder) {
74
-     *          parent::__construct(
75
-     *              $base64_encoder,
76
-     *              new CipherMethod(CIPHER_METHOD, CIPHER_METHOD_OPTION_NAME)
77
-     *              new EncryptionKeyManager(CUSTOM_KEY_ID, CUSTOM_KEYS_OPTION_NAME)
78
-     *          );
79
-     *      }
80
-     *
81
-     * @param Base64Encoder                      $base64_encoder
82
-     * @param CipherMethod                       $cipher_method
83
-     * @param EncryptionKeyManagerInterface|null $encryption_key_manager
84
-     * @param string                             $min_php_version
85
-     */
86
-    protected function __construct(
87
-        Base64Encoder                 $base64_encoder,
88
-        CipherMethod                  $cipher_method,
89
-        EncryptionKeyManagerInterface $encryption_key_manager,
90
-                                      $min_php_version
91
-    ) {
92
-        $this->base64_encoder         = $base64_encoder;
93
-        $this->cipher_method          = $cipher_method;
94
-        $this->encryption_key_manager = $encryption_key_manager;
95
-        $this->min_php_version        = $min_php_version;
96
-        $this->openssl_installed      = extension_loaded('openssl');
97
-    }
98
-
99
-
100
-    /**
101
-     * @return bool
102
-     */
103
-    public function isCryptographicallySecure()
104
-    {
105
-        return true;
106
-    }
107
-
108
-
109
-    /**
110
-     * @return bool
111
-     */
112
-    public function canUse()
113
-    {
114
-        return $this->openssl_installed && version_compare(PHP_VERSION, $this->min_php_version, '>=');
115
-    }
116
-
117
-
118
-    /**
119
-     * @return string
120
-     */
121
-    public function canUseNotice()
122
-    {
123
-        if (! $this->openssl_installed) {
124
-            return esc_html__(
125
-                'The PHP openssl server extension is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
126
-                'event_espresso'
127
-            );
128
-        }
129
-        if (version_compare(PHP_VERSION, $this->min_php_version, '<')) {
130
-            return sprintf(
131
-                esc_html__(
132
-                    'PHP version %1$s or greater is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
133
-                    'event_espresso'
134
-                ),
135
-                $this->min_php_version
136
-            );
137
-        }
138
-        return sprintf(
139
-            esc_html__('OpenSSL v1 encryption using %1$S is available for use.', 'event_espresso'),
140
-            OpenSSLv1::CIPHER_METHOD
141
-        );
142
-    }
143
-
144
-
145
-    /**
146
-     * Computes the digest hash value using the specified digest method.
147
-     * If that digest method fails to produce a valid hash value,
148
-     * then we'll grab the next digest method and recursively try again until something works.
149
-     *
150
-     * @param string $encryption_key
151
-     * @param string $digest_method
152
-     * @param bool   $return_raw_data
153
-     * @return string
154
-     * @throws RuntimeException
155
-     */
156
-    protected function getDigestHashValue(
157
-        $encryption_key,
158
-        $digest_method = OpenSSL::DEFAULT_DIGEST_METHOD,
159
-        $return_raw_data = false
160
-    ) {
161
-        $digest_hash_value = openssl_digest($encryption_key, $digest_method, $return_raw_data);
162
-        if ($digest_hash_value === false) {
163
-            return $this->getDigestHashValue($this->getDigestMethod());
164
-        }
165
-        return $digest_hash_value;
166
-    }
167
-
168
-
169
-    /**
170
-     * Returns the NEXT element in the $digest_methods array.
171
-     * If the $digest_methods array is empty, then we populate it
172
-     * with the available values returned from openssl_get_md_methods().
173
-     *
174
-     * @return string
175
-     * @throws RuntimeException
176
-     */
177
-    private function getDigestMethod()
178
-    {
179
-        $digest_method = prev($this->digest_methods);
180
-        if (empty($this->digest_methods)) {
181
-            $this->digest_methods = openssl_get_md_methods();
182
-            $digest_method        = end($this->digest_methods);
183
-        }
184
-        if ($digest_method === false) {
185
-            throw new RuntimeException(
186
-                esc_html__(
187
-                    'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
188
-                    'event_espresso'
189
-                )
190
-            );
191
-        }
192
-        return $digest_method;
193
-    }
194
-
195
-
196
-    /**
197
-     * @param string $encryption_key
198
-     * @return int
199
-     */
200
-    protected function calculateHashLength($encryption_key)
201
-    {
202
-        // get existing key length
203
-        $prev_key_length = $this->encryption_key_manager->keyLength();
204
-        // set it to something HUGE
205
-        $this->encryption_key_manager->setKeyLength(512);
206
-        // generate a new weak key, which should just be a really long random string
207
-        $test_text = $this->encryption_key_manager->generateEncryptionKey(false);
208
-        // generate a hash using our test string and our real $encryption_key
209
-        $hash = hash_hmac($this->getHashAlgorithm(), $test_text, $encryption_key, true);
210
-        // reset key length back to original value
211
-        $this->encryption_key_manager->setKeyLength($prev_key_length);
212
-        // return the length of the hash
213
-        return strlen($hash);
214
-    }
215
-
216
-
217
-    /**
218
-     * @return string
219
-     */
220
-    protected function getHashAlgorithm()
221
-    {
222
-        if (! $this->hash_algorithm) {
223
-            // get installed hashing algorithms
224
-            $hash_algorithms = hash_algos();
225
-            // filter array for "sha" algorithms
226
-            $hash_algorithms = preg_grep('/^sha\d{3}$/gi', $hash_algorithms);
227
-            // if no sha algorithms are installed, then just use md5
228
-            if (empty($hash_algorithms)) {
229
-                $this->hash_algorithm = 'md5';
230
-                return $this->hash_algorithm;
231
-            }
232
-            // sort ascending using "natural ordering"
233
-            sort($hash_algorithms, SORT_NATURAL);
234
-            // return last item from array, which should be the strongest installed sha hash
235
-            $this->hash_algorithm = array_pop($hash_algorithms);
236
-        }
237
-        return $this->hash_algorithm;
238
-    }
21
+	/**
22
+	 * the default OPENSSL digest method to use
23
+	 */
24
+	const DEFAULT_DIGEST_METHOD = 'sha512';
25
+
26
+	/**
27
+	 * separates the encrypted text from the initialization vector
28
+	 */
29
+	const IV_DELIMITER = ':iv:';
30
+
31
+	/**
32
+	 * @var Base64Encoder
33
+	 */
34
+	protected $base64_encoder;
35
+
36
+	/**
37
+	 * @var CipherMethod
38
+	 */
39
+	protected $cipher_method;
40
+
41
+	/**
42
+	 * @var array $digest_methods
43
+	 */
44
+	private $digest_methods = [];
45
+
46
+	/**
47
+	 * @var EncryptionKeyManagerInterface
48
+	 */
49
+	protected $encryption_key_manager;
50
+
51
+	/**
52
+	 * @var boolean
53
+	 */
54
+	private $openssl_installed;
55
+
56
+	/**
57
+	 * @var string
58
+	 */
59
+	private $min_php_version;
60
+
61
+	/**
62
+	 * @var string
63
+	 */
64
+	private $hash_algorithm;
65
+
66
+
67
+	/**
68
+	 * To use custom a cipher method and/or encryption keys:
69
+	 *  - extend this class
70
+	 *  - configure a new CipherMethod / EncryptionKeyManager in the constructor
71
+	 *  - pass those to this constructor, like so:
72
+	 *
73
+	 *      public function __construct(Base64Encoder $base64_encoder) {
74
+	 *          parent::__construct(
75
+	 *              $base64_encoder,
76
+	 *              new CipherMethod(CIPHER_METHOD, CIPHER_METHOD_OPTION_NAME)
77
+	 *              new EncryptionKeyManager(CUSTOM_KEY_ID, CUSTOM_KEYS_OPTION_NAME)
78
+	 *          );
79
+	 *      }
80
+	 *
81
+	 * @param Base64Encoder                      $base64_encoder
82
+	 * @param CipherMethod                       $cipher_method
83
+	 * @param EncryptionKeyManagerInterface|null $encryption_key_manager
84
+	 * @param string                             $min_php_version
85
+	 */
86
+	protected function __construct(
87
+		Base64Encoder                 $base64_encoder,
88
+		CipherMethod                  $cipher_method,
89
+		EncryptionKeyManagerInterface $encryption_key_manager,
90
+									  $min_php_version
91
+	) {
92
+		$this->base64_encoder         = $base64_encoder;
93
+		$this->cipher_method          = $cipher_method;
94
+		$this->encryption_key_manager = $encryption_key_manager;
95
+		$this->min_php_version        = $min_php_version;
96
+		$this->openssl_installed      = extension_loaded('openssl');
97
+	}
98
+
99
+
100
+	/**
101
+	 * @return bool
102
+	 */
103
+	public function isCryptographicallySecure()
104
+	{
105
+		return true;
106
+	}
107
+
108
+
109
+	/**
110
+	 * @return bool
111
+	 */
112
+	public function canUse()
113
+	{
114
+		return $this->openssl_installed && version_compare(PHP_VERSION, $this->min_php_version, '>=');
115
+	}
116
+
117
+
118
+	/**
119
+	 * @return string
120
+	 */
121
+	public function canUseNotice()
122
+	{
123
+		if (! $this->openssl_installed) {
124
+			return esc_html__(
125
+				'The PHP openssl server extension is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
126
+				'event_espresso'
127
+			);
128
+		}
129
+		if (version_compare(PHP_VERSION, $this->min_php_version, '<')) {
130
+			return sprintf(
131
+				esc_html__(
132
+					'PHP version %1$s or greater is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
133
+					'event_espresso'
134
+				),
135
+				$this->min_php_version
136
+			);
137
+		}
138
+		return sprintf(
139
+			esc_html__('OpenSSL v1 encryption using %1$S is available for use.', 'event_espresso'),
140
+			OpenSSLv1::CIPHER_METHOD
141
+		);
142
+	}
143
+
144
+
145
+	/**
146
+	 * Computes the digest hash value using the specified digest method.
147
+	 * If that digest method fails to produce a valid hash value,
148
+	 * then we'll grab the next digest method and recursively try again until something works.
149
+	 *
150
+	 * @param string $encryption_key
151
+	 * @param string $digest_method
152
+	 * @param bool   $return_raw_data
153
+	 * @return string
154
+	 * @throws RuntimeException
155
+	 */
156
+	protected function getDigestHashValue(
157
+		$encryption_key,
158
+		$digest_method = OpenSSL::DEFAULT_DIGEST_METHOD,
159
+		$return_raw_data = false
160
+	) {
161
+		$digest_hash_value = openssl_digest($encryption_key, $digest_method, $return_raw_data);
162
+		if ($digest_hash_value === false) {
163
+			return $this->getDigestHashValue($this->getDigestMethod());
164
+		}
165
+		return $digest_hash_value;
166
+	}
167
+
168
+
169
+	/**
170
+	 * Returns the NEXT element in the $digest_methods array.
171
+	 * If the $digest_methods array is empty, then we populate it
172
+	 * with the available values returned from openssl_get_md_methods().
173
+	 *
174
+	 * @return string
175
+	 * @throws RuntimeException
176
+	 */
177
+	private function getDigestMethod()
178
+	{
179
+		$digest_method = prev($this->digest_methods);
180
+		if (empty($this->digest_methods)) {
181
+			$this->digest_methods = openssl_get_md_methods();
182
+			$digest_method        = end($this->digest_methods);
183
+		}
184
+		if ($digest_method === false) {
185
+			throw new RuntimeException(
186
+				esc_html__(
187
+					'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
188
+					'event_espresso'
189
+				)
190
+			);
191
+		}
192
+		return $digest_method;
193
+	}
194
+
195
+
196
+	/**
197
+	 * @param string $encryption_key
198
+	 * @return int
199
+	 */
200
+	protected function calculateHashLength($encryption_key)
201
+	{
202
+		// get existing key length
203
+		$prev_key_length = $this->encryption_key_manager->keyLength();
204
+		// set it to something HUGE
205
+		$this->encryption_key_manager->setKeyLength(512);
206
+		// generate a new weak key, which should just be a really long random string
207
+		$test_text = $this->encryption_key_manager->generateEncryptionKey(false);
208
+		// generate a hash using our test string and our real $encryption_key
209
+		$hash = hash_hmac($this->getHashAlgorithm(), $test_text, $encryption_key, true);
210
+		// reset key length back to original value
211
+		$this->encryption_key_manager->setKeyLength($prev_key_length);
212
+		// return the length of the hash
213
+		return strlen($hash);
214
+	}
215
+
216
+
217
+	/**
218
+	 * @return string
219
+	 */
220
+	protected function getHashAlgorithm()
221
+	{
222
+		if (! $this->hash_algorithm) {
223
+			// get installed hashing algorithms
224
+			$hash_algorithms = hash_algos();
225
+			// filter array for "sha" algorithms
226
+			$hash_algorithms = preg_grep('/^sha\d{3}$/gi', $hash_algorithms);
227
+			// if no sha algorithms are installed, then just use md5
228
+			if (empty($hash_algorithms)) {
229
+				$this->hash_algorithm = 'md5';
230
+				return $this->hash_algorithm;
231
+			}
232
+			// sort ascending using "natural ordering"
233
+			sort($hash_algorithms, SORT_NATURAL);
234
+			// return last item from array, which should be the strongest installed sha hash
235
+			$this->hash_algorithm = array_pop($hash_algorithms);
236
+		}
237
+		return $this->hash_algorithm;
238
+	}
239 239
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
      */
121 121
     public function canUseNotice()
122 122
     {
123
-        if (! $this->openssl_installed) {
123
+        if ( ! $this->openssl_installed) {
124 124
             return esc_html__(
125 125
                 'The PHP openssl server extension is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
126 126
                 'event_espresso'
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
      */
220 220
     protected function getHashAlgorithm()
221 221
     {
222
-        if (! $this->hash_algorithm) {
222
+        if ( ! $this->hash_algorithm) {
223 223
             // get installed hashing algorithms
224 224
             $hash_algorithms = hash_algos();
225 225
             // filter array for "sha" algorithms
Please login to merge, or discard this patch.
core/services/encryption/openssl/OpenSSLv2.php 2 patches
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -19,227 +19,227 @@
 block discarded – undo
19 19
 class OpenSSLv2 extends OpenSSL
20 20
 {
21 21
 
22
-    /**
23
-     * name used for a default encryption key in case no others are set
24
-     */
25
-    const DEFAULT_ENCRYPTION_KEY_ID = 'default_openssl_v2_key';
26
-
27
-    /**
28
-     * name used for saving encryption keys to the wp_options table
29
-     */
30
-    const ENCRYPTION_KEYS_OPTION_NAME = 'ee_openssl_v2_encryption_keys';
31
-
32
-    /**
33
-     * the OPENSSL cipher method used
34
-     */
35
-    const CIPHER_METHOD = 'aes-256-gcm';
36
-
37
-    /**
38
-     * WP "options_name" used to store a verified available cipher method
39
-     */
40
-    const CIPHER_METHOD_OPTION_NAME = 'ee_openssl_v2_cipher_method';
41
-
42
-    /**
43
-     * The length of the authentication tag. Its value can be between 4 and 16 for GCM mode.
44
-     */
45
-    const AUTH_TAG_LENGTH = 16;
46
-
47
-
48
-    /**
49
-     * To use custom a cipher method and/or encryption keys and/or minimum PHP version:
50
-     *  - extend this class
51
-     *  - configure a new CipherMethod / EncryptionKeyManager in the constructor
52
-     *  - pass those to this constructor, like so:
53
-     *
54
-     *      public function __construct(Base64Encoder $base64_encoder) {
55
-     *          parent::__construct(
56
-     *              $base64_encoder,
57
-     *              new CipherMethod(CIPHER_METHOD, CIPHER_METHOD_OPTION_NAME),
58
-     *              new EncryptionKeyManager(CUSTOM_KEY_ID, CUSTOM_KEYS_OPTION_NAME),
59
-     *              '7.1.0'
60
-     *          );
61
-     *      }
62
-     *
63
-     * @param Base64Encoder                      $base64_encoder
64
-     * @param CipherMethod|null                  $cipher_method
65
-     * @param EncryptionKeyManagerInterface|null $encryption_key_manager
66
-     * @param string                             $min_php_version defaults to 7.1.0
67
-     *                                                            (when openssl auth tag and random_bytes() were added)
68
-     */
69
-    public function __construct(
70
-        Base64Encoder                 $base64_encoder,
71
-        CipherMethod                  $cipher_method = null,
72
-        EncryptionKeyManagerInterface $encryption_key_manager = null,
73
-                                      $min_php_version = '7.1.0'
74
-    ) {
75
-        parent::__construct(
76
-            $base64_encoder,
77
-            $cipher_method instanceof CipherMethod
78
-                ? $cipher_method
79
-                : new CipherMethod(
80
-                OpenSSLv2::CIPHER_METHOD,
81
-                OpenSSLv2::CIPHER_METHOD_OPTION_NAME
82
-            ),
83
-            $encryption_key_manager instanceof EncryptionKeyManager
84
-                ? $encryption_key_manager
85
-                : new EncryptionKeyManager(
86
-                OpenSSLv2::DEFAULT_ENCRYPTION_KEY_ID,
87
-                OpenSSLv2::ENCRYPTION_KEYS_OPTION_NAME
88
-            ),
89
-            $min_php_version
90
-        );
91
-    }
92
-
93
-
94
-    /**
95
-     * encrypts data
96
-     *
97
-     * @param string $text_to_encrypt           - the text to be encrypted
98
-     * @param string $encryption_key_identifier - [optional] cryptographically secure passphrase. generated if not set
99
-     * @param string $aad                       - [optional] additional authentication data
100
-     * @return string
101
-     * @throws Exception
102
-     */
103
-    public function encrypt($text_to_encrypt, $encryption_key_identifier = '', $aad = '')
104
-    {
105
-        $cipher_method  = $this->cipher_method->getCipherMethod();
106
-        $encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
107
-        // generate initialization vector for the cipher method.
108
-        $iv = random_bytes(openssl_cipher_iv_length($cipher_method));
109
-        // encrypt it
110
-        return $this->cipher_method->usesAuthenticatedEncryptionMode()
111
-            ? $this->authenticatedEncrypt($text_to_encrypt, $cipher_method, $encryption_key, $iv, $aad)
112
-            : $this->nonAuthenticatedEncrypt($text_to_encrypt, $cipher_method, $encryption_key, $iv);
113
-    }
114
-
115
-
116
-    /**
117
-     * @param string $text_to_encrypt - the text to be encrypted
118
-     * @param string $cipher_method   - the OpenSSL cipher method used during encryption
119
-     * @param string $encryption_key  - cryptographically secure passphrase uses default if not set
120
-     * @param string $iv              - the initialization vector
121
-     * @param string $aad             - additional authentication data
122
-     * @return string
123
-     */
124
-    private function authenticatedEncrypt($text_to_encrypt, $cipher_method, $encryption_key, $iv, $aad)
125
-    {
126
-        $encrypted_text = openssl_encrypt(
127
-            $text_to_encrypt,
128
-            $cipher_method,
129
-            $this->getDigestHashValue($encryption_key, OpenSSL::DEFAULT_DIGEST_METHOD, OPENSSL_RAW_DATA),
130
-            OPENSSL_RAW_DATA,
131
-            $iv,
132
-            $tag,
133
-            $aad,
134
-            OpenSSLv2::AUTH_TAG_LENGTH
135
-        );
136
-        // concatenate everything into one big string and encode it
137
-        return $this->base64_encoder->encodeString($iv . $tag . $encrypted_text);
138
-    }
139
-
140
-
141
-    /**
142
-     * @param string $text_to_encrypt - the text to be encrypted
143
-     * @param string $cipher_method   - the OpenSSL cipher method used during encryption
144
-     * @param string $encryption_key  - cryptographically secure passphrase uses default if not set
145
-     * @param string $iv              - the initialization vector
146
-     * @return string
147
-     */
148
-    private function nonAuthenticatedEncrypt($text_to_encrypt, $cipher_method, $encryption_key, $iv)
149
-    {
150
-        $encrypted_text = openssl_encrypt(
151
-            $text_to_encrypt,
152
-            $cipher_method,
153
-            $this->getDigestHashValue($encryption_key),
154
-            OPENSSL_RAW_DATA,
155
-            $iv
156
-        );
157
-        // prepend the initialization vector and encode it
158
-        return $this->base64_encoder->encodeString($iv . $encrypted_text);
159
-    }
160
-
161
-
162
-    /**
163
-     * decrypts data
164
-     *
165
-     * @param string $encrypted_text            - the text to be decrypted
166
-     * @param string $encryption_key_identifier - [optional] cryptographically secure passphrase uses default if not set
167
-     * @param string $aad                       - [optional] additional authentication data
168
-     * @return string
169
-     */
170
-    public function decrypt($encrypted_text, $encryption_key_identifier = '', $aad = '')
171
-    {
172
-        $cipher_method  = $this->cipher_method->getCipherMethod();
173
-        $encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
174
-        // maybe decode
175
-        $encrypted_text = $this->base64_encoder->decodeString($encrypted_text);
176
-        $iv_length      = openssl_cipher_iv_length($cipher_method);
177
-        // use the iv length to snip it from the decoded string
178
-        $iv = substr($encrypted_text, 0, $iv_length);
179
-        // then remove it from the rest of the decoded string
180
-        $encrypted_text = substr($encrypted_text, $iv_length);
181
-        // decrypt it
182
-        $decrypted_text = $this->cipher_method->usesAuthenticatedEncryptionMode()
183
-            ? $this->authenticatedDecrypt($encrypted_text, $cipher_method, $encryption_key, $iv, $aad)
184
-            : $this->nonAuthenticatedDecrypt($encrypted_text, $cipher_method, $encryption_key, $iv);
185
-
186
-        if ($decrypted_text === false) {
187
-            throw new RuntimeException(
188
-                sprintf(
189
-                    esc_html__(
190
-                        'The following error occurred during decryption: %1$s%2$s',
191
-                        'event_espresso'
192
-                    ),
193
-                    '<br />',
194
-                    openssl_error_string()
195
-                )
196
-            );
197
-        }
198
-        return trim($decrypted_text);
199
-    }
200
-
201
-
202
-    /**
203
-     * @param string $encrypted_text - the text to be decrypted
204
-     * @param string $cipher_method  - the OpenSSL cipher method used during encryption
205
-     * @param string $encryption_key - cryptographically secure passphrase uses default if not set
206
-     * @param string $iv             - the initialization vector
207
-     * @param string $aad            - additional authentication data
208
-     * @return string|false
209
-     */
210
-    private function authenticatedDecrypt($encrypted_text, $cipher_method, $encryption_key, $iv, $aad)
211
-    {
212
-        // use the tag length to snip it from the decoded string
213
-        $tag = substr($encrypted_text, 0, OpenSSLv2::AUTH_TAG_LENGTH);
214
-        // then remove it from the rest of the decoded string
215
-        $encrypted_text = substr($encrypted_text, OpenSSLv2::AUTH_TAG_LENGTH);
216
-        return openssl_decrypt(
217
-            $encrypted_text,
218
-            $cipher_method,
219
-            $this->getDigestHashValue($encryption_key, OpenSSL::DEFAULT_DIGEST_METHOD, OPENSSL_RAW_DATA),
220
-            OPENSSL_RAW_DATA,
221
-            $iv,
222
-            $tag,
223
-            $aad
224
-        );
225
-    }
226
-
227
-
228
-    /**
229
-     * @param string $encrypted_text - the text to be decrypted
230
-     * @param string $cipher_method  - the OpenSSL cipher method used during encryption
231
-     * @param string $encryption_key - cryptographically secure passphrase uses default if not set
232
-     * @param string $iv             - the initialization vector
233
-     * @return string|false
234
-     */
235
-    private function nonAuthenticatedDecrypt($encrypted_text, $cipher_method, $encryption_key, $iv)
236
-    {
237
-        return openssl_decrypt(
238
-            $encrypted_text,
239
-            $cipher_method,
240
-            $this->getDigestHashValue($encryption_key),
241
-            OPENSSL_RAW_DATA,
242
-            $iv
243
-        );
244
-    }
22
+	/**
23
+	 * name used for a default encryption key in case no others are set
24
+	 */
25
+	const DEFAULT_ENCRYPTION_KEY_ID = 'default_openssl_v2_key';
26
+
27
+	/**
28
+	 * name used for saving encryption keys to the wp_options table
29
+	 */
30
+	const ENCRYPTION_KEYS_OPTION_NAME = 'ee_openssl_v2_encryption_keys';
31
+
32
+	/**
33
+	 * the OPENSSL cipher method used
34
+	 */
35
+	const CIPHER_METHOD = 'aes-256-gcm';
36
+
37
+	/**
38
+	 * WP "options_name" used to store a verified available cipher method
39
+	 */
40
+	const CIPHER_METHOD_OPTION_NAME = 'ee_openssl_v2_cipher_method';
41
+
42
+	/**
43
+	 * The length of the authentication tag. Its value can be between 4 and 16 for GCM mode.
44
+	 */
45
+	const AUTH_TAG_LENGTH = 16;
46
+
47
+
48
+	/**
49
+	 * To use custom a cipher method and/or encryption keys and/or minimum PHP version:
50
+	 *  - extend this class
51
+	 *  - configure a new CipherMethod / EncryptionKeyManager in the constructor
52
+	 *  - pass those to this constructor, like so:
53
+	 *
54
+	 *      public function __construct(Base64Encoder $base64_encoder) {
55
+	 *          parent::__construct(
56
+	 *              $base64_encoder,
57
+	 *              new CipherMethod(CIPHER_METHOD, CIPHER_METHOD_OPTION_NAME),
58
+	 *              new EncryptionKeyManager(CUSTOM_KEY_ID, CUSTOM_KEYS_OPTION_NAME),
59
+	 *              '7.1.0'
60
+	 *          );
61
+	 *      }
62
+	 *
63
+	 * @param Base64Encoder                      $base64_encoder
64
+	 * @param CipherMethod|null                  $cipher_method
65
+	 * @param EncryptionKeyManagerInterface|null $encryption_key_manager
66
+	 * @param string                             $min_php_version defaults to 7.1.0
67
+	 *                                                            (when openssl auth tag and random_bytes() were added)
68
+	 */
69
+	public function __construct(
70
+		Base64Encoder                 $base64_encoder,
71
+		CipherMethod                  $cipher_method = null,
72
+		EncryptionKeyManagerInterface $encryption_key_manager = null,
73
+									  $min_php_version = '7.1.0'
74
+	) {
75
+		parent::__construct(
76
+			$base64_encoder,
77
+			$cipher_method instanceof CipherMethod
78
+				? $cipher_method
79
+				: new CipherMethod(
80
+				OpenSSLv2::CIPHER_METHOD,
81
+				OpenSSLv2::CIPHER_METHOD_OPTION_NAME
82
+			),
83
+			$encryption_key_manager instanceof EncryptionKeyManager
84
+				? $encryption_key_manager
85
+				: new EncryptionKeyManager(
86
+				OpenSSLv2::DEFAULT_ENCRYPTION_KEY_ID,
87
+				OpenSSLv2::ENCRYPTION_KEYS_OPTION_NAME
88
+			),
89
+			$min_php_version
90
+		);
91
+	}
92
+
93
+
94
+	/**
95
+	 * encrypts data
96
+	 *
97
+	 * @param string $text_to_encrypt           - the text to be encrypted
98
+	 * @param string $encryption_key_identifier - [optional] cryptographically secure passphrase. generated if not set
99
+	 * @param string $aad                       - [optional] additional authentication data
100
+	 * @return string
101
+	 * @throws Exception
102
+	 */
103
+	public function encrypt($text_to_encrypt, $encryption_key_identifier = '', $aad = '')
104
+	{
105
+		$cipher_method  = $this->cipher_method->getCipherMethod();
106
+		$encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
107
+		// generate initialization vector for the cipher method.
108
+		$iv = random_bytes(openssl_cipher_iv_length($cipher_method));
109
+		// encrypt it
110
+		return $this->cipher_method->usesAuthenticatedEncryptionMode()
111
+			? $this->authenticatedEncrypt($text_to_encrypt, $cipher_method, $encryption_key, $iv, $aad)
112
+			: $this->nonAuthenticatedEncrypt($text_to_encrypt, $cipher_method, $encryption_key, $iv);
113
+	}
114
+
115
+
116
+	/**
117
+	 * @param string $text_to_encrypt - the text to be encrypted
118
+	 * @param string $cipher_method   - the OpenSSL cipher method used during encryption
119
+	 * @param string $encryption_key  - cryptographically secure passphrase uses default if not set
120
+	 * @param string $iv              - the initialization vector
121
+	 * @param string $aad             - additional authentication data
122
+	 * @return string
123
+	 */
124
+	private function authenticatedEncrypt($text_to_encrypt, $cipher_method, $encryption_key, $iv, $aad)
125
+	{
126
+		$encrypted_text = openssl_encrypt(
127
+			$text_to_encrypt,
128
+			$cipher_method,
129
+			$this->getDigestHashValue($encryption_key, OpenSSL::DEFAULT_DIGEST_METHOD, OPENSSL_RAW_DATA),
130
+			OPENSSL_RAW_DATA,
131
+			$iv,
132
+			$tag,
133
+			$aad,
134
+			OpenSSLv2::AUTH_TAG_LENGTH
135
+		);
136
+		// concatenate everything into one big string and encode it
137
+		return $this->base64_encoder->encodeString($iv . $tag . $encrypted_text);
138
+	}
139
+
140
+
141
+	/**
142
+	 * @param string $text_to_encrypt - the text to be encrypted
143
+	 * @param string $cipher_method   - the OpenSSL cipher method used during encryption
144
+	 * @param string $encryption_key  - cryptographically secure passphrase uses default if not set
145
+	 * @param string $iv              - the initialization vector
146
+	 * @return string
147
+	 */
148
+	private function nonAuthenticatedEncrypt($text_to_encrypt, $cipher_method, $encryption_key, $iv)
149
+	{
150
+		$encrypted_text = openssl_encrypt(
151
+			$text_to_encrypt,
152
+			$cipher_method,
153
+			$this->getDigestHashValue($encryption_key),
154
+			OPENSSL_RAW_DATA,
155
+			$iv
156
+		);
157
+		// prepend the initialization vector and encode it
158
+		return $this->base64_encoder->encodeString($iv . $encrypted_text);
159
+	}
160
+
161
+
162
+	/**
163
+	 * decrypts data
164
+	 *
165
+	 * @param string $encrypted_text            - the text to be decrypted
166
+	 * @param string $encryption_key_identifier - [optional] cryptographically secure passphrase uses default if not set
167
+	 * @param string $aad                       - [optional] additional authentication data
168
+	 * @return string
169
+	 */
170
+	public function decrypt($encrypted_text, $encryption_key_identifier = '', $aad = '')
171
+	{
172
+		$cipher_method  = $this->cipher_method->getCipherMethod();
173
+		$encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
174
+		// maybe decode
175
+		$encrypted_text = $this->base64_encoder->decodeString($encrypted_text);
176
+		$iv_length      = openssl_cipher_iv_length($cipher_method);
177
+		// use the iv length to snip it from the decoded string
178
+		$iv = substr($encrypted_text, 0, $iv_length);
179
+		// then remove it from the rest of the decoded string
180
+		$encrypted_text = substr($encrypted_text, $iv_length);
181
+		// decrypt it
182
+		$decrypted_text = $this->cipher_method->usesAuthenticatedEncryptionMode()
183
+			? $this->authenticatedDecrypt($encrypted_text, $cipher_method, $encryption_key, $iv, $aad)
184
+			: $this->nonAuthenticatedDecrypt($encrypted_text, $cipher_method, $encryption_key, $iv);
185
+
186
+		if ($decrypted_text === false) {
187
+			throw new RuntimeException(
188
+				sprintf(
189
+					esc_html__(
190
+						'The following error occurred during decryption: %1$s%2$s',
191
+						'event_espresso'
192
+					),
193
+					'<br />',
194
+					openssl_error_string()
195
+				)
196
+			);
197
+		}
198
+		return trim($decrypted_text);
199
+	}
200
+
201
+
202
+	/**
203
+	 * @param string $encrypted_text - the text to be decrypted
204
+	 * @param string $cipher_method  - the OpenSSL cipher method used during encryption
205
+	 * @param string $encryption_key - cryptographically secure passphrase uses default if not set
206
+	 * @param string $iv             - the initialization vector
207
+	 * @param string $aad            - additional authentication data
208
+	 * @return string|false
209
+	 */
210
+	private function authenticatedDecrypt($encrypted_text, $cipher_method, $encryption_key, $iv, $aad)
211
+	{
212
+		// use the tag length to snip it from the decoded string
213
+		$tag = substr($encrypted_text, 0, OpenSSLv2::AUTH_TAG_LENGTH);
214
+		// then remove it from the rest of the decoded string
215
+		$encrypted_text = substr($encrypted_text, OpenSSLv2::AUTH_TAG_LENGTH);
216
+		return openssl_decrypt(
217
+			$encrypted_text,
218
+			$cipher_method,
219
+			$this->getDigestHashValue($encryption_key, OpenSSL::DEFAULT_DIGEST_METHOD, OPENSSL_RAW_DATA),
220
+			OPENSSL_RAW_DATA,
221
+			$iv,
222
+			$tag,
223
+			$aad
224
+		);
225
+	}
226
+
227
+
228
+	/**
229
+	 * @param string $encrypted_text - the text to be decrypted
230
+	 * @param string $cipher_method  - the OpenSSL cipher method used during encryption
231
+	 * @param string $encryption_key - cryptographically secure passphrase uses default if not set
232
+	 * @param string $iv             - the initialization vector
233
+	 * @return string|false
234
+	 */
235
+	private function nonAuthenticatedDecrypt($encrypted_text, $cipher_method, $encryption_key, $iv)
236
+	{
237
+		return openssl_decrypt(
238
+			$encrypted_text,
239
+			$cipher_method,
240
+			$this->getDigestHashValue($encryption_key),
241
+			OPENSSL_RAW_DATA,
242
+			$iv
243
+		);
244
+	}
245 245
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
             OpenSSLv2::AUTH_TAG_LENGTH
135 135
         );
136 136
         // concatenate everything into one big string and encode it
137
-        return $this->base64_encoder->encodeString($iv . $tag . $encrypted_text);
137
+        return $this->base64_encoder->encodeString($iv.$tag.$encrypted_text);
138 138
     }
139 139
 
140 140
 
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
             $iv
156 156
         );
157 157
         // prepend the initialization vector and encode it
158
-        return $this->base64_encoder->encodeString($iv . $encrypted_text);
158
+        return $this->base64_encoder->encodeString($iv.$encrypted_text);
159 159
     }
160 160
 
161 161
 
Please login to merge, or discard this patch.
core/services/encryption/openssl/OpenSSLv1.php 2 patches
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -18,153 +18,153 @@
 block discarded – undo
18 18
 class OpenSSLv1 extends OpenSSL
19 19
 {
20 20
 
21
-    /**
22
-     * name used for a default encryption key in case no others are set
23
-     */
24
-    const DEFAULT_ENCRYPTION_KEY_ID = 'default_openssl_v1_key';
21
+	/**
22
+	 * name used for a default encryption key in case no others are set
23
+	 */
24
+	const DEFAULT_ENCRYPTION_KEY_ID = 'default_openssl_v1_key';
25 25
 
26
-    /**
27
-     * name used for saving encryption keys to the wp_options table
28
-     */
29
-    const ENCRYPTION_KEYS_OPTION_NAME = 'ee_openssl_v1_encryption_keys';
26
+	/**
27
+	 * name used for saving encryption keys to the wp_options table
28
+	 */
29
+	const ENCRYPTION_KEYS_OPTION_NAME = 'ee_openssl_v1_encryption_keys';
30 30
 
31
-    /**
32
-     * the OPENSSL cipher method used
33
-     */
34
-    const CIPHER_METHOD = 'aes-128-cbc';
31
+	/**
32
+	 * the OPENSSL cipher method used
33
+	 */
34
+	const CIPHER_METHOD = 'aes-128-cbc';
35 35
 
36
-    /**
37
-     * WP "options_name" used to store a verified available cipher method
38
-     */
39
-    const CIPHER_METHOD_OPTION_NAME = 'ee_openssl_v1_cipher_method';
36
+	/**
37
+	 * WP "options_name" used to store a verified available cipher method
38
+	 */
39
+	const CIPHER_METHOD_OPTION_NAME = 'ee_openssl_v1_cipher_method';
40 40
 
41 41
 
42
-    /**
43
-     * To use custom a cipher method and/or encryption keys and/or minimum PHP version:
44
-     *  - extend this class
45
-     *  - configure a new CipherMethod / EncryptionKeyManager in the constructor
46
-     *  - pass those to this constructor, like so:
47
-     *
48
-     *      public function __construct(Base64Encoder $base64_encoder) {
49
-     *          parent::__construct(
50
-     *              $base64_encoder,
51
-     *              new CipherMethod(CIPHER_METHOD, CIPHER_METHOD_OPTION_NAME),
52
-     *              new EncryptionKeyManager(CUSTOM_KEY_ID, CUSTOM_KEYS_OPTION_NAME),
53
-     *              '7.1.0'
54
-     *          );
55
-     *      }
56
-     *
57
-     * @param Base64Encoder                      $base64_encoder
58
-     * @param CipherMethod|null                  $cipher_method
59
-     * @param EncryptionKeyManagerInterface|null $encryption_key_manager
60
-     * @param string                             $min_php_version defaults to 5.3.0 (when openssl added)
61
-     */
62
-    public function __construct(
63
-        Base64Encoder                 $base64_encoder,
64
-        CipherMethod                  $cipher_method = null,
65
-        EncryptionKeyManagerInterface $encryption_key_manager = null,
66
-                                      $min_php_version = '5.3.0'
67
-    ) {
68
-        parent::__construct(
69
-            $base64_encoder,
70
-            $cipher_method instanceof CipherMethod
71
-                ? $cipher_method
72
-                : new CipherMethod(
73
-                OpenSSLv1::CIPHER_METHOD,
74
-                OpenSSLv1::CIPHER_METHOD_OPTION_NAME
75
-            ),
76
-            $encryption_key_manager instanceof EncryptionKeyManager
77
-                ? $encryption_key_manager
78
-                : new EncryptionKeyManager(
79
-                OpenSSLv1::DEFAULT_ENCRYPTION_KEY_ID,
80
-                OpenSSLv1::ENCRYPTION_KEYS_OPTION_NAME
81
-            ),
82
-            $min_php_version
83
-        );
84
-    }
42
+	/**
43
+	 * To use custom a cipher method and/or encryption keys and/or minimum PHP version:
44
+	 *  - extend this class
45
+	 *  - configure a new CipherMethod / EncryptionKeyManager in the constructor
46
+	 *  - pass those to this constructor, like so:
47
+	 *
48
+	 *      public function __construct(Base64Encoder $base64_encoder) {
49
+	 *          parent::__construct(
50
+	 *              $base64_encoder,
51
+	 *              new CipherMethod(CIPHER_METHOD, CIPHER_METHOD_OPTION_NAME),
52
+	 *              new EncryptionKeyManager(CUSTOM_KEY_ID, CUSTOM_KEYS_OPTION_NAME),
53
+	 *              '7.1.0'
54
+	 *          );
55
+	 *      }
56
+	 *
57
+	 * @param Base64Encoder                      $base64_encoder
58
+	 * @param CipherMethod|null                  $cipher_method
59
+	 * @param EncryptionKeyManagerInterface|null $encryption_key_manager
60
+	 * @param string                             $min_php_version defaults to 5.3.0 (when openssl added)
61
+	 */
62
+	public function __construct(
63
+		Base64Encoder                 $base64_encoder,
64
+		CipherMethod                  $cipher_method = null,
65
+		EncryptionKeyManagerInterface $encryption_key_manager = null,
66
+									  $min_php_version = '5.3.0'
67
+	) {
68
+		parent::__construct(
69
+			$base64_encoder,
70
+			$cipher_method instanceof CipherMethod
71
+				? $cipher_method
72
+				: new CipherMethod(
73
+				OpenSSLv1::CIPHER_METHOD,
74
+				OpenSSLv1::CIPHER_METHOD_OPTION_NAME
75
+			),
76
+			$encryption_key_manager instanceof EncryptionKeyManager
77
+				? $encryption_key_manager
78
+				: new EncryptionKeyManager(
79
+				OpenSSLv1::DEFAULT_ENCRYPTION_KEY_ID,
80
+				OpenSSLv1::ENCRYPTION_KEYS_OPTION_NAME
81
+			),
82
+			$min_php_version
83
+		);
84
+	}
85 85
 
86 86
 
87
-    /**
88
-     * encrypts data
89
-     *
90
-     * @param string $text_to_encrypt           - the text to be encrypted
91
-     * @param string $encryption_key_identifier - cryptographically secure passphrase. will generate if necessary
92
-     * @return string
93
-     */
94
-    public function encrypt($text_to_encrypt, $encryption_key_identifier = '')
95
-    {
96
-        $cipher_method  = $this->cipher_method->getCipherMethod();
97
-        $encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
98
-        // get initialization vector size
99
-        $iv_length = openssl_cipher_iv_length($cipher_method);
100
-        // generate initialization vector.
101
-        // The second parameter ("crypto_strong") is passed by reference,
102
-        // and is used to determines if the algorithm used was "cryptographically strong"
103
-        // openssl_random_pseudo_bytes() will toggle it to either true or false
104
-        $iv = openssl_random_pseudo_bytes($iv_length, $is_strong);
105
-        if ($iv === false || $is_strong === false) {
106
-            throw new RuntimeException(
107
-                esc_html__('Failed to generate OpenSSL initialization vector.', 'event_espresso')
108
-            );
109
-        }
110
-        $key = $this->getDigestHashValue($encryption_key);
111
-        // encrypt it
112
-        $encrypted_text = openssl_encrypt(
113
-            $text_to_encrypt,
114
-            $cipher_method,
115
-            $key,
116
-            OPENSSL_RAW_DATA,
117
-            $iv
118
-        );
119
-        $encrypted_text = trim($encrypted_text);
120
-        // hash the raw encrypted text
121
-        $hmac = hash_hmac($this->getHashAlgorithm(), $encrypted_text, $key, true);
122
-        // concatenate everything into one big string and encode it
123
-        return $this->base64_encoder->encodeString($iv . $hmac . $encrypted_text);
124
-    }
87
+	/**
88
+	 * encrypts data
89
+	 *
90
+	 * @param string $text_to_encrypt           - the text to be encrypted
91
+	 * @param string $encryption_key_identifier - cryptographically secure passphrase. will generate if necessary
92
+	 * @return string
93
+	 */
94
+	public function encrypt($text_to_encrypt, $encryption_key_identifier = '')
95
+	{
96
+		$cipher_method  = $this->cipher_method->getCipherMethod();
97
+		$encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
98
+		// get initialization vector size
99
+		$iv_length = openssl_cipher_iv_length($cipher_method);
100
+		// generate initialization vector.
101
+		// The second parameter ("crypto_strong") is passed by reference,
102
+		// and is used to determines if the algorithm used was "cryptographically strong"
103
+		// openssl_random_pseudo_bytes() will toggle it to either true or false
104
+		$iv = openssl_random_pseudo_bytes($iv_length, $is_strong);
105
+		if ($iv === false || $is_strong === false) {
106
+			throw new RuntimeException(
107
+				esc_html__('Failed to generate OpenSSL initialization vector.', 'event_espresso')
108
+			);
109
+		}
110
+		$key = $this->getDigestHashValue($encryption_key);
111
+		// encrypt it
112
+		$encrypted_text = openssl_encrypt(
113
+			$text_to_encrypt,
114
+			$cipher_method,
115
+			$key,
116
+			OPENSSL_RAW_DATA,
117
+			$iv
118
+		);
119
+		$encrypted_text = trim($encrypted_text);
120
+		// hash the raw encrypted text
121
+		$hmac = hash_hmac($this->getHashAlgorithm(), $encrypted_text, $key, true);
122
+		// concatenate everything into one big string and encode it
123
+		return $this->base64_encoder->encodeString($iv . $hmac . $encrypted_text);
124
+	}
125 125
 
126 126
 
127
-    /**
128
-     * decrypts data
129
-     *
130
-     * @param string $encrypted_text            - the text to be decrypted
131
-     * @param string $encryption_key_identifier - cryptographically secure passphrase. will use default if necessary
132
-     * @return string
133
-     */
134
-    public function decrypt($encrypted_text, $encryption_key_identifier = '')
135
-    {
136
-        $cipher_method  = $this->cipher_method->getCipherMethod();
137
-        $encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
138
-        $key            = $this->getDigestHashValue($encryption_key);
139
-        // decode our concatenated string
140
-        $encrypted_text = $this->base64_encoder->decodeString($encrypted_text);
141
-        // get the string lengths used for the hash and iv
142
-        $hash_length = $this->calculateHashLength($encryption_key);
143
-        $iv_length   = openssl_cipher_iv_length($cipher_method);
144
-        // use the above lengths to snip the required values from the decoded string
145
-        $iv                 = substr($encrypted_text, 0, $iv_length);
146
-        $hmac               = substr($encrypted_text, $iv_length, $hash_length);
147
-        $encrypted_text_raw = substr($encrypted_text, $iv_length + $hash_length);
148
-        // rehash the original raw encrypted text
149
-        $rehash_mac = hash_hmac($this->getHashAlgorithm(), $encrypted_text_raw, $key, true);
150
-        // timing attack safe comparison to determine if anything has changed
151
-        if (hash_equals($hmac, $rehash_mac)) {
152
-            // looks good, decrypt it, trim it, and return it
153
-            return trim(
154
-                openssl_decrypt(
155
-                    $encrypted_text_raw,
156
-                    $this->cipher_method->getCipherMethod(),
157
-                    $key,
158
-                    OPENSSL_RAW_DATA,
159
-                    $iv
160
-                )
161
-            );
162
-        }
163
-        throw new RuntimeException(
164
-            esc_html__(
165
-                'Decryption failed because a hash comparison of the original text and the decrypted text was not the same, meaning something in the system or the encrypted data has changed.',
166
-                'event_espresso'
167
-            )
168
-        );
169
-    }
127
+	/**
128
+	 * decrypts data
129
+	 *
130
+	 * @param string $encrypted_text            - the text to be decrypted
131
+	 * @param string $encryption_key_identifier - cryptographically secure passphrase. will use default if necessary
132
+	 * @return string
133
+	 */
134
+	public function decrypt($encrypted_text, $encryption_key_identifier = '')
135
+	{
136
+		$cipher_method  = $this->cipher_method->getCipherMethod();
137
+		$encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
138
+		$key            = $this->getDigestHashValue($encryption_key);
139
+		// decode our concatenated string
140
+		$encrypted_text = $this->base64_encoder->decodeString($encrypted_text);
141
+		// get the string lengths used for the hash and iv
142
+		$hash_length = $this->calculateHashLength($encryption_key);
143
+		$iv_length   = openssl_cipher_iv_length($cipher_method);
144
+		// use the above lengths to snip the required values from the decoded string
145
+		$iv                 = substr($encrypted_text, 0, $iv_length);
146
+		$hmac               = substr($encrypted_text, $iv_length, $hash_length);
147
+		$encrypted_text_raw = substr($encrypted_text, $iv_length + $hash_length);
148
+		// rehash the original raw encrypted text
149
+		$rehash_mac = hash_hmac($this->getHashAlgorithm(), $encrypted_text_raw, $key, true);
150
+		// timing attack safe comparison to determine if anything has changed
151
+		if (hash_equals($hmac, $rehash_mac)) {
152
+			// looks good, decrypt it, trim it, and return it
153
+			return trim(
154
+				openssl_decrypt(
155
+					$encrypted_text_raw,
156
+					$this->cipher_method->getCipherMethod(),
157
+					$key,
158
+					OPENSSL_RAW_DATA,
159
+					$iv
160
+				)
161
+			);
162
+		}
163
+		throw new RuntimeException(
164
+			esc_html__(
165
+				'Decryption failed because a hash comparison of the original text and the decrypted text was not the same, meaning something in the system or the encrypted data has changed.',
166
+				'event_espresso'
167
+			)
168
+		);
169
+	}
170 170
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@
 block discarded – undo
120 120
         // hash the raw encrypted text
121 121
         $hmac = hash_hmac($this->getHashAlgorithm(), $encrypted_text, $key, true);
122 122
         // concatenate everything into one big string and encode it
123
-        return $this->base64_encoder->encodeString($iv . $hmac . $encrypted_text);
123
+        return $this->base64_encoder->encodeString($iv.$hmac.$encrypted_text);
124 124
     }
125 125
 
126 126
 
Please login to merge, or discard this patch.