Completed
Branch FET/enhanced-encryption (8fe725)
by
unknown
04:17 queued 02:33
created
core/services/encryption/EncryptionKeyManagerInterface.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -12,43 +12,43 @@
 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);
24
-
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);
34
-
35
-
36
-    /**
37
-     * creates a new encryption key
38
-     *
39
-     * @return string
40
-     */
41
-    public function generateEncryptionKey();
42
-
43
-
44
-    /**
45
-     * @param int $bit_depth options are 128, 192, or 256
46
-     */
47
-    public function setBitDepth($bit_depth);
48
-
49
-
50
-    /**
51
-     * @param int $key_length
52
-     */
53
-    public function setKeyLength($key_length);
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
+
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);
34
+
35
+
36
+	/**
37
+	 * creates a new encryption key
38
+	 *
39
+	 * @return string
40
+	 */
41
+	public function generateEncryptionKey();
42
+
43
+
44
+	/**
45
+	 * @param int $bit_depth options are 128, 192, or 256
46
+	 */
47
+	public function setBitDepth($bit_depth);
48
+
49
+
50
+	/**
51
+	 * @param int $key_length
52
+	 */
53
+	public function setKeyLength($key_length);
54 54
 }
Please login to merge, or discard this patch.
core/services/encryption/EncryptionKeyManager.php 2 patches
Indentation   +208 added lines, -208 removed lines patch added patch discarded remove patch
@@ -17,212 +17,212 @@
 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 = [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
-        return random_bytes($this->bit_depth);
154
-    }
155
-
156
-
157
-    /**
158
-     * creates a new encryption key that should not be trusted to be cryptographically secure
159
-     *
160
-     * @return string
161
-     * @throws Exception
162
-     */
163
-    protected function generateWeakEncryptionKey()
164
-    {
165
-        // @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
166
-        $iterations    = ceil($this->key_length / 40);
167
-        $random_string = '';
168
-        for ($i = 0; $i < $iterations; $i++) {
169
-            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
170
-        }
171
-        return substr($random_string, 0, $this->key_length);
172
-    }
173
-
174
-
175
-    /**
176
-     * @param int $bit_depth options are 128, 192, or 256
177
-     */
178
-    public function setBitDepth($bit_depth)
179
-    {
180
-        $bit_depth       = absint($bit_depth);
181
-        $this->bit_depth = in_array($bit_depth, $this->bit_depth_options) ? $bit_depth : 128;
182
-    }
183
-
184
-
185
-    /**
186
-     * @param int $key_length
187
-     */
188
-    public function setKeyLength($key_length)
189
-    {
190
-        // let's not let the key length go below 8 or above 128
191
-        $this->key_length = min(max($key_length, 8), 128);
192
-    }
193
-
194
-
195
-    /**
196
-     * retrieves encryption keys from db
197
-     *
198
-     * @return string
199
-     * @throws Exception
200
-     */
201
-    protected function retrieveEncryptionKeys()
202
-    {
203
-        // if encryption key has not been set
204
-        if (! empty($this->encryption_keys)) {
205
-            // retrieve encryption_key from db
206
-            $this->encryption_keys = get_option($this->encryption_keys_option_name, null);
207
-            // WHAT?? No encryption_key in the db ??
208
-            if ($this->encryption_keys === null) {
209
-                // let's make one. And md5 it to make it just the right size for a key
210
-                $this->addEncryptionKey($this->default_encryption_key_id);
211
-            }
212
-        }
213
-        return $this->encryption_keys;
214
-    }
215
-
216
-
217
-    /**
218
-     * saves encryption keys from db
219
-     *
220
-     * @return bool
221
-     */
222
-    protected function saveEncryptionKeys()
223
-    {
224
-        return $this->encryption_keys === null
225
-            ? add_option($this->encryption_keys_option_name, $this->encryption_keys)
226
-            : update_option($this->encryption_keys_option_name, $this->encryption_keys);
227
-    }
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 = [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
+		return random_bytes($this->bit_depth);
154
+	}
155
+
156
+
157
+	/**
158
+	 * creates a new encryption key that should not be trusted to be cryptographically secure
159
+	 *
160
+	 * @return string
161
+	 * @throws Exception
162
+	 */
163
+	protected function generateWeakEncryptionKey()
164
+	{
165
+		// @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
166
+		$iterations    = ceil($this->key_length / 40);
167
+		$random_string = '';
168
+		for ($i = 0; $i < $iterations; $i++) {
169
+			$random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
170
+		}
171
+		return substr($random_string, 0, $this->key_length);
172
+	}
173
+
174
+
175
+	/**
176
+	 * @param int $bit_depth options are 128, 192, or 256
177
+	 */
178
+	public function setBitDepth($bit_depth)
179
+	{
180
+		$bit_depth       = absint($bit_depth);
181
+		$this->bit_depth = in_array($bit_depth, $this->bit_depth_options) ? $bit_depth : 128;
182
+	}
183
+
184
+
185
+	/**
186
+	 * @param int $key_length
187
+	 */
188
+	public function setKeyLength($key_length)
189
+	{
190
+		// let's not let the key length go below 8 or above 128
191
+		$this->key_length = min(max($key_length, 8), 128);
192
+	}
193
+
194
+
195
+	/**
196
+	 * retrieves encryption keys from db
197
+	 *
198
+	 * @return string
199
+	 * @throws Exception
200
+	 */
201
+	protected function retrieveEncryptionKeys()
202
+	{
203
+		// if encryption key has not been set
204
+		if (! empty($this->encryption_keys)) {
205
+			// retrieve encryption_key from db
206
+			$this->encryption_keys = get_option($this->encryption_keys_option_name, null);
207
+			// WHAT?? No encryption_key in the db ??
208
+			if ($this->encryption_keys === null) {
209
+				// let's make one. And md5 it to make it just the right size for a key
210
+				$this->addEncryptionKey($this->default_encryption_key_id);
211
+			}
212
+		}
213
+		return $this->encryption_keys;
214
+	}
215
+
216
+
217
+	/**
218
+	 * saves encryption keys from db
219
+	 *
220
+	 * @return bool
221
+	 */
222
+	protected function saveEncryptionKeys()
223
+	{
224
+		return $this->encryption_keys === null
225
+			? add_option($this->encryption_keys_option_name, $this->encryption_keys)
226
+			: update_option($this->encryption_keys_option_name, $this->encryption_keys);
227
+	}
228 228
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -80,9 +80,9 @@  discard block
 block discarded – undo
