/home/suroeste/public_html/payments.transportessuroeste.com/src/Services
Edit: /home/suroeste/public_html/payments.transportessuroeste.com/src/Services/EncryptionService.php (3867B)
key = strlen($key) === 32 ? $key : hash('sha256', $key, true);
}
/**
* Cifrar datos con AES-256-GCM + HMAC
*/
public function encrypt(mixed $data): string
{
$plaintext = is_string($data) ? $data : json_encode($data);
$iv = random_bytes(12);
$tag = '';
$ciphertext = openssl_encrypt($plaintext, self::METHOD, $this->key, OPENSSL_RAW_DATA, $iv, $tag, '', 16);
if ($ciphertext === false) {
throw new SecurityException('Error de cifrado');
}
$combined = $iv . $tag . $ciphertext;
$hmac = hash_hmac(self::HMAC_ALGO, $combined, $this->key, true);
return base64_encode($hmac . $combined);
}
/**
* Descifrar datos
*/
public function decrypt(string $encrypted): mixed
{
$decoded = base64_decode($encrypted, true);
if ($decoded === false) {
throw new SecurityException('Datos inválidos');
}
$hmac = substr($decoded, 0, 64);
$combined = substr($decoded, 64);
if (!hash_equals($hmac, hash_hmac(self::HMAC_ALGO, $combined, $this->key, true))) {
throw new SecurityException('Integridad comprometida');
}
$iv = substr($combined, 0, 12);
$tag = substr($combined, 12, 16);
$ciphertext = substr($combined, 28);
$plaintext = openssl_decrypt($ciphertext, self::METHOD, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
if ($plaintext === false) {
throw new SecurityException('Error de descifrado');
}
$json = json_decode($plaintext, true);
return $json ?? $plaintext;
}
/**
* Hash seguro para contraseñas (Argon2id si disponible, bcrypt como fallback)
*/
public function hashPassword(string $password): string
{
if (defined('PASSWORD_ARGON2ID')) {
return password_hash($password, PASSWORD_ARGON2ID, [
'memory_cost' => 65536,
'time_cost' => 4,
'threads' => 3
]);
}
return password_hash($password, PASSWORD_BCRYPT, [
'cost' => 12
]);
}
public function verifyPassword(string $password, string $hash): bool
{
return password_verify($password, $hash);
}
/**
* Generar firma HMAC
*/
public function sign(string $data): string
{
return hash_hmac(self::HMAC_ALGO, $data, $this->key);
}
/**
* Verificar firma HMAC
*/
public function verifySignature(string $data, string $signature): bool
{
return hash_equals($this->sign($data), $signature);
}
/**
* Generar API Key segura
*/
public function generateApiKey(string $prefix = 'ts'): string
{
return $prefix . '_' . bin2hex(random_bytes(24));
}
/**
* Generar UUID v4
*/
public function generateUuid(): string
{
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
}