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

85 lines
2.3 KiB
PHP

<?php
namespace App\Services;
use Exception;
class LegacyEncryption
{
private $key;
private $iv;
public function __construct()
{
$keyPath = config('intaleq.legacy_enc_key_path', '/home/intaleq-api/.enckey');
if (file_exists($keyPath)) {
$this->key = trim(file_get_contents($keyPath));
} else {
$this->key = env('LEGACY_ENC_KEY', '');
}
$this->iv = config('intaleq.legacy_iv', env('initializationVector', ''));
if (strlen($this->iv) !== 16) {
$this->iv = str_pad($this->iv, 16, "\0");
}
if (strlen($this->key) !== 32) {
// Log warning or throw error in production
}
if (strlen($this->iv) !== 16) {
// Log warning
}
}
/**
* Encrypt data using AES-256-CBC (Legacy V1 compatibility)
*/
public function encrypt($plainText)
{
if (empty($plainText)) return $plainText;
try {
$plainText = (string) $plainText;
$paddedText = $this->addPadding($plainText);
$encrypted = openssl_encrypt($paddedText, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
return base64_encode($encrypted);
} catch (Exception $e) {
return $plainText;
}
}
/**
* Decrypt data using AES-256-CBC (Legacy V1 compatibility)
*/
public function decrypt($encryptedText)
{
if (empty($encryptedText)) return $encryptedText;
try {
$decoded = base64_decode($encryptedText, true);
if ($decoded === false) return $encryptedText;
$decrypted = openssl_decrypt($decoded, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
if ($decrypted === false) return $encryptedText;
return $this->removePadding($decrypted);
} catch (Exception $e) {
return $encryptedText;
}
}
private function addPadding($data, $blockSize = 16)
{
$pad = $blockSize - (strlen($data) % $blockSize);
return $data . str_repeat(chr($pad), $pad);
}
private function removePadding($data)
{
$pad = ord($data[strlen($data) - 1]);
if ($pad < 1 || $pad > 16) return $data;
return substr($data, 0, -$pad);
}
}