| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
class WooMailerLiteEncryption { |
| 5 |
|
| 6 |
private $key; |
| 7 |
|
| 8 |
private $salt; |
| 9 |
|
| 10 |
protected static $instance = null; |
| 11 |
|
| 12 |
public function __construct() { |
| 13 |
$this->key = $this->getDefaultKey(); |
| 14 |
$this->salt = $this->getDefaultSalt(); |
| 15 |
} |
| 16 |
|
| 17 |
public static function instance() |
| 18 |
{ |
| 19 |
if (!empty(static::$instance)) { |
| 20 |
return static::$instance; |
| 21 |
} |
| 22 |
static::$instance = new static(); |
| 23 |
return static::$instance; |
| 24 |
} |
| 25 |
|
| 26 |
public function encrypt( $value ) { |
| 27 |
if ( ! extension_loaded( 'openssl' ) ) { |
| 28 |
return $value; |
| 29 |
} |
| 30 |
|
| 31 |
$method = 'aes-256-ctr'; |
| 32 |
$ivlen = openssl_cipher_iv_length( $method ); |
| 33 |
$iv = openssl_random_pseudo_bytes( $ivlen ); |
| 34 |
|
| 35 |
$raw_value = openssl_encrypt( $value . $this->salt, $method, $this->key, 0, $iv ); |
| 36 |
if ( ! $raw_value ) { |
| 37 |
return false; |
| 38 |
} |
| 39 |
|
| 40 |
return base64_encode( $iv . $raw_value ); |
| 41 |
} |
| 42 |
|
| 43 |
public function decrypt( $raw_value ) { |
| 44 |
if ( ! extension_loaded( 'openssl' ) ) { |
| 45 |
return $raw_value; |
| 46 |
} |
| 47 |
|
| 48 |
$raw_value = base64_decode( $raw_value, true ); |
| 49 |
|
| 50 |
$method = 'aes-256-ctr'; |
| 51 |
$ivlen = openssl_cipher_iv_length( $method ); |
| 52 |
$iv = substr( $raw_value, 0, $ivlen ); |
| 53 |
|
| 54 |
$raw_value = substr( $raw_value, $ivlen ); |
| 55 |
|
| 56 |
$value = openssl_decrypt( $raw_value, $method, $this->key, 0, $iv ); |
| 57 |
if ( ! $value || substr( $value, - strlen( $this->salt ) ) !== $this->salt ) { |
| 58 |
return false; |
| 59 |
} |
| 60 |
|
| 61 |
return substr( $value, 0, - strlen( $this->salt ) ); |
| 62 |
} |
| 63 |
|
| 64 |
protected function getDefaultKey() |
| 65 |
{ |
| 66 |
if ( defined( 'LOGGED_IN_KEY' ) && '' !== LOGGED_IN_KEY ) { |
| 67 |
return LOGGED_IN_KEY; |
| 68 |
} |
| 69 |
|
| 70 |
return 'this-is-a-fallback-key-but-not-secure'; |
| 71 |
} |
| 72 |
|
| 73 |
protected function getDefaultSalt() |
| 74 |
{ |
| 75 |
if ( defined( 'LOGGED_IN_SALT' ) && '' !== LOGGED_IN_SALT ) { |
| 76 |
return LOGGED_IN_SALT; |
| 77 |
} |
| 78 |
return 'this-is-a-fallback-salt-but-not-secure'; |
| 79 |
} |
| 80 |
|
| 81 |
} |
| 82 |
|