Initial V2 commit 4\5

This commit is contained in:
Hamza-Ayed
2026-04-22 23:56:02 +03:00
parent 3f4afd0f5c
commit d64a423db9
2 changed files with 83 additions and 24 deletions

View File

@@ -15,20 +15,42 @@ namespace App\Services;
*/
class PayloadCrypto
{
private string $key;
private ?string $key = null;
private const CIPHER = 'aes-256-gcm';
private const IV_LENGTH = 12;
private const TAG_LENGTH = 16;
public function __construct()
/**
* PayloadCrypto can be initialized with a specific key,
* or a key can be set later via setKeyFromSecret().
*/
public function __construct(?string $rawKey = null)
{
$keyPath = config('intaleq.legacy_enc_key_path');
if (!file_exists($keyPath)) {
throw new \RuntimeException('Encryption key not found');
if ($rawKey) {
$this->setKeyFromSecret($rawKey);
}
// Derive a 32-byte key from the stored key using HKDF
$rawKey = trim(file_get_contents($keyPath));
$this->key = hash_hkdf('sha256', $rawKey, 32, 'intaleq-v2-gcm');
}
/**
* Derives a 32-byte AES key from a raw secret (like api_secret) using HKDF.
*/
public function setKeyFromSecret(string $rawSecret): self
{
// Derive a 32-byte key from the secret using HKDF
$this->key = hash_hkdf('sha256', $rawSecret, 32, 'intaleq-v2-gcm');
return $this;
}
/**
* Set a 32-byte key directly.
*/
public function setRawKey(string $key): self
{
if (strlen($key) !== 32) {
throw new \InvalidArgumentException('Key must be exactly 32 bytes');
}
$this->key = $key;
return $this;
}
/**
@@ -39,6 +61,10 @@ class PayloadCrypto
*/
public function encrypt($data): string
{
if (!$this->key) {
throw new \RuntimeException('Encryption key not set. Call setKeyFromSecret() first.');
}
$plaintext = is_array($data) ? json_encode($data) : $data;
$iv = random_bytes(self::IV_LENGTH);
$tag = '';
@@ -70,6 +96,10 @@ class PayloadCrypto
*/
public function decrypt(string $encoded): ?string
{
if (!$this->key) {
throw new \RuntimeException('Decryption key not set. Call setKeyFromSecret() first.');
}
$raw = base64_decode($encoded, true);
if ($raw === false || strlen($raw) < self::IV_LENGTH + self::TAG_LENGTH + 1) {
return null;