# Signatures and test vectors

> **Answer.** KRIN signs every message between your server and KRIN with HMAC-SHA256: the wall link your server builds for a user and the reward postback KRIN sends to your server. Each signs a fixed canonical string with a time stamp, and each has a test vector to check your code against before you go live.

These are the formats KRIN's code uses. Every signature on this page is checked against the test vectors in KRIN's API contract each time the docs are built, and the code below passes all of them.

| message | who signs | who checks | secret | time window |
|---|---|---|---|---|
| [Signed wall link](#signed-wall-link) | your server | KRIN | placement launch secret | 5 minutes, one-time nonce |
| [Reward postback](#reward-postback) | KRIN | your server | placement postback secret | 300 seconds |

Rules for every signed message:

- The signature is lowercase hex of HMAC-SHA256 over a canonical string. Lines are joined with `\n` (one line feed), with no line feed at the end.
- Compare signatures in constant time.
- Secrets stay on your server. Never put one in a browser, an app or a URL you share.
- During a rotation the old and the new secret both work for the grace period you chose, then only the new one.

## Signed wall link

Your server builds the link a user opens to reach the offer wall: `https://wall.krin.io/w` with `placement`, `user_id`, `ts` (unix seconds), a one-time `nonce` (16 to 128 characters) and `sig`.

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

`{sub_ids}` is empty unless you pass tracking sub-ids (up to 5). Then it is the keys sorted, `key=value` joined by `&`, percent-encoded as RFC 3986 (only `A-Z a-z 0-9 - . _ ~` stay as they are).

**Test vector.** Launch secret `kls_test_1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d`, placement `plc_01kbmz6v7r1s0e5d4c3b2a1z0y`, user `player-1042`, ts `1764867600`, nonce `n0nce-7f3a9c2e1b4d`, sub-ids `s1=spring` and `s2=tiktok`:

```text
sig = 2b9e27a873a2d1da412af2d1d4a794ebc3f7e07f5a511117cc6cf494bf7b3800
```

## Reward postback

KRIN tells your server to credit or reverse a user's reward. It sends one of two formats, both signed with the placement's postback secret.

**POST JSON.** The header is `X-Krin-Signature: t=<unix>,v1=<hex>`, and

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

Use the raw bytes you received, before any JSON parsing. During a secret rotation the header carries two `v1` values (`t=...,v1=<new>,v1=<old>`), and either may match.

**GET URL template.** `sig` covers these values exactly as they read after URL-decoding:

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

`{test}` is `0` or `1`, and KRIN refuses a template without it. A message whose `test` is `1` is a test: answer 2xx and never credit it.

Refuse either format when `t` or `ts` is more than 300 seconds away from your clock.

**Test vectors.** Postback secret `kps_test_5f2b9c1d8e7a4b3c2d1e0f9a8b7c6d5e`, `t = ts = 1764867600`. POST body (exact bytes, one line):

```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}
```

| check | expected |
|---|---|
| POST `v1` | `d2ac88178d4693b9a2a0382a66aada97a4ec9711ba44e6cd2961c34a0fb525cc` |
| GET `sig` for the same conversion | `53493e91b788502054cef2f461a753cbb08ced30af9972e3dcd5a4c56d85a555` |
| GET `sig`, same conversion with `test` = `1` | `84e8afb4c9eb9c8afb186a0b9a146c85ad9170ef131d89c4637b2572719f04b6` |
| the same body with one byte changed | must fail |
| the same message checked 301 seconds after `t` | must fail |

## The code

One file per language with the functions this page describes: sign a wall link, check a POST postback and check a GET postback. Copy the one you need, or download it.

```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}"
```

Downloads: [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

**Why does my POST check fail when the GET check passes?**
You are probably computing the HMAC over the parsed and re-serialized JSON. Compute it over the raw bytes exactly as they arrived; any change in spacing or key order changes the result.

**My signature matches the vector but KRIN still refuses my wall link. Why?**
Check the time and the nonce. `ts` must be within 5 minutes of KRIN's clock, and each nonce works once, so sign a fresh link every time a user opens the wall.

**Which characters stay unencoded in sub-ids?**
Only `A-Z a-z 0-9 - . _ ~` (RFC 3986). Encode everything else as `%XX` with uppercase hex. In JavaScript, `encodeURIComponent` leaves `! ' ( ) *`, so the code above encodes them too.

**Can I use one secret for both the wall link and the postback?**
No. Each placement has its own launch secret and its own postback secret, and an offer has its own inbound secret. Keep them separate so that rotating one never breaks the others.

