Files
intaleq_v2/app/Helpers/LegacyEncryption.php
2026-04-25 11:48:52 +03:00

103 lines
3.4 KiB
PHP

<?php
namespace App\Helpers;
/**
* مساعد التشفير القديم (Legacy Encryption Helper)
*
* الغرض من الملف:
* الحفاظ على التوافق مع الإصدار الأول (V1) للنظام من خلال القدرة على قراءة البيانات التي تم تشفيرها قديماً في قاعدة البيانات.
*
* كيفية العمل:
* 1. يستخدم خوارزمية AES-256-CBC مع مفتاح تشفير ثابت (IV) مماثل للمستخدم في النسخة القديمة.
* 2. يقوم بفك تشفير الحقول الحساسة مثل (رقم الهاتف، الاسم، العنوان) المحفوظة في قاعدة البيانات الأساسية.
* 3. يضمن أن البيانات المنتقلة من النظام القديم للنظام الجديد تظل قابلة للقراءة والاستخدام.
*/
class LegacyEncryption
{
private string $key;
private string $iv;
private string $cipher = 'aes-256-cbc';
public function __construct()
{
$keyPath = config('intaleq.legacy_enc_key_path', '/home/intaleq-api/.enckey');
if (!file_exists($keyPath)) {
throw new \RuntimeException("Encryption key file not found: {$keyPath}");
}
$this->key = trim(file_get_contents($keyPath));
$this->iv = config('intaleq.legacy_iv', env('initializationVector', ''));
if (strlen($this->iv) !== 16) {
$this->iv = str_pad($this->iv, 16, "\0");
}
}
/**
* Encrypt data (legacy format — for backward compatibility)
*/
public function encrypt(string $plainText): string
{
$padded = $this->pkcs5Pad($plainText);
$encrypted = openssl_encrypt($padded, $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);
return base64_encode($encrypted);
}
/**
* Decrypt data encrypted with legacy format
*/
public function decrypt(?string $cipherText): ?string
{
if (empty($cipherText)) {
return null;
}
try {
$decoded = base64_decode($cipherText);
if ($decoded === false) {
return $cipherText; // Not base64, return as-is
}
$decrypted = openssl_decrypt($decoded, $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);
if ($decrypted === false) {
return $cipherText; // Decryption failed, return as-is
}
return $this->pkcs5Unpad($decrypted);
} catch (\Exception $e) {
return $cipherText;
}
}
/**
* Decrypt multiple fields in an associative array
*/
public function decryptFields(array $data, array $fields): array
{
foreach ($fields as $field) {
if (!empty($data[$field])) {
$data[$field] = $this->decrypt($data[$field]);
}
}
return $data;
}
private function pkcs5Pad(string $text): string
{
$blockSize = 16;
$pad = $blockSize - (strlen($text) % $blockSize);
return $text . str_repeat(chr($pad), $pad);
}
private function pkcs5Unpad(string $text): string
{
$pad = ord($text[strlen($text) - 1]);
if ($pad > 16 || $pad === 0) {
return $text;
}
return substr($text, 0, -$pad);
}
}