Completed
Branch FET-3467-waitlists (9ee75b)
by
unknown
91:40 queued 79:00
created

EE_Encryption::getDigestMethod()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 4
nop 0
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
defined('EVENT_ESPRESSO_VERSION') || exit('No direct script access allowed');
3
4
5
6
/**
7
 * EE_Encryption class
8
 * class for applying low-grade string encryption/decryption
9
 * really only good for hiding content from simple bots and script kiddies
10
 * but better for solving encoding issues with databases
11
 *
12
 * @package    Event Espresso
13
 * @subpackage includes/functions
14
 * @author     Brent Christensen
15
 */
16
class EE_Encryption
17
{
18
19
    /**
20
     * key used for saving the encryption key to the wp_options table
21
     */
22
    const ENCRYPTION_OPTION_KEY = 'ee_encryption_key';
23
24
    /**
25
     * the OPENSSL cipher method used
26
     */
27
    const OPENSSL_CIPHER_METHOD = 'AES-128-CBC';
28
29
    /**
30
     * WP "options_name" used to store a verified available cipher method
31
     */
32
    const OPENSSL_CIPHER_METHOD_OPTION_NAME = 'ee_openssl_cipher_method';
33
34
    /**
35
     * the OPENSSL digest method used
36
     */
37
    const OPENSSL_DIGEST_METHOD = 'sha512';
38
39
    /**
40
     * separates the encrypted text from the initialization vector
41
     */
42
    const OPENSSL_IV_DELIMITER = ':iv:';
43
44
    /**
45
     * appended to text encrypted using the acme encryption
46
     */
47
    const ACME_ENCRYPTION_FLAG = '::ae';
48
49
50
51
    /**
52
     * instance of the EE_Encryption object
53
     */
54
    protected static $_instance;
55
56
    /**
57
     * @var string $_encryption_key
58
     */
59
    protected $_encryption_key;
60
61
    /**
62
     * @var string $cipher_method
63
     */
64
    private $cipher_method = '';
65
66
    /**
67
     * @var array $cipher_methods
68
     */
69
    private $cipher_methods = array();
70
71
    /**
72
     * @var array $digest_methods
73
     */
74
    private $digest_methods = array();
75
76
    /**
77
     * @var boolean $_use_openssl_encrypt
78
     */
79
    protected $_use_openssl_encrypt = false;
80
81
    /**
82
     * @var boolean $_use_mcrypt
83
     */
84
    protected $_use_mcrypt = false;
85
86
    /**
87
     * @var boolean $_use_base64_encode
88
     */
89
    protected $_use_base64_encode = false;
90
91
92
93
    /**
94
     * protected constructor to prevent direct creation
95
     */
96
    protected function __construct()
97
    {
98
        if (! defined('ESPRESSO_ENCRYPT')) {
99
            define('ESPRESSO_ENCRYPT', true);
100
        }
101
        if (extension_loaded('openssl')) {
102
            $this->_use_openssl_encrypt = true;
103
        } else if (extension_loaded('mcrypt')) {
104
            $this->_use_mcrypt = true;
105
        }
106
        if (function_exists('base64_encode')) {
107
            $this->_use_base64_encode = true;
108
        }
109
    }
110
111
112
113
    /**
114
     * singleton method used to instantiate class object
115
     *
116
     * @return EE_Encryption
117
     */
118
    public static function instance()
119
    {
120
        // check if class object is instantiated
121
        if (! self::$_instance instanceof EE_Encryption) {
122
            self::$_instance = new self();
123
        }
124
        return self::$_instance;
125
    }
126
127
128
129
    /**
130
     * get encryption key
131
     *
132
     * @return string
133
     */
134
    public function get_encryption_key()
135
    {
136
        // if encryption key has not been set
137
        if (empty($this->_encryption_key)) {
138
            // retrieve encryption_key from db
139
            $this->_encryption_key = get_option(EE_Encryption::ENCRYPTION_OPTION_KEY, '');
140
            // WHAT?? No encryption_key in the db ??
141
            if ($this->_encryption_key === '') {
142
                // let's make one. And md5 it to make it just the right size for a key
143
                $new_key = md5($this->generate_random_string());
144
                // now save it to the db for later
145
                add_option(EE_Encryption::ENCRYPTION_OPTION_KEY, $new_key);
146
                // here's the key - FINALLY !
147
                $this->_encryption_key = $new_key;
148
            }
149
        }
150
        return $this->_encryption_key;
151
    }
152
153
154
155
    /**
156
     * encrypts data
157
     *
158
     * @param string $text_string - the text to be encrypted
159
     * @return string
160
     * @throws RuntimeException
161
     */
162
    public function encrypt($text_string = '')
163
    {
164
        // you give me nothing??? GET OUT !
165
        if (empty($text_string)) {
166
            return $text_string;
167
        }
168
        if ($this->_use_openssl_encrypt) {
169
            $encrypted_text = $this->openssl_encrypt($text_string);
170
        } else {
171
            $encrypted_text = $this->acme_encrypt($text_string);
172
        }
173
        return $encrypted_text;
174
    }
175
176
177
178
    /**
179
     * decrypts data
180
     *
181
     * @param string $encrypted_text - the text to be decrypted
182
     * @return string
183
     * @throws RuntimeException
184
     */
185
    public function decrypt($encrypted_text = '')
186
    {
187
        // you give me nothing??? GET OUT !
188
        if (empty($encrypted_text)) {
189
            return $encrypted_text;
190
        }
191
        // if PHP's mcrypt functions are installed then we'll use them
192
        if ($this->_use_openssl_encrypt) {
193
            $decrypted_text = $this->openssl_decrypt($encrypted_text);
194
        } else {
195
            $decrypted_text = $this->acme_decrypt($encrypted_text);
196
        }
197
        return $decrypted_text;
198
    }
199
200
201
202
    /**
203
     * encodes string with PHP's base64 encoding
204
     *
205
     * @see http://php.net/manual/en/function.base64-encode.php
206
     * @param string $text_string the text to be encoded
207
     * @return string
208
     */
209
    public function base64_string_encode($text_string = '')
210
    {
211
        // you give me nothing??? GET OUT !
212
        if (empty($text_string) || ! $this->_use_base64_encode) {
213
            return $text_string;
214
        }
215
        // encode
216
        return base64_encode($text_string);
217
    }
218
219
220
221
    /**
222
     * decodes string that has been encoded with PHP's base64 encoding
223
     *
224
     * @see http://php.net/manual/en/function.base64-encode.php
225
     * @param string $encoded_string the text to be decoded
226
     * @return string
227
     */
228
    public function base64_string_decode($encoded_string = '')
229
    {
230
        // you give me nothing??? GET OUT !
231
        if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
232
            return $encoded_string;
233
        }
234
        // decode
235
        return base64_decode($encoded_string);
236
    }
