Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório wordpress-ai-plugin, anteriormente
0
wordpress-ai-plugin/mozout-ai/includes/class-crypto.php
2026-12-01 13:25:59 +02:00

62 linhas
2,3 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 MOZOUT_AI_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 MOZOUT_AI_Crypto
{
private static function secret()
{
if (defined('MOZOUT_AI_ENCRYPTION_KEY') && MOZOUT_AI_ENCRYPTION_KEY) {
$material = (string) MOZOUT_AI_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', 'mozout-ai|' . $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('mozout_ai_no_openssl', __('This server cannot encrypt the key (the PHP OpenSSL extension is missing). Define MOZOUT_AI_API_KEY in wp-config.php instead.', 'mozout-ai'));
}
$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('mozout_ai_encrypt_failed', __('The key could not be encrypted.', 'mozout-ai'));
}
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;
}
}