<?php
// 依赖: PHP 7.4+ 且启用 openssl 扩展
$BASE   = '{{BASE}}';
$CODE   = 'YOUR-CARD-KEY';               // 待验证的卡密

/* 1. 生成客户端 RSA 密钥对(用于让服务器加密返回) */
$res = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
openssl_pkey_export($res, $clientPriv);
$clientPub = openssl_pkey_get_details($res)['key'];

/* 2. 获取服务器公钥 */
$serverPub = json_decode(file_get_contents('{{PUBKEY}}'), true)['data']['public_key'];
$serverKey = openssl_pkey_get_public($serverPub);

/* 3. RSA-OAEP 分块加/解密(每块 190 字节, 以 | 连接) */
function kami_encrypt($plain, $key) {
    $out = '';
    foreach (str_split($plain, 190) as $chunk) {
        openssl_public_encrypt($chunk, $enc, $key, OPENSSL_PKCS1_OAEP_PADDING);
        $out .= base64_encode($enc) . '|';
    }
    return rtrim($out, '|');
}
function kami_decrypt($cipher, $key) {
    $out = '';
    foreach (explode('|', $cipher) as $chunk) {
        openssl_private_decrypt(base64_decode($chunk), $dec, $key, OPENSSL_PKCS1_OAEP_PADDING);
        $out .= $dec;
    }
    return $out;
}

/* 4. 组装并加密请求 */
$payload = json_encode([
    'code'              => $CODE,
    'timestamp'         => time(),
    'client_public_key' => $clientPub,
]);
$body = json_encode(['encrypted' => kami_encrypt($payload, $serverKey)]);

/* 5. 发送请求 */
$ctx = stream_context_create(['http' => [
    'method'        => 'POST',
    'header'        => "Content-Type: application/json\r\n",
    'content'       => $body,
    'timeout'       => 15,
    'ignore_errors' => true,
]]);
$resp = json_decode(file_get_contents('{{VERIFY}}', false, $ctx), true);

/* 6. 解密响应 */
if (isset($resp['encrypted'])) {
    echo kami_decrypt($resp['encrypted'], $clientPriv);
} else {
    echo json_encode($resp, JSON_UNESCAPED_UNICODE);
}