237
238
239
240
    /**
241
     * encodes  url string with PHP's base64 encoding
242
     *
243
     * @see http://php.net/manual/en/function.base64-encode.php
244
     * @param string $text_string the text to be encoded
245
     * @return string
246
     */
247
    public function base64_url_encode($text_string = '')
248
    {
249
        // you give me nothing??? GET OUT !
250
        if (empty($text_string) || ! $this->_use_base64_encode) {
251
            return $text_string;
252
        }
253
        // encode
254
        $encoded_string = base64_encode($text_string);
255
        // remove chars to make encoding more URL friendly
256
        return strtr($encoded_string, '+/=', '-_,');
257
    }
258
259
260
261
    /**
262
     * decodes  url string that has been encoded with PHP's base64 encoding
263
     *
264
     * @see http://php.net/manual/en/function.base64-encode.php
265
     * @param string $encoded_string the text to be decoded
266
     * @return string
267
     */
268
    public function base64_url_decode($encoded_string = '')
269
    {
270
        // you give me nothing??? GET OUT !
271
        if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
272
            return $encoded_string;
273
        }
274
        // replace previously removed characters
275
        $encoded_string = strtr($encoded_string, '-_,', '+/=');
276
        // decode
277
        return base64_decode($encoded_string);
278
    }
279
280
281
282
    /**
283
     * encrypts data using PHP's openssl functions
284
     *
285
     * @param string $text_string the text to be encrypted
286
     * @return string
287
     * @throws RuntimeException
288
     */
289
    protected function openssl_encrypt($text_string = '')
