<?php
declare(strict_types=1);

/**
 * 主题静态加解密（无在线授权）。
 * 发布前请修改 YUSER_THEME_SECRET，并用 tools/theme_encrypt.php 生成 .yenc 包。
 */
const YUSER_THEME_SECRET = 'BUACG000333';
const YUSER_ENC_MAGIC = 'YENC1';

function yuser_crypto_key(): string
{
    $env = getenv('YUSER_THEME_SECRET');
    if (is_string($env) && $env !== '') {
        return hash('sha256', $env, true);
    }
    return hash('sha256', YUSER_THEME_SECRET, true);
}

function yuser_encrypt_bytes(string $plain): string
{
    $key = yuser_crypto_key();
    $iv = random_bytes(16);
    $cipher = openssl_encrypt($plain, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    if ($cipher === false) {
        throw new RuntimeException('encrypt failed');
    }
    $payload = YUSER_ENC_MAGIC . $iv . $cipher;
    $mac = hash_hmac('sha256', $payload, $key, true);
    return $payload . $mac;
}

function yuser_decrypt_bytes(string $blob): string
{
    $key = yuser_crypto_key();
    if (strlen($blob) < 5 + 16 + 32) {
        throw new RuntimeException('invalid blob');
    }
    if (substr($blob, 0, 5) !== YUSER_ENC_MAGIC) {
        throw new RuntimeException('bad magic');
    }
    $mac = substr($blob, -32);
    $payload = substr($blob, 0, -32);
    $expect = hash_hmac('sha256', $payload, $key, true);
    if (!hash_equals($expect, $mac)) {
        throw new RuntimeException('hmac mismatch');
    }
    $iv = substr($payload, 5, 16);
    $cipher = substr($payload, 21);
    $plain = openssl_decrypt($cipher, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    if ($plain === false) {
        throw new RuntimeException('decrypt failed');
    }
    return $plain;
}
