nhance/app/Helpers/ClientTokenHelper.php
2025-04-16 11:05:18 +05:30

54 lines
1.6 KiB
PHP

<?php
namespace App\Helpers;
class ClientTokenHelper{
public static function generateKey($clientId,$length = 32)
{
$clientIdPart = bin2hex($clientId); // Convert client ID to hex
$randomPart = bin2hex(random_bytes($length)); // Random part
return $clientIdPart . ':' . $randomPart; // Combine with a delimiter
}
public static function extractClientId($token)
{
$parts = explode(':', $token);
return hex2bin($parts[0]); // Decode the hex client ID
}
public static function encryptData($data, $key)
{
$cipher = "AES-256-CBC";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
// Convert array to JSON string before encrypting
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
$encrypted = openssl_encrypt($jsonData, $cipher, $key, OPENSSL_RAW_DATA, $iv);
// Combine IV + encrypted, then base64 encode it to make it JSON-safe
return base64_encode($iv . $encrypted);
}
public static function decryptData($encryptedData, $key)
{
$cipher = "AES-256-CBC";
$data = base64_decode($encryptedData);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($data, 0, $ivlen); // Extract IV
$ciphertext = substr($data, $ivlen); // Extract Encrypted Payload
$decryptedJson = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
return json_decode($decryptedJson, true); // return as array
}
}