290
    {
291
        // you give me nothing??? GET OUT !
292
        if (empty($text_string)) {
293
            return $text_string;
294
        }
295
        $this->cipher_method = $this->getCipherMethod();
296
        // get initialization vector size
297
        $iv_size = openssl_cipher_iv_length($this->cipher_method);
298
        // generate initialization vector.
299
        // The second parameter ("crypto_strong") is passed by reference,
300
        // and is used to determines if the algorithm used was "cryptographically strong"
301
        // openssl_random_pseudo_bytes() will toggle it to either true or false
302
        $iv = openssl_random_pseudo_bytes($iv_size, $is_strong);
303
        if ($iv === false || $is_strong === false) {
304
            throw new RuntimeException(
305
                esc_html__('Failed to generate OpenSSL initialization vector.', 'event_espresso')
306
            );
307
        }
308
        // encrypt it
309
        $encrypted_text = openssl_encrypt(
310
            $text_string,
311
            $this->cipher_method,
312
            $this->getDigestHashValue(),
313
            0,
314
            $iv
315
        );
316
        // append the initialization vector
317
        $encrypted_text .= EE_Encryption::OPENSSL_IV_DELIMITER . $iv;
318
        // trim and maybe encode
319
        return $this->_use_base64_encode
320
            ? trim(base64_encode($encrypted_text))
321
            : trim($encrypted_text);
322
    }
323
324
325
326
    /**
327
     * Returns a cipher method that has been verified to work.
328
     * First checks if the cached cipher has been set already and if so, returns that.
329
     * Then tests the incoming default and returns that if it's good.
330
     * If not, then it retrieves the previously tested and saved cipher method.
331
     * But if that doesn't exist, then calls getAvailableCipherMethod()
332
     * to see what is available on the server, and returns the results.
333
     *
334
     * @param string $cipher_method
335
     * @return string
336
     * @throws RuntimeException
337
     */
338
    protected function getCipherMethod($cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD)
339
    {
340
        if($this->cipher_method !== ''){
341
            return $this->cipher_method;
342
        }
343
        // verify that the default cipher method can produce an initialization vector
344
        if (openssl_cipher_iv_length($cipher_method) === false) {
345
            // nope? okay let's get what we found in the past to work
346
            $cipher_method = get_option(EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME, '');
347
            // oops... haven't tested available cipher methods yet
348
            if($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
349
                $cipher_method = $this->getAvailableCipherMethod($cipher_method);
350
            }
351
        }
352
        return $cipher_method;
353
    }
354
355
356
357
    /**
358
     * @param string $cipher_method
359
     * @return string
360
     * @throws \RuntimeException
361
     */
362
    protected function getAvailableCipherMethod($cipher_method)
363
    {
364
        // verify that the incoming cipher method can produce an initialization vector
365
        if (openssl_cipher_iv_length($cipher_method) === false) {
366
            // nope? then check the next cipher in the list of available cipher methods
367
            $cipher_method = next($this->cipher_methods);
368
            // what? there's no list? then generate that list and cache it,
369
            if (empty($this->cipher_methods)) {
370
                $this->cipher_methods = openssl_get_cipher_methods();
371
                // then grab the first item from the list
372
                $cipher_method = reset($this->cipher_methods);
373
            }
374
            if($cipher_method === false){
375
                throw new RuntimeException(
376
                    esc_html__(
377
                        'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
378
                        'event_espresso'
379
                    )
380
                );
381
            }
382
            // verify that the next cipher method works
383
            return $this->getAvailableCipherMethod($cipher_method);
384
        }
385
        // if we've gotten this far, then we found an available cipher method that works
386
        // so save that for next time
387
        update_option(
388
            EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME,
389
            $cipher_method
390
        );
391
        return $cipher_method;
392
    }
393
394
395
396
    /**
397
     * decrypts data that has been encrypted with PHP's openssl functions
398
     *
399
     * @param string $encrypted_text the text to be decrypted
400
     * @return string
401
     * @throws RuntimeException
402
     */
403
    protected function openssl_decrypt($encrypted_text = '')
