62 linhas
2,4 KiB
PHP
62 linhas
2,4 KiB
PHP
<?php
|
|
if (!defined('ABSPATH')) {
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* Encrypts the API key before it goes to the database (AES-256-GCM).
|
|
* The encryption key comes from INTERWEB_MZ_STATUS_ENCRYPTION_KEY, if defined in wp-config.php, or from the WordPress salts.
|
|
* If the salts change, the saved key can no longer be read and has to be saved again.
|
|
*/
|
|
class INTERWEB_MZ_STATUS_Crypto
|
|
{
|
|
private static function secret()
|
|
{
|
|
if (defined('INTERWEB_MZ_STATUS_ENCRYPTION_KEY') && INTERWEB_MZ_STATUS_ENCRYPTION_KEY) {
|
|
$material = (string) INTERWEB_MZ_STATUS_ENCRYPTION_KEY;
|
|
} else {
|
|
$material = (defined('AUTH_KEY') ? AUTH_KEY : '') . '|' . (defined('SECURE_AUTH_KEY') ? SECURE_AUTH_KEY : '')
|
|
. '|' . (defined('LOGGED_IN_SALT') ? LOGGED_IN_SALT : '');
|
|
}
|
|
return hash('sha256', 'interweb-mz-status|' . $material, true);
|
|
}
|
|
|
|
public static function available()
|
|
{
|
|
return function_exists('openssl_encrypt') && in_array('aes-256-gcm', array_map('strtolower', openssl_get_cipher_methods()), true);
|
|
}
|
|
|
|
public static function encrypt($plain)
|
|
{
|
|
if ($plain === '' || $plain === null) {
|
|
return '';
|
|
}
|
|
if (!self::available()) {
|
|
return new WP_Error('interweb_mz_status_no_openssl', __('This server cannot encrypt the key (the PHP OpenSSL extension is missing). Define INTERWEB_MZ_STATUS_API_KEY in wp-config.php instead.', 'interweb-mz-status'));
|
|
}
|
|
$iv = random_bytes(12);
|
|
$tag = '';
|
|
$ct = openssl_encrypt($plain, 'aes-256-gcm', self::secret(), OPENSSL_RAW_DATA, $iv, $tag);
|
|
if ($ct === false) {
|
|
return new WP_Error('interweb_mz_status_encrypt_failed', __('The key could not be encrypted.', 'interweb-mz-status'));
|
|
}
|
|
return 'v1:' . base64_encode($iv . $tag . $ct);
|
|
}
|
|
|
|
/** Returns the plain text, or '' when it cannot be read. */
|
|
public static function decrypt($stored)
|
|
{
|
|
if (!is_string($stored) || strpos($stored, 'v1:') !== 0 || !self::available()) {
|
|
return '';
|
|
}
|
|
$raw = base64_decode(substr($stored, 3), true);
|
|
if ($raw === false || strlen($raw) < 29) {
|
|
return '';
|
|
}
|
|
$iv = substr($raw, 0, 12);
|
|
$tag = substr($raw, 12, 16);
|
|
$ct = substr($raw, 28);
|
|
$plain = openssl_decrypt($ct, 'aes-256-gcm', self::secret(), OPENSSL_RAW_DATA, $iv, $tag);
|
|
return ($plain === false) ? '' : $plain;
|
|
}
|
|
}
|