| 1 |
<?php |
| 2 |
if ( ! defined( 'ABSPATH' ) ) { |
| 3 |
exit; |
| 4 |
} |
| 5 |
class WPDBBackupSymmetricEncryption { |
| 6 |
|
| 7 |
private $cipher; |
| 8 |
|
| 9 |
public function __construct($cipher = 'aes-256-cbc') { |
| 10 |
$this->cipher = $cipher; |
| 11 |
} |
| 12 |
|
| 13 |
private function getKeySize() { |
| 14 |
if (preg_match("/([0-9]+)/i", $this->cipher, $matches)) { |
| 15 |
return $matches[1] >> 3; |
| 16 |
} |
| 17 |
return 0; |
| 18 |
} |
| 19 |
|
| 20 |
private function derived($password, $salt) { |
| 21 |
|
| 22 |
$AESKeyLength = $this->getKeySize(); |
| 23 |
$AESIVLength = openssl_cipher_iv_length($this->cipher); |
| 24 |
|
| 25 |
$pbkdf2 = hash_pbkdf2("SHA1", $password, mb_convert_encoding($salt, 'UTF-16LE'), 1000, $AESKeyLength + $AESIVLength, TRUE); |
| 26 |
|
| 27 |
$key = substr($pbkdf2, 0, $AESKeyLength); |
| 28 |
$iv = substr($pbkdf2, $AESKeyLength, $AESIVLength); |
| 29 |
|
| 30 |
$derived = new stdClass(); |
| 31 |
$derived->key = $key; |
| 32 |
$derived->iv = $iv; |
| 33 |
return $derived; |
| 34 |
} |
| 35 |
|
| 36 |
function encrypt($message, $password, $salt) { |
| 37 |
$derived = $this->derived($password, $salt); |
| 38 |
$enc = openssl_encrypt(mb_convert_encoding($message, 'UTF-16', 'UTF-8'), $this->cipher, $derived->key, 0, $derived->iv); |
| 39 |
return '$$'.$enc.'$$'; |
| 40 |
} |
| 41 |
|
| 42 |
function decrypt($message, $password, $salt) { |
| 43 |
$derived = $this->derived($password, $salt); |
| 44 |
$dec = openssl_decrypt($message, $this->cipher, $derived->key, 0, $derived->iv); |
| 45 |
return mb_convert_encoding($dec, 'UTF-8', 'UTF-16'); |
| 46 |
} |
| 47 |
|
| 48 |
} |