404
    {
405
        // you give me nothing??? GET OUT !
406
        if (empty($encrypted_text)) {
407
            return $encrypted_text;
408
        }
409
        // decode
410
        $encrypted_text = $this->valid_base_64($encrypted_text)
411
            ? base64_decode($encrypted_text)
412
            : $encrypted_text;
413
        $encrypted_components = explode(
414
            EE_Encryption::OPENSSL_IV_DELIMITER,
415
            $encrypted_text,
416
            2
417
        );
418
        // check that iv exists, and if not, maybe text was encoded using mcrypt?
419
        if ($this->_use_mcrypt && ! isset($encrypted_components[1])) {
420
            return $this->m_decrypt($encrypted_text);
0 ignored issues
show
Deprecated Code introduced by
The method EE_Encryption::m_decrypt() has been deprecated with message: 4.9.39

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
421
        }
422
        // decrypt it
423
        $decrypted_text = openssl_decrypt(
424
            $encrypted_components[0],
425
            $this->getCipherMethod(),
426
            $this->getDigestHashValue(),
427
            0,
428
            $encrypted_components[1]
429
        );
430
        $decrypted_text = trim($decrypted_text);
431
        return $decrypted_text;
432
    }
433
434
435
436
    /**
437
     * Computes the digest hash value using the specified digest method.
438
     * If that digest method fails to produce a valid hash value,
439
     * then we'll grab the next digest method and recursively try again until something works.
440
     *
441
     * @param string $digest_method
442
     * @return string
443
     * @throws RuntimeException
444
     */
445
    protected function getDigestHashValue($digest_method = EE_Encryption::OPENSSL_DIGEST_METHOD){
446
        $digest_hash_value = openssl_digest($this->get_encryption_key(), $digest_method);
447
        if ($digest_hash_value === false) {
448
            return $this->getDigestHashValue($this->getDigestMethod());
449
        }
450
        return $digest_hash_value;
451
    }
452
453
454
455
    /**
456
     * Returns the NEXT element in the $digest_methods array.
457
     * If the $digest_methods array is empty, then we populate it
458
     * with the available values returned from openssl_get_md_methods().
459
     *
460
     * @return string
461
     * @throws \RuntimeException
462
     */
463
    protected function getDigestMethod(){
464
        $digest_method = prev($this->digest_methods);
465
        if (empty($this->digest_methods)) {
466
            $this->digest_methods = openssl_get_md_methods();
467
            $digest_method = end($this->digest_methods);
468
        }
469
        if ($digest_method === false) {
470
            throw new RuntimeException(
471
                esc_html__(
472
                    'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
473
                    'event_espresso'
474
                )
475
            );
476
        }
477
        return $digest_method;
478
    }
479
480
481
    /**
482
     * encrypts data for acme servers that didn't bother to install PHP mcrypt
483
     *
484
     * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
485
     * @param string $text_string the text to be decrypted
486
     * @return string
487
     */
488
    protected function acme_encrypt($text_string = '')
489
    {
490
        // you give me nothing??? GET OUT !
491
        if (empty($text_string)) {
492
            return $text_string;
493
        }
494
        $key_bits = str_split(
495
            str_pad(
496
                '',
497
                strlen($text_string),
498
                $this->get_encryption_key(),
499
                STR_PAD_RIGHT
500
            )
501
        );
502
        $string_bits = str_split($text_string);
503 View Code Duplication
        foreach ($string_bits as $k => $v) {
504
            $temp = ord($v) + ord($key_bits[$k]);
505
            $string_bits[$k] = chr($temp > 255 ? ($temp - 256) : $temp);
506
        }
507
        $encrypted_text = implode('', $string_bits);
508
        $encrypted_text .= EE_Encryption::ACME_ENCRYPTION_FLAG;
509
        return $this->_use_base64_encode
510
            ? base64_encode($encrypted_text)
511
            : $encrypted_text;
512
    }
513
514
515
516
    /**
517
     * decrypts data for acme servers that didn't bother to install PHP mcrypt
518
     *
519
     * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
520
     * @param string $encrypted_text the text to be decrypted
521
     * @return string
522
     * @throws RuntimeException
523
     */
524
    protected function acme_decrypt($encrypted_text = '')
525
    {
526
        // you give me nothing??? GET OUT !
527
        if (empty($encrypted_text)) {
528
            return $encrypted_text;
529
        }
530
        // decode the data ?
531
        $encrypted_text = $this->valid_base_64($encrypted_text)
532
            ? base64_decode($encrypted_text)
533
            : $encrypted_text;
534
        if (
535
            $this->_use_mcrypt
536
            && strpos($encrypted_text, EE_Encryption::ACME_ENCRYPTION_FLAG) === false
537
        ){
538
            return $this->m_decrypt($encrypted_text);
0 ignored issues
show
Deprecated Code introduced by
The method EE_Encryption::m_decrypt() has been deprecated with message: 4.9.39

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
539
        }
540
        $encrypted_text = substr($encrypted_text, 0, -4);
541
        $key_bits = str_split(
542
            str_pad(
543
                '',
544
                strlen($encrypted_text),
545
                $this->get_encryption_key(),
546
                STR_PAD_RIGHT
547
            )
548
        );
549
        $string_bits = str_split($encrypted_text);
550 View Code Duplication
        foreach ($string_bits as $k => $v) {
551
            $temp = ord($v) - ord($key_bits[$k]);
552
            $string_bits[$k] = chr($temp < 0 ? ($temp + 256) : $temp);
553
        }
554
        return implode('', $string_bits);
555
    }
