<?php
/**
 * encryption.php - API Key এনক্রিপ্ট/ডিক্রিপ্ট (ডাটাবেজে সেফ রাখা)
 */
require_once __DIR__ . '/config.php';

function encryptKey($text) {
    if (empty($text)) return null;
    $key = substr(hash('sha256', ENCRYPTION_KEY, true), 0, 32);
    $iv = random_bytes(16);
    $encrypted = openssl_encrypt($text, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($iv . $encrypted);
}

function decryptKey($encryptedText) {
    if (empty($encryptedText)) return null;
    $raw = base64_decode($encryptedText, true);
    if ($raw === false || strlen($raw) < 17) return null;
    $key = substr(hash('sha256', ENCRYPTION_KEY, true), 0, 32);
    $iv = substr($raw, 0, 16);
    $cipher = substr($raw, 16);
    $decrypted = openssl_decrypt($cipher, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return $decrypted !== false ? $decrypted : null;
}
?>
