79 lines
2.4 KiB
PHP
79 lines
2.4 KiB
PHP
<?php
|
|
namespace App\Helpers;
|
|
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class EncryptionHelper
|
|
{
|
|
|
|
/**
|
|
* Encrypt using a custom key (independent of APP_KEY)
|
|
* Useful for tokens that should survive APP_KEY rotation
|
|
*/
|
|
public static function encryptWithCustomKey(string $string, string $key): string
|
|
{
|
|
try {
|
|
$cipher = 'AES-256-CBC';
|
|
$ivLength = openssl_cipher_iv_length($cipher);
|
|
$iv = openssl_random_pseudo_bytes($ivLength);
|
|
|
|
$encrypted = openssl_encrypt($string, $cipher, $key, 0, $iv);
|
|
|
|
if ($encrypted === false) {
|
|
throw new \RuntimeException('Encryption failed');
|
|
}
|
|
|
|
// Combinar IV + encrypted data y codificar en base64
|
|
return base64_encode($iv . $encrypted);
|
|
} catch (\Exception $e) {
|
|
throw new \RuntimeException("Error al encriptar con clave personalizada: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Decrypt using a custom key (independent of APP_KEY)
|
|
*/
|
|
public static function decryptWithCustomKey(string $encryptedString, string $key): ?string
|
|
{
|
|
try {
|
|
$cipher = 'AES-256-CBC';
|
|
$ivLength = openssl_cipher_iv_length($cipher);
|
|
|
|
// Decodificar y separar IV + encrypted data
|
|
$data = base64_decode($encryptedString);
|
|
if ($data === false) {
|
|
return null;
|
|
}
|
|
|
|
$iv = substr($data, 0, $ivLength);
|
|
$encrypted = substr($data, $ivLength);
|
|
|
|
$decrypted = openssl_decrypt($encrypted, $cipher, $key, 0, $iv);
|
|
|
|
if ($decrypted === false) {
|
|
Log::error('Error al desencriptar con clave personalizada');
|
|
return null;
|
|
}
|
|
|
|
return $decrypted;
|
|
} catch (\Exception $e) {
|
|
Log::error('Error inesperado al desencriptar con clave personalizada: ' . $e->getMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Verify if a plain value matches a value encrypted with custom key
|
|
*/
|
|
public static function verifyWithCustomKey(string $plainValue, string $encryptedValue, string $key): bool
|
|
{
|
|
try {
|
|
$decrypted = self::decryptWithCustomKey($encryptedValue, $key);
|
|
return $decrypted === $plainValue;
|
|
} catch (\Exception $e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
}
|