50 lines
1.3 KiB
PHP
50 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Support\Facades\Session;
|
|
|
|
class EncryptionService
|
|
{
|
|
const ALGORITHM = 'aes-256-ctr';
|
|
private $password;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->password = $this->getPasswordFromCookie();
|
|
}
|
|
|
|
private function getPasswordFromCookie()
|
|
{
|
|
$cookieService = app(CookieService::class);
|
|
$cookie = $cookieService->getCookie(process.env.REACT_APP_TOKEN ?? 'token');
|
|
return $cookie['token'] ?? 'default_password'; // Fallback if token not found
|
|
}
|
|
|
|
public function encrypt(string $text): string
|
|
{
|
|
$iv = random_bytes(16); // Initialization vector
|
|
$encrypted = openssl_encrypt($text, self::ALGORITHM, $this->password, 0, $iv);
|
|
return base64_encode($iv . $encrypted); // Combine IV and encrypted data
|
|
}
|
|
|
|
public function decrypt(string $text): string|bool
|
|
{
|
|
$data = base64_decode($text);
|
|
$iv = substr($data, 0, 16);
|
|
$encrypted = substr($data, 16);
|
|
|
|
$decrypted = openssl_decrypt($encrypted, self::ALGORITHM, $this->password, 0, $iv);
|
|
|
|
if ($decrypted === false) {
|
|
return false;
|
|
}
|
|
|
|
// Check if the result is hexadecimal (simulating your JS check)
|
|
if (preg_match('/^[0-9a-fA-F]+$/', $decrypted)) {
|
|
return $decrypted;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
} |