# 签名与测试向量

> **答案**：KRIN 使用 HMAC-SHA256 为您的服务器与 KRIN 之间的每条消息签名：您的服务器为用户生成的积分墙链接，以及 KRIN 发送到您服务器的奖励回传。每条消息都对一个带时间戳的固定规范字符串签名，并且都有测试向量，供您在上线前检查代码。

以下是 KRIN 代码使用的格式。每次构建文档时，本页的每个签名都会与 KRIN API 规范中的测试向量进行核对，下方代码全部通过。

| 消息 | 签名方 | 验证方 | 密钥 | 时间窗口 |
|---|---|---|---|---|
| [签名积分墙链接](#签名积分墙链接) | 您的服务器 | KRIN | 广告位启动密钥 | 5 分钟，一次性 nonce |
| [奖励回传](#奖励回传) | KRIN | 您的服务器 | 广告位回传密钥 | 300 秒 |

适用于每条签名消息的规则：

- 签名是对规范字符串计算 HMAC-SHA256 后得到的小写十六进制值。各行用 `\n`（一个换行符）连接，末尾不加换行符。
- 请以恒定时间比较签名。
- 密钥只保存在您的服务器上。切勿将其放入浏览器、应用或您分享的 URL 中。
- 轮换期间，旧密钥和新密钥在您选择的宽限期内都有效，之后只有新密钥有效。

## 签名积分墙链接

您的服务器生成用户打开积分墙所用的链接：`https://wall.krin.io/w`，附带 `placement`、`user_id`、`ts`（Unix 秒）、一次性 `nonce`（16 到 128 个字符）和 `sig`。

```text
krin-launch-v1
{placement}
{user_id}
{ts}
{nonce}
{sub_ids}
```

如果您不传递追踪 sub-id（最多 5 个），`{sub_ids}` 为空。如果传递，则为排序后的键，以 `key=value` 形式用 `&` 连接，并按 RFC 3986 进行百分号编码（只有 `A-Z a-z 0-9 - . _ ~` 保持原样）。

**测试向量**：启动密钥 `kls_test_1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d`，广告位 `plc_01kbmz6v7r1s0e5d4c3b2a1z0y`，用户 `player-1042`，ts `1764867600`，nonce `n0nce-7f3a9c2e1b4d`，sub-id `s1=spring` 和 `s2=tiktok`：

```text
sig = 2b9e27a873a2d1da412af2d1d4a794ebc3f7e07f5a511117cc6cf494bf7b3800
```

## 奖励回传

KRIN 通知您的服务器为用户发放或撤销奖励。它会发送两种格式之一，两者都使用广告位回传密钥签名。

**POST JSON**：请求头为 `X-Krin-Signature: t=<unix>,v1=<hex>`，其中

```text
v1 = hex(HMAC-SHA256(postback_secret, "<t>.<raw body>"))
```

请使用收到的原始字节，在解析 JSON 之前计算。密钥轮换期间，请求头会带有两个 `v1` 值（`t=...,v1=<new>,v1=<old>`），任一匹配即可。

**GET URL 模板**：`sig` 覆盖以下各值，取 URL 解码后的原样：

```text
krin-pb-v2
{ts}
{conversion_id}
{kind}
{user_id}
{reward}
{payout_micros}
{test}
```

`{test}` 为 `0` 或 `1`，缺少它的模板会被 KRIN 拒绝。`test` 为 `1` 的消息是测试：请返回 2xx，且绝不发放奖励。

当 `t` 或 `ts` 与您的时钟相差超过 300 秒时，两种格式都应拒绝。

**测试向量**：回传密钥 `kps_test_5f2b9c1d8e7a4b3c2d1e0f9a8b7c6d5e`，`t = ts = 1764867600`。POST 请求体（确切字节，单行）：

```json
{"kind":"credit","conversion_id":"cnv_01kbnkrpg0fgz9y6hb7h6nwvvg","click_id":"clk_01kbnkrnzv2c4t3bq8xyn9w7fe","user_id":"player-1042","placement_id":"plc_01kbmz6v7r1s0e5d4c3b2a1z0y","offer_id":"ofr_01kbmy9x8w7v6t5s4r3q2p1n0m","event_key":"level_10","event_name":"Reach level 10","payout_micros":412500,"payout_usd":"0.4125","reward":"412","currency":"Gems","status":"approved","reason_code":null,"ip":null,"country":"US","ts":1764867600,"test":false}
```

| 检查项 | 预期结果 |
|---|---|
| POST `v1` | `d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc` |
| 同一转化的 GET `sig` | `53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555` |
| `test` = `1` 时同一转化的 GET `sig` | `84e8afb4c9eb9c8afb186a0b9a146c85ad9170ef131d89c4637b2572719f04b6` |
| 改动一个字节的同一请求体 | 必须失败 |
| 在 `t` 之后 301 秒检查的同一消息 | 必须失败 |

## 代码

每种语言一个文件，包含本页介绍的函数：签名积分墙链接、检查 POST 回传和检查 GET 回传。复制您需要的文件，或直接下载。

```js
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";

// RFC 3986: only A-Z a-z 0-9 - . _ ~ stay as they are.
const enc = (s) =>
  encodeURIComponent(s).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());

export function signLaunchUrl(secret, { placement, userId, subIds = {} },
    ts = Math.floor(Date.now() / 1000), nonce = randomBytes(16).toString("hex")) {
  const keys = Object.keys(subIds).sort();
  const sub = keys.map((k) => `${enc(k)}=${enc(subIds[k])}`).join("&");
  const message = ["krin-launch-v1", placement, userId, String(ts), nonce, sub].join("\n");
  const sig = createHmac("sha256", secret).update(message).digest("hex");
  const query = new URLSearchParams({ placement, user_id: userId, ts: String(ts), nonce, sig });
  for (const k of keys) query.append(`sub_ids[${k}]`, subIds[k]);
  return { url: `https://wall.krin.io/w?${query}`, sig };
}

const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));

