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); } }