80 80
     {
81 81
         // ensure keys are loaded
82 82
         $this->retrieveEncryptionKeys();
83
-        if (isset($this->encryption_keys[ $encryption_key_identifier ]) && ! $overwrite) {
83
+        if (isset($this->encryption_keys[$encryption_key_identifier]) && ! $overwrite) {
84 84
             // WOAH!!! that key already exists and we don't want to overwrite it
85
-            throw new RuntimeException (
85
+            throw new RuntimeException(
86 86
                 sprintf(
87 87
                     esc_html__(
88 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.',
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
                 )
93 93
             );
94 94
         }
95
-        $this->encryption_keys[ $encryption_key_identifier ] = $encryption_key ?: $this->generateEncryptionKey();
95
+        $this->encryption_keys[$encryption_key_identifier] = $encryption_key ?: $this->generateEncryptionKey();
96 96
         return $this->saveEncryptionKeys();
97 97
     }
98 98
 
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
         // ensure keys are loaded
112 112
         $this->retrieveEncryptionKeys();
113 113
         // if encryption key has not been set
114
-        if (! isset($this->encryption_keys[ $encryption_key_identifier ])) {
114
+        if ( ! isset($this->encryption_keys[$encryption_key_identifier])) {
115 115
             if ($generate) {
116 116
                 $this->addEncryptionKey($encryption_key_identifier);
117 117
             } else {
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
                 );
124 124
             }
125 125
         }
126
-        return $this->encryption_keys[ $encryption_key_identifier ];
126
+        return $this->encryption_keys[$encryption_key_identifier];
127 127
     }
128 128
 
129 129
 
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
         $iterations    = ceil($this->key_length / 40);
167 167
         $random_string = '';
168 168
         for ($i = 0; $i < $iterations; $i++) {
169
-            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
169
+            $random_string .= sha1(microtime(true).mt_rand(10000, 90000));
170 170
         }
171 171
         return substr($random_string, 0, $this->key_length);
172 172
     }
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
     protected function retrieveEncryptionKeys()
202 202
     {
203 203
         // if encryption key has not been set
204
-        if (! empty($this->encryption_keys)) {
204
+        if ( ! empty($this->encryption_keys)) {
205 205
             // retrieve encryption_key from db
206 206
             $this->encryption_keys = get_option($this->encryption_keys_option_name, null);
207 207
             // WHAT?? No encryption_key in the db ??
Please login to merge, or discard this patch.
core/services/encryption/openssl/OpenSSLv1.php 2 patches
Indentation   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -18,135 +18,135 @@
 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
-        $encryption_key      = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
97
-        $this->cipher_method = $this->cipher_method->getCipherMethod();
98
-        // get initialization vector size
99
-        $iv_size = openssl_cipher_iv_length($this->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_size, $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
-        // encrypt it
111
-        $encrypted_text = openssl_encrypt(
112
-            $text_to_encrypt,
113
-            $this->cipher_method,
114
-            $this->getDigestHashValue($encryption_key),
115
-            0,
116
-            $iv
117
-        );
118
-        // append the initialization vector
119
-        $encrypted_text .= OpenSSL::IV_DELIMITER . $iv;
120
-        // trim and maybe encode
121
-        return $this->base64_encoder->encodeString(trim($encrypted_text));
122
-    }
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
+		$encryption_key      = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
97
+		$this->cipher_method = $this->cipher_method->getCipherMethod();
98
+		// get initialization vector size
99
+		$iv_size = openssl_cipher_iv_length($this->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_size, $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
+		// encrypt it
111
+		$encrypted_text = openssl_encrypt(
112
+			$text_to_encrypt,
113
+			$this->cipher_method,
114
+			$this->getDigestHashValue($encryption_key),
115
+			0,
116
+			$iv
117
+		);
118
+		// append the initialization vector
119
+		$encrypted_text .= OpenSSL::IV_DELIMITER . $iv;
120
+		// trim and maybe encode
121
+		return $this->base64_encoder->encodeString(trim($encrypted_text));
122
+	}
123 123
 
124 124
 
125
-    /**
126
-     * decrypts data
127
-     *
128
-     * @param string $encrypted_text            - the text to be decrypted
129
-     * @param string $encryption_key_identifier - cryptographically secure passphrase. will use default if necessary
130
-     * @return string
131
-     */
132
-    public function decrypt($encrypted_text, $encryption_key_identifier = '')
133
-    {
134
-        $encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
135
-        // maybe decode
136
-        $encrypted_text       = $this->base64_encoder->decodeString($encrypted_text);
137
-        $encrypted_components = explode(
138
-            OpenSSL::IV_DELIMITER,
139
-            $encrypted_text,
140
-            2
141
-        );
142
-        // decrypt it
143
-        $decrypted_text = openssl_decrypt(
144
-            $encrypted_components[0],
145
-            $this->cipher_method->getCipherMethod(),
146
-            $this->getDigestHashValue($encryption_key),
147
-            0,
148
-            $encrypted_components[1]
149
-        );
150
-        return trim($decrypted_text);
151
-    }
125
+	/**
126
+	 * decrypts data
127
+	 *
128
+	 * @param string $encrypted_text            - the text to be decrypted
129
+	 * @param string $encryption_key_identifier - cryptographically secure passphrase. will use default if necessary
130
+	 * @return string
131
+	 */
132
+	public function decrypt($encrypted_text, $encryption_key_identifier = '')
133
+	{
134
+		$encryption_key = $this->encryption_key_manager->getEncryptionKey($encryption_key_identifier);
135
+		// maybe decode
136
+		$encrypted_text       = $this->base64_encoder->decodeString($encrypted_text);
137
+		$encrypted_components = explode(
138
+			OpenSSL::IV_DELIMITER,
139
+			$encrypted_text,
140
+			2
141
+		);
142
+		// decrypt it
143
+		$decrypted_text = openssl_decrypt(
144
+			$encrypted_components[0],
145
+			$this->cipher_method->getCipherMethod(),
146
+			$this->getDigestHashValue($encryption_key),
147
+			0,
148
+			$encrypted_components[1]
149
+		);
150
+		return trim($decrypted_text);
151
+	}
152 152
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -116,7 +116,7 @@
 block discarded – undo
116 116
             $iv
117 117
         );
118 118
         // append the initialization vector
119
-        $encrypted_text .= OpenSSL::IV_DELIMITER . $iv;
119
+        $encrypted_text .= OpenSSL::IV_DELIMITER.$iv;
120 120
         // trim and maybe encode
121 121
         return $this->base64_encoder->encodeString(trim($encrypted_text));
122 122
     }
Please login to merge, or discard this patch.
core/services/encryption/openssl/OpenSSL.php 2 patches
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -18,168 +18,168 @@
 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
-    /**
63
-     * To use custom a cipher method and/or encryption keys:
64
-     *  - extend this class
65
-     *  - configure a new CipherMethod / EncryptionKeyManager in the constructor
66
-     *  - pass those to this constructor, like so:
67
-     *
68
-     *      public function __construct(Base64Encoder $base64_encoder) {
69
-     *          parent::__construct(
70
-     *              $base64_encoder,
71
-     *              new CipherMethod(CIPHER_METHOD, CIPHER_METHOD_OPTION_NAME)
72
-     *              new EncryptionKeyManager(CUSTOM_KEY_ID, CUSTOM_KEYS_OPTION_NAME)
73
-     *          );
74
-     *      }
75
-     *
76
-     * @param Base64Encoder                      $base64_encoder
77
-     * @param CipherMethod                       $cipher_method
78
-     * @param EncryptionKeyManagerInterface|null $encryption_key_manager
79
-     * @param string                             $min_php_version
80
-     */
81
-    protected function __construct(
82
-        Base64Encoder $base64_encoder,
83
-        CipherMethod $cipher_method,
84
-        EncryptionKeyManagerInterface $encryption_key_manager,
85
-        $min_php_version
86
-    ) {
87
-        $this->base64_encoder         = $base64_encoder;
88
-        $this->cipher_method          = $cipher_method;
89
-        $this->encryption_key_manager = $encryption_key_manager;
90
-        $this->min_php_version        = $min_php_version;
91
-        $this->openssl_installed      = extension_loaded('openssl');
92
-    }
93
-
94
-
95
-    /**
96
-     * @return bool
97
-     */
98
-    public function isCryptographicallySecure()
99
-    {
100
-        return true;
101
-    }
102
-
103
-
104
-    /**
105
-     * @return bool
106
-     */
107
-    public function canUse()
108
-    {
109
-        return $this->openssl_installed && version_compare(PHP_VERSION, $this->min_php_version, '>=');
110
-    }
111
-
112
-
113
-    /**
114
-     * @return string
115
-     */
116
-    public function canUseNotice()
117
-    {
118
-        if (! $this->openssl_installed) {
119
-            return esc_html__(
120
-                'The PHP openssl server extension is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
121
-                'event_espresso'
122
-            );
123
-        }
124
-        if (version_compare(PHP_VERSION, $this->min_php_version, '<')) {
125
-            return sprintf(
126
-                esc_html__(
127
-                    'PHP version %1$s or greater is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
128
-                    'event_espresso'
129
-                ),
130
-                $this->min_php_version
131
-            );
132
-        }
133
-        return sprintf(
134
-            esc_html__('OpenSSL v1 encryption using %1$S is available for use.', 'event_espresso'),
135
-            OpenSSLv1::CIPHER_METHOD
136
-        );
137
-    }
138
-
139
-
140
-    /**
141
-     * Computes the digest hash value using the specified digest method.
142
-     * If that digest method fails to produce a valid hash value,
143
-     * then we'll grab the next digest method and recursively try again until something works.
144
-     *
145
-     * @param string $encryption_key
146
-     * @param string $digest_method
147
-     * @return string
148
-     * @throws RuntimeException
149
-     */
150
-    protected function getDigestHashValue($encryption_key, $digest_method = OpenSSL::DEFAULT_DIGEST_METHOD)
151
-    {
152
-        $digest_hash_value = openssl_digest($encryption_key, $digest_method);
153
-        if ($digest_hash_value === false) {
154
-            return $this->getDigestHashValue($this->getDigestMethod());
155
-        }
156
-        return $digest_hash_value;
157
-    }
158
-
159
-
160
-    /**
161
-     * Returns the NEXT element in the $digest_methods array.
162
-     * If the $digest_methods array is empty, then we populate it
163
-     * with the available values returned from openssl_get_md_methods().
164
-     *
165
-     * @return string
166
-     * @throws RuntimeException
167
-     */
168
-    private function getDigestMethod()
169
-    {
170
-        $digest_method = prev($this->digest_methods);
171
-        if (empty($this->digest_methods)) {
172
-            $this->digest_methods = openssl_get_md_methods();
173
-            $digest_method        = end($this->digest_methods);
174
-        }
175
-        if ($digest_method === false) {
176
-            throw new RuntimeException(
177
-                esc_html__(
178
-                    'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
179
-                    'event_espresso'
180
-                )
181
-            );
182
-        }
183
-        return $digest_method;
184
-    }
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
+	/**
63
+	 * To use custom a cipher method and/or encryption keys:
64
+	 *  - extend this class
65
+	 *  - configure a new CipherMethod / EncryptionKeyManager in the constructor
66
+	 *  - pass those to this constructor, like so:
67
+	 *
68
+	 *      public function __construct(Base64Encoder $base64_encoder) {
69
+	 *          parent::__construct(
70
+	 *              $base64_encoder,
71
+	 *              new CipherMethod(CIPHER_METHOD, CIPHER_METHOD_OPTION_NAME)
72
+	 *              new EncryptionKeyManager(CUSTOM_KEY_ID, CUSTOM_KEYS_OPTION_NAME)
73
+	 *          );
74
+	 *      }
75
+	 *
76
+	 * @param Base64Encoder                      $base64_encoder
77
+	 * @param CipherMethod                       $cipher_method
78
+	 * @param EncryptionKeyManagerInterface|null $encryption_key_manager
79
+	 * @param string                             $min_php_version
80
+	 */
81
+	protected function __construct(
82
+		Base64Encoder $base64_encoder,
83
+		CipherMethod $cipher_method,
84
+		EncryptionKeyManagerInterface $encryption_key_manager,
85
+		$min_php_version
86
+	) {
87
+		$this->base64_encoder         = $base64_encoder;
88
+		$this->cipher_method          = $cipher_method;
89
+		$this->encryption_key_manager = $encryption_key_manager;
90
+		$this->min_php_version        = $min_php_version;
91
+		$this->openssl_installed      = extension_loaded('openssl');
92
+	}
93
+
94
+
95
+	/**
96
+	 * @return bool
97
+	 */
98
+	public function isCryptographicallySecure()
99
+	{
100
+		return true;
101
+	}
102
+
103
+
104
+	/**
105
+	 * @return bool
106
+	 */
107
+	public function canUse()
108
+	{
109
+		return $this->openssl_installed && version_compare(PHP_VERSION, $this->min_php_version, '>=');
110
+	}
111
+
112
+
113
+	/**
114
+	 * @return string
115
+	 */
116
+	public function canUseNotice()
117
+	{
118
+		if (! $this->openssl_installed) {
119
+			return esc_html__(
120
+				'The PHP openssl server extension is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
121
+				'event_espresso'
122
+			);
123
+		}
124
+		if (version_compare(PHP_VERSION, $this->min_php_version, '<')) {
125
+			return sprintf(
126
+				esc_html__(
127
+					'PHP version %1$s or greater is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
128
+					'event_espresso'
129
+				),
130
+				$this->min_php_version
131
+			);
132
+		}
133
+		return sprintf(
134
+			esc_html__('OpenSSL v1 encryption using %1$S is available for use.', 'event_espresso'),
135
+			OpenSSLv1::CIPHER_METHOD
136
+		);
137
+	}
138
+
139
+
140
+	/**
141
+	 * Computes the digest hash value using the specified digest method.
142
+	 * If that digest method fails to produce a valid hash value,
143
+	 * then we'll grab the next digest method and recursively try again until something works.
144
+	 *
145
+	 * @param string $encryption_key
146
+	 * @param string $digest_method
147
+	 * @return string
148
+	 * @throws RuntimeException
149
+	 */
150
+	protected function getDigestHashValue($encryption_key, $digest_method = OpenSSL::DEFAULT_DIGEST_METHOD)
151
+	{
152
+		$digest_hash_value = openssl_digest($encryption_key, $digest_method);
153
+		if ($digest_hash_value === false) {
154
+			return $this->getDigestHashValue($this->getDigestMethod());
155
+		}
156
+		return $digest_hash_value;
157
+	}
158
+
159
+
160
+	/**
161
+	 * Returns the NEXT element in the $digest_methods array.
162
+	 * If the $digest_methods array is empty, then we populate it
163
+	 * with the available values returned from openssl_get_md_methods().
164
+	 *
165
+	 * @return string
166
+	 * @throws RuntimeException
167
+	 */
168
+	private function getDigestMethod()
169
+	{
170
+		$digest_method = prev($this->digest_methods);
171
+		if (empty($this->digest_methods)) {
172
+			$this->digest_methods = openssl_get_md_methods();
173
+			$digest_method        = end($this->digest_methods);
174
+		}
175
+		if ($digest_method === false) {
176
+			throw new RuntimeException(
177
+				esc_html__(
178
+					'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
179
+					'event_espresso'
180
+				)
181
+			);
182
+		}
183
+		return $digest_method;
184
+	}
185 185
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@
 block discarded – undo
115 115
      */
116 116
     public function canUseNotice()
117 117
     {
118
-        if (! $this->openssl_installed) {
118
+        if ( ! $this->openssl_installed) {
119 119
             return esc_html__(
120 120
                 'The PHP openssl server extension is required to use Openssl encryption. Please contact your hosting provider regarding this issue.',
121 121
                 'event_espresso'
Please login to merge, or discard this patch.
core/services/encryption/openssl/CipherMethod.php 2 patches
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -15,137 +15,137 @@
 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
-     * @param string $cipher_method
93
-     * @return string
94
-     * @throws RuntimeException
95
-     */
96
-    private function getAvailableCipherMethod($cipher_method)
97
-    {
98
-        // verify that the incoming cipher method can produce an initialization vector
99
-        if (openssl_cipher_iv_length($cipher_method) === false) {
100
-            // what? there's no list?
101
-            if (empty($this->cipher_methods)) {
102
-                // generate that list and cache it
103
-                $this->cipher_methods = $this->getAvailableStrongCipherMethods();
104
-                // then grab the first item from the list
105
-                $cipher_method = reset($this->cipher_methods);
106
-            } else {
107
-                // check the next cipher in the list of available cipher methods
108
-                $cipher_method = next($this->cipher_methods);
109
-            }
110
-            if ($cipher_method === false) {
111
-                throw new RuntimeException(
112
-                    esc_html__(
113
-                        'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
114
-                        'event_espresso'
115
-                    )
116
-                );
117
-            }
118
-            // verify that the next cipher method works
119
-            return $this->getAvailableCipherMethod($cipher_method);
120
-        }
121
-        // if we've gotten this far, then we found an available cipher method that works
122
-        // so save that for next time
123
-        update_option($this->cipher_method_option_name, $cipher_method);
124
-        return $cipher_method;
125
-    }
126
-
127
-
128
-    /**
129
-     * @return array
130
-     */
131
-    private function getAvailableStrongCipherMethods()
132
-    {
133
-        $cipher_methods = openssl_get_cipher_methods();
134
-        return array_filter($cipher_methods, [$this, 'weakAlgorithmFilter']);
135
-    }
136
-
137
-
138
-    /**
139
-     * @see https://www.php.net/manual/en/function.openssl-get-cipher-methods.php#example-890
140
-     * @param string $cipher_method
141
-     */
142
-    private function weakAlgorithmFilter($cipher_method)
143
-    {
144
-        foreach ($this->weak_algorithms as $weak_algorithm) {
145
-            if (stripos($cipher_method, $weak_algorithm) !== false) {
146
-                return false;
147
-            }
148
-        }
149
-        return true;
150
-    }
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
+	 * @param string $cipher_method
93
+	 * @return string
94
+	 * @throws RuntimeException
95
+	 */
96
+	private function getAvailableCipherMethod($cipher_method)
97
+	{
98
+		// verify that the incoming cipher method can produce an initialization vector
99
+		if (openssl_cipher_iv_length($cipher_method) === false) {
100
+			// what? there's no list?
101
+			if (empty($this->cipher_methods)) {
102
+				// generate that list and cache it
103
+				$this->cipher_methods = $this->getAvailableStrongCipherMethods();
104
+				// then grab the first item from the list
105
+				$cipher_method = reset($this->cipher_methods);
106
+			} else {
107
+				// check the next cipher in the list of available cipher methods
108
+				$cipher_method = next($this->cipher_methods);
109
+			}
110
+			if ($cipher_method === false) {
111
+				throw new RuntimeException(
112
+					esc_html__(
113
+						'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
114
+						'event_espresso'
115
+					)
116
+				);
117
+			}
118
+			// verify that the next cipher method works
119
+			return $this->getAvailableCipherMethod($cipher_method);
120
+		}
121
+		// if we've gotten this far, then we found an available cipher method that works
122
+		// so save that for next time
123
+		update_option($this->cipher_method_option_name, $cipher_method);
124
+		return $cipher_method;
125
+	}
126
+
127
+
128
+	/**
129
+	 * @return array
130
+	 */
131
+	private function getAvailableStrongCipherMethods()
132
+	{
133
+		$cipher_methods = openssl_get_cipher_methods();
134
+		return array_filter($cipher_methods, [$this, 'weakAlgorithmFilter']);
135
+	}
136
+
137
+
138
+	/**
139
+	 * @see https://www.php.net/manual/en/function.openssl-get-cipher-methods.php#example-890
140
+	 * @param string $cipher_method
141
+	 */
142
+	private function weakAlgorithmFilter($cipher_method)
143
+	{
144
+		foreach ($this->weak_algorithms as $weak_algorithm) {
145
+			if (stripos($cipher_method, $weak_algorithm) !== false) {
146
+				return false;
147
+			}
148
+		}
149
+		return true;
150
+	}
151 151
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@
 block discarded – undo
43 43
      *
44 44
      * @var array
45 45
      */
46
-    private $weak_algorithms = [ 'des', 'ecb', 'md5', 'rc2', 'rc4' ];
46
+    private $weak_algorithms = ['des', 'ecb', 'md5', 'rc2', 'rc4'];
47 47
 
48 48
 
49 49
     /**
Please login to merge, or discard this patch.
core/services/encryption/EncryptionMethodInterface.php 1 patch
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -12,45 +12,45 @@
 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
-     * returns true if the method can be used on the current server
24
-     *
25
-     * @return bool
26
-     */
27
-    public function canUse();
28
-
29
-
30
-    /**
31
-     * returns a message explaining why the encryption method in question can or can not be used
32
-     *
33
-     * @return string
34
-     */
35
-    public function canUseNotice();
36
-
37
-
38
-    /**
39
-     * encrypts data
40
-     *
41
-     * @param string $text_to_encrypt    - the text to be encrypted
42
-     * @param string $encryption_key_identifier - name of the encryption key to use
43
-     * @return string
44
-     */
45
-    public function encrypt($text_to_encrypt, $encryption_key_identifier = '');
46
-
47
-
48
-    /**
49
-     * decrypts data
50
-     *
51
-     * @param string $encrypted_text - the text to be decrypted
52
-     * @param string $encryption_key_identifier - name of the encryption key to use
53
-     * @return string
54
-     */
55
-    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
+	 * returns true if the method can be used on the current server
24
+	 *
25
+	 * @return bool
26
+	 */
27
+	public function canUse();
28
+
29
+
30
+	/**
31
+	 * returns a message explaining why the encryption method in question can or can not be used
32
+	 *
33
+	 * @return string
34
+	 */
35
+	public function canUseNotice();
36
+
37
+
38
+	/**
39
+	 * encrypts data
40
+	 *
41
+	 * @param string $text_to_encrypt    - the text to be encrypted
42
+	 * @param string $encryption_key_identifier - name of the encryption key to use
43
+	 * @return string
44
+	 */
45
+	public function encrypt($text_to_encrypt, $encryption_key_identifier = '');
46
+
47
+
48
+	/**
49
+	 * decrypts data
50
+	 *
51
+	 * @param string $encrypted_text - the text to be decrypted
52
+	 * @param string $encryption_key_identifier - name of the encryption key to use
53
+	 * @return string
54
+	 */
55
+	public function decrypt($encrypted_text, $encryption_key_identifier = '');
56 56
 }
Please login to merge, or discard this patch.
core/services/encryption/Base64Encoder.php 2 patches
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -15,129 +15,129 @@
 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) || ! $this->isValidBase64($encoded_string)) {
60
-            return $encoded_string;
61
-        }
62
-        // decode
63
-        $decoded_string = base64_decode($encoded_string);
64
-        if ($decoded_string === false) {
65
-            throw new RuntimeException(
66
-                esc_html__('Base 64 decoding failed.', 'event_espresso')
67
-            );
68
-        }
69
-        return $decoded_string;
70
-    }
71
-
72
-
73
-    /**
74
-     * encodes  url string with PHP's base64 encoding
75
-     *
76
-     * @see http://php.net/manual/en/function.base64-encode.php
77
-     * @param string $text_string the text to be encoded
78
-     * @return string
79
-     */
80
-    public function encodeUrl($text_string = '')
81
-    {
82
-        // you give me nothing??? GET OUT !
83
-        if (empty($text_string) || ! $this->use_base64_encode) {
84
-            return $text_string;
85
-        }
86
-        // encode
87
-        $encoded_string = base64_encode($text_string);
88
-        // remove chars to make encoding more URL friendly
89
-        return strtr($encoded_string, '+/=', '-_,');
90
-    }
91
-
92
-
93
-    /**
94
-     * decodes  url string that has been encoded with PHP's base64 encoding
95
-     *
96
-     * @see http://php.net/manual/en/function.base64-encode.php
97
-     * @param string $encoded_string the text to be decoded
98
-     * @return string
99
-     * @throws RuntimeException
100
-     */
101
-    public function decodeUrl($encoded_string = '')
102
-    {
103
-        // you give me nothing??? GET OUT !
104
-        if (empty($encoded_string) || ! $this->isValidBase64($encoded_string)) {
105
-            return $encoded_string;
106
-        }
107
-        // replace previously removed characters
108
-        $encoded_string = strtr($encoded_string, '-_,', '+/=');
109
-        // decode
110
-        $decoded_string = base64_decode($encoded_string);
111
-        if ($decoded_string === false) {
112
-            throw new RuntimeException(
113
-                esc_html__('Base 64 decoding failed.', 'event_espresso')
114
-            );
115
-        }
116
-        return $decoded_string;
117
-    }
118
-
119
-
120
-    /**
121
-     * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
122
-     * @param $string
123
-     * @return bool
124
-     */
125
-    protected function isValidBase64($string)
126
-    {
127
-        // ensure data is a string
128
-        if (! is_string($string) || ! $this->use_base64_encode) {
129
-            return false;
130
-        }
131
-        $decoded = base64_decode($string, true);
132
-        // Check if there is no invalid character in string
133
-        if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
134
-            return false;
135
-        }
136
-        // Decode the string in strict mode and send the response
137
-        if (! base64_decode($string, true)) {
138
-            return false;
139
-        }
140
-        // Encode and compare it to original one
141
-        return base64_encode($decoded) === $string;
142
-    }
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) || ! $this->isValidBase64($encoded_string)) {
60
+			return $encoded_string;
61
+		}
62
+		// decode
63
+		$decoded_string = base64_decode($encoded_string);
64
+		if ($decoded_string === false) {
65
+			throw new RuntimeException(
66
+				esc_html__('Base 64 decoding failed.', 'event_espresso')
67
+			);
68
+		}
69
+		return $decoded_string;
70
+	}
71
+
72
+
73
+	/**
74
+	 * encodes  url string with PHP's base64 encoding
75
+	 *
76
+	 * @see http://php.net/manual/en/function.base64-encode.php
77
+	 * @param string $text_string the text to be encoded
78
+	 * @return string
79
+	 */
80
+	public function encodeUrl($text_string = '')
81
+	{
82
+		// you give me nothing??? GET OUT !
83
+		if (empty($text_string) || ! $this->use_base64_encode) {
84
+			return $text_string;
85
+		}
86
+		// encode
87
+		$encoded_string = base64_encode($text_string);
88
+		// remove chars to make encoding more URL friendly
89
+		return strtr($encoded_string, '+/=', '-_,');
90
+	}
91
+
92
+
93
+	/**
94
+	 * decodes  url string that has been encoded with PHP's base64 encoding
95
+	 *
96
+	 * @see http://php.net/manual/en/function.base64-encode.php
97
+	 * @param string $encoded_string the text to be decoded
98
+	 * @return string
99
+	 * @throws RuntimeException
100
+	 */
101
+	public function decodeUrl($encoded_string = '')
102
+	{
103
+		// you give me nothing??? GET OUT !
104
+		if (empty($encoded_string) || ! $this->isValidBase64($encoded_string)) {
105
+			return $encoded_string;
106
+		}
107
+		// replace previously removed characters
108
+		$encoded_string = strtr($encoded_string, '-_,', '+/=');
109
+		// decode
110
+		$decoded_string = base64_decode($encoded_string);
111
+		if ($decoded_string === false) {
112
+			throw new RuntimeException(
113
+				esc_html__('Base 64 decoding failed.', 'event_espresso')
114
+			);
115
+		}
116
+		return $decoded_string;
117
+	}
118
+
119
+
120
+	/**
121
+	 * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
122
+	 * @param $string
123
+	 * @return bool
124
+	 */
125
+	protected function isValidBase64($string)
126
+	{
127
+		// ensure data is a string
128
+		if (! is_string($string) || ! $this->use_base64_encode) {
129
+			return false;
130
+		}
131
+		$decoded = base64_decode($string, true);
132
+		// Check if there is no invalid character in string
133
+		if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
134
+			return false;
135
+		}
136
+		// Decode the string in strict mode and send the response
137
+		if (! base64_decode($string, true)) {
138
+			return false;
139
+		}
140
+		// Encode and compare it to original one
141
+		return base64_encode($decoded) === $string;
142
+	}
143 143
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -125,16 +125,16 @@
 block discarded – undo
125 125
     protected function isValidBase64($string)
126 126
     {
127 127
         // ensure data is a string
128
-        if (! is_string($string) || ! $this->use_base64_encode) {
128
+        if ( ! is_string($string) || ! $this->use_base64_encode) {
129 129
             return false;
130 130
         }
131 131
         $decoded = base64_decode($string, true);
132 132
         // Check if there is no invalid character in string
133
-        if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
133
+        if ( ! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
134 134
             return false;
135 135
         }
136 136
         // Decode the string in strict mode and send the response
137
-        if (! base64_decode($string, true)) {
137
+        if ( ! base64_decode($string, true)) {
138 138
             return false;
139 139
         }
140 140
         // Encode and compare it to original one
Please login to merge, or discard this patch.