🚀 مُصادَق: تحديث برمجي جديد 2026-05-03 16:43
This commit is contained in:
@@ -13,50 +13,36 @@ final class EncryptionService
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
// Load encryption key from secrets config
|
||||
$secrets = require __DIR__ . '/../../../config/secrets.php';
|
||||
$this->key = $secrets['encryption_key'] ?? '';
|
||||
// Load from config/secrets.php — NEVER from .env directly
|
||||
$secrets = require dirname(__DIR__, 3) . '/config/secrets.php';
|
||||
$key = $secrets['encryption_key'] ?? '';
|
||||
|
||||
// Ensure key is hexadecimal and convert to binary (32 bytes)
|
||||
if (strlen($this->key) === 64) {
|
||||
$this->key = hex2bin($this->key);
|
||||
}
|
||||
|
||||
if (strlen($this->key) !== 32) {
|
||||
throw new Exception("Security Error: Invalid ENCRYPTION_KEY length. Must be 32 bytes.");
|
||||
if (strlen($key) !== 32) {
|
||||
throw new \RuntimeException(
|
||||
'ENCRYPTION_KEY_B64 not set or invalid. ' .
|
||||
'Generate: php -r "echo base64_encode(random_bytes(32));"'
|
||||
);
|
||||
}
|
||||
$this->key = $key;
|
||||
}
|
||||
|
||||
public function encrypt(string $plaintext): string
|
||||
{
|
||||
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(self::METHOD));
|
||||
$ciphertext = openssl_encrypt($plaintext, self::METHOD, $this->key, 0, $iv, $tag);
|
||||
|
||||
if ($ciphertext === false) {
|
||||
throw new Exception("Encryption failed.");
|
||||
}
|
||||
|
||||
$iv = random_bytes(12); // 12 bytes for GCM
|
||||
$tag = '';
|
||||
$ciphertext = openssl_encrypt($plaintext, self::METHOD, $this->key, OPENSSL_RAW_DATA, $iv, $tag, '', 16);
|
||||
if ($ciphertext === false) throw new \RuntimeException('Encryption failed');
|
||||
return base64_encode($iv) . ':' . base64_encode($ciphertext) . ':' . base64_encode($tag);
|
||||
}
|
||||
|
||||
public function decrypt(string $encryptedData): string
|
||||
public function decrypt(string $data): string
|
||||
{
|
||||
$parts = explode(':', $encryptedData);
|
||||
if (count($parts) !== 3) {
|
||||
throw new Exception("Invalid encrypted data format.");
|
||||
}
|
||||
|
||||
[$ivBase64, $ciphertextBase64, $tagBase64] = $parts;
|
||||
$iv = base64_decode($ivBase64);
|
||||
$ciphertext = base64_decode($ciphertextBase64);
|
||||
$tag = base64_decode($tagBase64);
|
||||
|
||||
$plaintext = openssl_decrypt($ciphertext, self::METHOD, $this->key, 0, $iv, $tag);
|
||||
|
||||
if ($plaintext === false) {
|
||||
throw new Exception("Decryption failed.");
|
||||
}
|
||||
|
||||
[$iv64, $ct64, $tag64] = explode(':', $data);
|
||||
$plaintext = openssl_decrypt(
|
||||
base64_decode($ct64), self::METHOD, $this->key,
|
||||
OPENSSL_RAW_DATA, base64_decode($iv64), base64_decode($tag64)
|
||||
);
|
||||
if ($plaintext === false) throw new \RuntimeException('Decryption failed');
|
||||
return $plaintext;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user