| 1 |
<?php |
| 2 |
/** |
| 3 |
* Security Functions for API Key Encryption/Decryption |
| 4 |
* |
| 5 |
* @package BdThemes\AiImage |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace BDT_AI_IMG; |
| 9 |
|
| 10 |
// Exit if accessed directly |
| 11 |
if (!defined('ABSPATH')) { |
| 12 |
exit; |
| 13 |
} |
| 14 |
|
| 15 |
/** |
| 16 |
* Encrypt a string using AES-256-CBC encryption |
| 17 |
* |
| 18 |
* @param string $plain_text The text to encrypt |
| 19 |
* @return string The encrypted string (base64 encoded) |
| 20 |
*/ |
| 21 |
function encrypt_key($plain_text) { |
| 22 |
if (empty($plain_text)) { |
| 23 |
return ''; |
| 24 |
} |
| 25 |
|
| 26 |
// Get the encryption key from constant |
| 27 |
if (!defined('AI_IMAGE_ENCRYPTION_KEY')) { |
| 28 |
return $plain_text; // Return plain text if no encryption key is defined |
| 29 |
} |
| 30 |
|
| 31 |
$encryption_key = AI_IMAGE_ENCRYPTION_KEY; |
| 32 |
|
| 33 |
// Generate a key from the constant using MD5 (as requested) |
| 34 |
$key = md5($encryption_key, true); |
| 35 |
|
| 36 |
// Generate a random initialization vector |
| 37 |
$iv_length = openssl_cipher_iv_length('aes-256-cbc'); |
| 38 |
$iv = openssl_random_pseudo_bytes($iv_length); |
| 39 |
|
| 40 |
// Encrypt the data |
| 41 |
$encrypted = openssl_encrypt( |
| 42 |
$plain_text, |
| 43 |
'aes-256-cbc', |
| 44 |
$key, |
| 45 |
OPENSSL_RAW_DATA, |
| 46 |
$iv |
| 47 |
); |
| 48 |
|
| 49 |
// Combine IV and encrypted data, then base64 encode |
| 50 |
return base64_encode($iv . $encrypted); |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Decrypt a string using AES-256-CBC decryption |
| 55 |
* |
| 56 |
* @param string $encrypted_text The encrypted text (base64 encoded) |
| 57 |
* @return string The decrypted plain text |
| 58 |
*/ |
| 59 |
function decrypt_key($encrypted_text) { |
| 60 |
if (empty($encrypted_text)) { |
| 61 |
return ''; |
| 62 |
} |
| 63 |
|
| 64 |
// Get the encryption key from constant |
| 65 |
if (!defined('AI_IMAGE_ENCRYPTION_KEY')) { |
| 66 |
return $encrypted_text; // Return as-is if no encryption key is defined |
| 67 |
} |
| 68 |
|
| 69 |
$encryption_key = AI_IMAGE_ENCRYPTION_KEY; |
| 70 |
|
| 71 |
// Generate a key from the constant using MD5 (as requested) |
| 72 |
$key = md5($encryption_key, true); |
| 73 |
|
| 74 |
// Decode the base64 encoded data |
| 75 |
$data = base64_decode($encrypted_text); |
| 76 |
|
| 77 |
if ($data === false) { |
| 78 |
return ''; // Invalid base64 |
| 79 |
} |
| 80 |
|
| 81 |
// Extract IV and encrypted data |
| 82 |
$iv_length = openssl_cipher_iv_length('aes-256-cbc'); |
| 83 |
$iv = substr($data, 0, $iv_length); |
| 84 |
$encrypted = substr($data, $iv_length); |
| 85 |
|
| 86 |
// Decrypt the data |
| 87 |
$decrypted = openssl_decrypt( |
| 88 |
$encrypted, |
| 89 |
'aes-256-cbc', |
| 90 |
$key, |
| 91 |
OPENSSL_RAW_DATA, |
| 92 |
$iv |
| 93 |
); |
| 94 |
|
| 95 |
return $decrypted !== false ? $decrypted : ''; |
| 96 |
} |
| 97 |
|