// POST: header "t=<unix>,v1=<hex>" (two v1 values during a secret rotation).
// rawBody: the exact bytes KRIN sent. secrets: [current] or [new, old] while you rotate.
export function verifyPostbackPost(rawBody, header, secrets, now = Math.floor(Date.now() / 1000)) {
  let t = null;
  const sigs = [];
  for (const part of header.split(",")) {
    const [k, v = ""] = part.trim().split("=", 2);
    if (k === "t") t = v;
    else if (k === "v1") sigs.push(v);
  }
  if (!/^\d+$/.test(t ?? "") || Math.abs(now - Number(t)) > 300) return false;
  return secrets.some((secret) => {
    const expected = createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest("hex");
    return sigs.some((v) => same(v, expected));
  });
}

// GET: the decoded query values of the signed macros (krin-pb-v2; test is "0" or "1").
// A true result with q.test === "1" is a test postback: never credit it.
export function verifyPostbackGet(q, secrets, now = Math.floor(Date.now() / 1000)) {
  if (!/^\d+$/.test(q.ts ?? "") || Math.abs(now - Number(q.ts)) > 300) return false;
  if (q.test !== "0" && q.test !== "1") return false;
  const message = ["krin-pb-v2", q.ts, q.conversion_id, q.kind, q.user_id, q.reward, q.payout_micros, q.test].join("\n");
  return secrets.some((secret) =>
    same(String(q.sig ?? ""), createHmac("sha256", secret).update(message).digest("hex")));
}

