Files
intaleq_v2/app/Helpers/LegacyEncryption.php
2026-04-22 21:59:56 +03:00

98 lines
2.7 KiB
PHP

<?php
namespace App\Helpers;
/**
* Legacy Encryption Helper
*
* Backward-compatible encryption for data stored in the database.
* Uses AES-256-CBC with static IV (same as V1) to read existing encrypted data.
*
* WARNING: This class uses a static IV for backward compatibility only.
* For new payload encryption between Flutter and server, use PayloadCrypto service.
*/
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 = env('LEGACY_IV', '');
}
/**
* 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);
}
}