556
557
558
559
    /**
560
     * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
561
     * @param $string
562
     * @return bool
563
     */
564
    protected function valid_base_64($string)
565
    {
566
        // ensure data is a string
567
        if (! is_string($string) || ! $this->_use_base64_encode) {
568
            return false;
569
        }
570
        $decoded = base64_decode($string, true);
571
        // Check if there is no invalid character in string
572
        if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
573
            return false;
574
        }
575
        // Decode the string in strict mode and send the response
576
        if (! base64_decode($string, true)) {
577
            return false;
578
        }
579
        // Encode and compare it to original one
580
        return base64_encode($decoded) === $string;
581
    }
582
583
584
585
    /**
586
     * generate random string
587
     *
588
     * @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
589
     * @param int $length number of characters for random string
590
     * @return string
591
     */
592
    public function generate_random_string($length = 40)
593
    {
594
        $iterations = ceil($length / 40);
595
        $random_string = '';
596
        for ($i = 0; $i < $iterations; $i++) {
597
            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
598
        }
599
        $random_string = substr($random_string, 0, $length);
600
        return $random_string;
601
    }
602
603
604
605
    /**
606
     * encrypts data using PHP's mcrypt functions
607
     *
608
     * @deprecated 4.9.39
609
     * @param string $text_string
610
     * @internal   param $string - the text to be encrypted
611
     * @return string
612
     * @throws RuntimeException
613
     */
614
    protected function m_encrypt($text_string = '')
615
    {
616
        // you give me nothing??? GET OUT !
617
        if (empty($text_string)) {
618
            return $text_string;
619
        }
620
        // get the initialization vector size
621
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
622
        // initialization vector
623
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
624
        if ($iv === false) {
625
            throw new RuntimeException(
626
                esc_html__('Failed to generate mcrypt initialization vector.', 'event_espresso')
627
            );
628
        }
629
        // encrypt it
630
        $encrypted_text = mcrypt_encrypt(
631
            MCRYPT_RIJNDAEL_256,
632
            $this->get_encryption_key(),
633
            $text_string,
634
            MCRYPT_MODE_ECB,
635
            $iv
636
        );
637
        // trim and maybe encode
638
        return $this->_use_base64_encode
639
            ? trim(base64_encode($encrypted_text))
640
            : trim($encrypted_text);
641
    }
642
643
644
645
    /**
646
     * decrypts data that has been encrypted with PHP's mcrypt functions
647
     *
648
     * @deprecated 4.9.39
649
     * @param string $encrypted_text the text to be decrypted
650
     * @return string
651
     * @throws RuntimeException
652
     */
653
    protected function m_decrypt($encrypted_text = '')
654
    {
655
        // you give me nothing??? GET OUT !
656
        if (empty($encrypted_text)) {
657
            return $encrypted_text;
658
        }
659
        // decode
660
        $encrypted_text = $this->valid_base_64($encrypted_text)
661
            ? base64_decode($encrypted_text)
662
            : $encrypted_text;
663
        // get the initialization vector size
664
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
665
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
666
        if ($iv === false) {
667
            throw new RuntimeException(
668
                esc_html__('Failed to generate mcrypt initialization vector.', 'event_espresso')
669
            );
670
        }
671
        // decrypt it
672
        $decrypted_text = mcrypt_decrypt(
673
            MCRYPT_RIJNDAEL_256,
674
            $this->get_encryption_key(),
675
            $encrypted_text,
676
            MCRYPT_MODE_ECB,
677
            $iv
678
        );
679
        $decrypted_text = trim($decrypted_text);
680
        return $decrypted_text;
681
    }
682
683
}
684
/* End of file EE_Encryption.class.php */
685
/* Location: /includes/core/EE_Encryption.core.php */
686