// Advertiser S2S: sign the conversion you send to t.krin.io (postbacks.md 4.1, signature v2).
// The signature covers the request exactly as sent: method, host, path and the query without sig.
export function signInbound(secret, { offerKey, clickId, event, txnId = "" }, ts = Math.floor(Date.now() / 1000)) {
  const host = "t.krin.io";
  const path = `/pb/${encodeURIComponent(offerKey)}`;
  const params = new URLSearchParams({ click_id: clickId, event });
  if (txnId) params.set("txn_id", txnId);
  params.set("ts", String(ts));
  const query = params.toString();
  const sig = createHmac("sha256", secret).update(["krin-in-v2", "GET", host, path, query].join("\n")).digest("hex");
  return { url: `https://${host}${path}?${query}&sig=${sig}`, sig };
}
```

```php
<?php
// Sign a wall launch URL (sdk.md 2.1).
function krin_sign_launch_url(string $secret, string $placement, string $userId, array $subIds = [],
                              ?int $ts = null, ?string $nonce = null): string {
    ksort($subIds, SORT_STRING);
    $sub = implode('&', array_map(
        fn ($k) => rawurlencode((string) $k) . '=' . rawurlencode((string) $subIds[$k]),
        array_keys($subIds)
    ));
    $ts = (string) ($ts ?? time());
    $nonce ??= bin2hex(random_bytes(16));
    $sig = hash_hmac('sha256', implode("\n", ['krin-launch-v1', $placement, $userId, $ts, $nonce, $sub]), $secret);
    $query = ['placement' => $placement, 'user_id' => $userId, 'ts' => $ts, 'nonce' => $nonce, 'sig' => $sig];
    foreach ($subIds as $k => $v) {
        $query["sub_ids[$k]"] = $v;
    }
    return 'https://wall.krin.io/w?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986);
}

// Verify a POST reward postback. $rawBody = file_get_contents('php://input').
function krin_verify_postback_post(string $rawBody, string $header, array $secrets, ?int $now = null): bool {
    $now ??= time();
    $t = null;
    $sigs = [];
    foreach (explode(',', $header) as $part) {
        [$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($k === 't') { $t = $v; } elseif ($k === 'v1') { $sigs[] = $v; }
    }
    if ($t === null || !ctype_digit($t) || abs($now - (int) $t) > 300) {
        return false;
    }
    foreach ($secrets as $secret) {
        $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
        foreach ($sigs as $v) {
            if (hash_equals($expected, $v)) {
                return true;
            }
        }
    }
    return false;
}

// Verify a GET reward postback (krin-pb-v2). $q = $_GET (already decoded).
// A true result with $q['test'] === '1' is a test postback: never credit it.
function krin_verify_postback_get(array $q, array $secrets, ?int $now = null): bool {
    $now ??= time();
    $ts = (string) ($q['ts'] ?? '');
    if (!ctype_digit($ts) || abs($now - (int) $ts) > 300) {
        return false;
    }
    $test = (string) ($q['test'] ?? '');
    if ($test !== '0' && $test !== '1') {
        return false;
    }
    $message = implode("\n", ['krin-pb-v2', $ts, $q['conversion_id'] ?? '', $q['kind'] ?? '',
        $q['user_id'] ?? '', $q['reward'] ?? '', $q['payout_micros'] ?? '', $test]);
    foreach ($secrets as $secret) {
        if (hash_equals(hash_hmac('sha256', $message, $secret), (string) ($q['sig'] ?? ''))) {
            return true;
        }
    }
    return false;
}

// Advertiser S2S: sign the conversion you send to t.krin.io (postbacks.md 4.1, signature v2).
// The signature covers the request exactly as sent: method, host, path and the query without sig.
function krin_sign_inbound(string $secret, string $offerKey, string $clickId, string $event,
                           string $txnId = '', ?int $ts = null): string {
    $host = 't.krin.io';
    $path = '/pb/' . rawurlencode($offerKey);
    $params = ['click_id' => $clickId, 'event' => $event];
    if ($txnId !== '') {
        $params['txn_id'] = $txnId;
    }
    $params['ts'] = (string) ($ts ?? time());
    $query = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
    $sig = hash_hmac('sha256', implode("\n", ['krin-in-v2', 'GET', $host, $path, $query]), $secret);
    return "https://{$host}{$path}?{$query}&sig={$sig}";
}
```

```python
import hashlib
import hmac
import secrets as _secrets
import time
from urllib.parse import quote, urlencode

def _hex(secret: str, message: bytes) -> str:
    return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()

def sign_launch_url(secret, placement, user_id, sub_ids=None, ts=None, nonce=None):
    """Signed wall launch URL (sdk.md 2.1)."""
    sub_ids = sub_ids or {}
    keys = sorted(sub_ids)
    sub = "&".join(f"{quote(k, safe='')}={quote(sub_ids[k], safe='')}" for k in keys)
    ts = str(int(time.time()) if ts is None else ts)
    nonce = nonce or _secrets.token_hex(16)
    message = "\n".join(["krin-launch-v1", placement, user_id, ts, nonce, sub])
    sig = _hex(secret, message.encode())
    params = [("placement", placement), ("user_id", user_id), ("ts", ts), ("nonce", nonce), ("sig", sig)]
    params += [(f"sub_ids[{k}]", sub_ids[k]) for k in keys]
    return "https://wall.krin.io/w?" + urlencode(params, quote_via=quote)

def verify_postback_post(raw_body: bytes, header: str, secrets: list, now=None) -> bool:
    """POST reward postback: raw_body is the exact bytes KRIN sent."""
    now = int(time.time()) if now is None else now
    t, sigs = None, []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            t = value
        elif key == "v1":
            sigs.append(value)
    if not t or not t.isdigit() or abs(now - int(t)) > 300:
        return False
    for secret in secrets:
        expected = _hex(secret, t.encode() + b"." + raw_body)
        if any(hmac.compare_digest(expected, v) for v in sigs):
            return True
    return False

def verify_postback_get(q: dict, secrets: list, now=None) -> bool:
    """GET reward postback (krin-pb-v2): q holds the decoded query values.
    A True result with q["test"] == "1" is a test postback: never credit it."""
    now = int(time.time()) if now is None else now
    ts = str(q.get("ts", ""))
    if not ts.isdigit() or abs(now - int(ts)) > 300:
        return False
    test = str(q.get("test", ""))
    if test not in ("0", "1"):
        return False
    message = "\n".join(["krin-pb-v2", ts] + [str(q.get(k, "")) for k in
                         ("conversion_id", "kind", "user_id", "reward", "payout_micros")] + [test])
    return any(hmac.compare_digest(_hex(s, message.encode()), str(q.get("sig", ""))) for s in secrets)

def sign_inbound(secret, offer_key, click_id, event, txn_id="", ts=None):
    """Advertiser S2S conversion to t.krin.io (postbacks.md 4.1, signature v2).
    The signature covers the request exactly as sent: method, host, path and the query without sig."""
    host = "t.krin.io"
    path = "/pb/" + quote(offer_key, safe="")
    params = [("click_id", click_id), ("event", event)]
    if txn_id:
        params.append(("txn_id", txn_id))
    params.append(("ts", str(int(time.time()) if ts is None else ts)))
    query = urlencode(params, quote_via=quote)
    sig = _hex(secret, "\n".join(["krin-in-v2", "GET", host, path, query]).encode())
    return f"https://{host}{path}?{query}&sig={sig}"
```

下载：[krin.mjs](https://docs.krin.io/code/krin.mjs) · [krin.php](https://docs.krin.io/code/krin.php) · [krin.py](https://docs.krin.io/code/krin.py) · [test-vectors.json](https://docs.krin.io/postbacks/test-vectors.json)

## FAQ

**为什么 GET 检查通过了，POST 检查却失败？**
您很可能是在解析后重新序列化的 JSON 上计算 HMAC。请在原始字节上计算，保持其到达时的原样；空格或键顺序的任何变化都会改变结果。

**我的签名与测试向量一致，但 KRIN 仍然拒绝我的积分墙链接。为什么？**
请检查时间和 nonce。`ts` 与 KRIN 时钟的差距必须在 5 分钟以内，并且每个 nonce 只能使用一次，因此用户每次打开积分墙时都要签名一个新链接。

**sub-id 中哪些字符保持不编码？**
只有 `A-Z a-z 0-9 - . _ ~`（RFC 3986）。其他字符一律用大写十六进制编码为 `%XX`。在 JavaScript 中，`encodeURIComponent` 不会编码 `! ' ( ) *`，因此上面的代码也会对它们进行编码。

**我可以让积分墙链接和回传共用一个密钥吗？**
不可以。每个广告位都有自己的启动密钥和回传密钥，每个任务也有自己的入站密钥。请将它们分开保存，这样轮换其中一个时不会影响其他密钥。

