Skip to content
pi-c Documentation
Login

Documentation

/* See noise.h. Noise's names (MixHash, MixKey, MixKeyAndHash, EncryptAndHash) are kept in the
 * comments so the code reads against the specification, revision 34. */
#include <string.h>

#include "bearssl.h"
#include "noise.h"
#include "platform.h"

#define NZ_IK "Noise_IK_P256_AESGCM_SHA256"
#define NZ_IKPSK1 "Noise_IKpsk1_P256_AESGCM_SHA256"

static void nz_wipe(void *p, size_t n) {
    volatile unsigned char *v = p;
    while (n--) {
        *v++ = 0;
    }
}

void pic_noise_sha256(unsigned char out[32], const void *a, size_t an, const void *b, size_t bn) {
    br_sha256_context c;
    br_sha256_init(&c);
    br_sha256_update(&c, a, an);
    if (bn) {
        br_sha256_update(&c, b, bn);
    }
    br_sha256_out(&c, out);
}

void pic_noise_hmac(unsigned char out[32], const void *key, size_t kn, const void *a, size_t an, const void *b,
                    size_t bn) {
    br_hmac_key_context kc;
    br_hmac_context c;
    br_hmac_key_init(&kc, &br_sha256_vtable, key, kn);
    br_hmac_init(&c, &kc, 0);
    br_hmac_update(&c, a, an);
    if (bn) {
        br_hmac_update(&c, b, bn);
    }
    br_hmac_out(&c, out);
    nz_wipe(&kc, sizeof kc);
    nz_wipe(&c, sizeof c);
}

void pic_noise_id(unsigned char out[16], const char *label, const unsigned char token[32]) {
    unsigned char d[32];
    pic_noise_sha256(d, label, strlen(label), token, 32);
    memcpy(out, d, 16);
}

void pic_noise_pair_derive(const unsigned char ps[32], unsigned char psk[32], unsigned char token[32],
                           unsigned char channel[16]) {
    static const char lp[] = "pic-rc/1 pair psk", lt[] = "pic-rc/1 pair token";
    pic_noise_hmac(psk, ps, 32, lp, sizeof lp - 1, NULL, 0);
    pic_noise_hmac(token, ps, 32, lt, sizeof lt - 1, NULL, 0);
    pic_noise_id(channel, "pic-rc/1 channel", token);
}

void pic_noise_offer(const unsigned char mailbox[16], const unsigned char pub[PIC_NOISE_PUB], const unsigned char ps[32],
                     uint64_t expires, unsigned char out[PIC_NOISE_OFFER]) {
    out[0] = 0x01;
    memcpy(out + 1, mailbox, 16);
    memcpy(out + 17, pub, PIC_NOISE_PUB);
    memcpy(out + 82, ps, 32);
    for (int i = 0; i < 8; i++) {
        out[114 + i] = (unsigned char)(expires >> (8 * (7 - i)));
    }
}

int pic_noise_offer_read(const unsigned char *in, size_t n, unsigned char mailbox[16], unsigned char pub[PIC_NOISE_PUB],
                         unsigned char ps[32], uint64_t *expires) {
    if (n != PIC_NOISE_OFFER || in[0] != 0x01) {
        return -1;
    }
    memcpy(mailbox, in + 1, 16);
    memcpy(pub, in + 17, PIC_NOISE_PUB);
    memcpy(ps, in + 82, 32);
    *expires = 0;
    for (int i = 0; i < 8; i++) {
        *expires = (*expires << 8) | in[114 + i];
    }
    return 0;
}

/* ---- P-256 (section 2's DH) ------------------------------------------------ */

int pic_noise_pub_valid(const unsigned char pub[PIC_NOISE_PUB]) {
    unsigned char p[PIC_NOISE_PUB];
    static const unsigned char one = 1;
    if (pub[0] != 0x04) {
        return 0;
    }
    memcpy(p, pub, sizeof p);
    return br_ec_p256_m31.mul(p, sizeof p, &one, 1, BR_EC_secp256r1) == 1;
}

/* The X coordinate of PRIV times PUB; -1 when PUB is not a valid point. */
static int nz_dh(unsigned char out[32], const unsigned char priv[32], const unsigned char pub[PIC_NOISE_PUB]) {
    unsigned char p[PIC_NOISE_PUB];
    if (pub[0] != 0x04) {
        return -1;
    }
    memcpy(p, pub, sizeof p);
    if (br_ec_p256_m31.mul(p, sizeof p, priv, 32, BR_EC_secp256r1) != 1) {
        nz_wipe(p, sizeof p);
        return -1;
    }
    memcpy(out, p + 1, 32);
    nz_wipe(p, sizeof p);
    return 0;
}

int pic_noise_keypair_make(pic_noise_keypair *k, const unsigned char *priv) {
    if (priv) {
        memcpy(k->priv, priv, PIC_NOISE_PRIV);
    } else {
        /* A scalar whose first four bytes are not all 0xff is below the group order, and one that
         * is zero is refused: retrying those leaves a uniform key in [1, n - 1]. */
        static const unsigned char zero[PIC_NOISE_PRIV];
        do {
            if (pic_platform_get()->entropy(k->priv, PIC_NOISE_PRIV) != 0) {
                return -1;
            }
        } while ((k->priv[0] & k->priv[1] & k->priv[2] & k->priv[3]) == 0xff ||
                 memcmp(k->priv, zero, sizeof zero) == 0);
    }
    return br_ec_p256_m31.mulgen(k->pub, k->priv, PIC_NOISE_PRIV, BR_EC_secp256r1) == PIC_NOISE_PUB ? 0 : -1;
}

/* ---- the symmetric state (Noise 5.1, 5.2) ------------------------------------ */

static void nz_mix_hash(pic_noise_hs *hs, const unsigned char *d, size_t n) { pic_noise_sha256(hs->h, hs->h, 32, d, n); }

/* HKDF(ck, ikm) as section 4.3 writes it: up to three outputs. */
static void nz_hkdf(const unsigned char ck[32], const unsigned char *ikm, size_t n, unsigned char o1[32],
                    unsigned char o2[32], unsigned char *o3) {
    unsigned char t[32];
    static const unsigned char one = 1, two = 2, three = 3;
    pic_noise_hmac(t, ck, 32, ikm, n, NULL, 0);
    pic_noise_hmac(o1, t, 32, &one, 1, NULL, 0);
    pic_noise_hmac(o2, t, 32, o1, 32, &two, 1);
    if (o3) {
        pic_noise_hmac(o3, t, 32, o2, 32, &three, 1);
    }
    nz_wipe(t, sizeof t);
}

static void nz_mix_key(pic_noise_hs *hs, const unsigned char *ikm, size_t n) {
    unsigned char a[32], b[32];
    nz_hkdf(hs->ck, ikm, n, a, b, NULL);
    memcpy(hs->ck, a, 32);
    memcpy(hs->k, b, 32);
    hs->has_k = 1;
    hs->n = 0;
    nz_wipe(a, sizeof a);
    nz_wipe(b, sizeof b);
}

static void nz_mix_key_and_hash(pic_noise_hs *hs, const unsigned char *ikm, size_t n) {
    unsigned char a[32], b[32], c[32];
    nz_hkdf(hs->ck, ikm, n, a, b, c);
    memcpy(hs->ck, a, 32);
    nz_mix_hash(hs, b, 32);
    memcpy(hs->k, c, 32);
    hs->has_k = 1;
    hs->n = 0;
    nz_wipe(a, sizeof a);
    nz_wipe(b, sizeof b);
    nz_wipe(c, sizeof c);
}

/* AES-256-GCM with Noise's nonce (12.4): four zero bytes, then N big-endian. ENCRYPT 1 seals
 * LEN bytes of BUF in place and writes the tag after them; 0 opens them in place and checks the
 * tag at BUF + LEN (1 when it verifies). */
/* Encrypt LEN bytes of BUF in place and write its tag after them; or decrypt them in place and check
 * TAG (the 16 bytes after BUF when TAG is NULL). BUF is never written past LEN, except the tag on
 * encrypt. */
static int nz_gcm_tag(const unsigned char k[32], size_t klen, const unsigned char nonce[12], const unsigned char *aad,
                      size_t aadn, unsigned char *buf, size_t len, int encrypt, const unsigned char *tag_in) {
    br_aes_ct_ctr_keys bc;
    br_gcm_context g;
    int ok = 1;
    br_aes_ct_ctr_init(&bc, k, klen);
    br_gcm_init(&g, &bc.vtable, br_ghash_ctmul32);
    br_gcm_reset(&g, nonce, 12);
    if (aadn) {
        br_gcm_aad_inject(&g, aad, aadn);
    }
    br_gcm_flip(&g);
    if (encrypt) {
        br_gcm_run(&g, 1, buf, len);
        br_gcm_get_tag(&g, buf + len);
    } else {
        unsigned char tag[16];
        memcpy(tag, tag_in ? tag_in : buf + len, 16);
        br_gcm_run(&g, 0, buf, len);
        ok = br_gcm_check_tag(&g, tag) == 1;
        nz_wipe(tag, sizeof tag);
    }
    nz_wipe(&bc, sizeof bc);
    nz_wipe(&g, sizeof g);
    return ok;
}

static int nz_gcm(const unsigned char k[32], size_t klen, const unsigned char nonce[12], const unsigned char *aad,
                  size_t aadn, unsigned char *buf, size_t len, int encrypt) {
    return nz_gcm_tag(k, klen, nonce, aad, aadn, buf, len, encrypt, NULL);
}

static void nz_nonce(unsigned char out[12], uint64_t n) {
    memset(out, 0, 4);
    for (int i = 0; i < 8; i++) {
        out[11 - i] = (unsigned char)(n >> (8 * i));
    }
}

/* EncryptAndHash: LEN bytes of PT to OUT (LEN + 16 when there is a key). The bytes written. */
static size_t nz_encrypt_and_hash(pic_noise_hs *hs, const void *pt, size_t len, unsigned char *out) {
    unsigned char nonce[12];
    if (len) {
        memmove(out, pt, len);
    }
    if (!hs->has_k) {
        nz_mix_hash(hs, out, len);
        return len;
    }
    nz_nonce(nonce, hs->n++);
    (void)nz_gcm(hs->k, 32, nonce, hs->h, 32, out, len, 1);
    nz_mix_hash(hs, out, len + 16);
    return len + 16;
}

/* DecryptAndHash of LEN bytes of CT (its tag included when there is a key) into OUT. The
 * plaintext's length, or -1. */
static long nz_decrypt_and_hash(pic_noise_hs *hs, const unsigned char *ct, size_t len, unsigned char *out) {
    unsigned char nonce[12], h[32], tag[16];
    size_t pn;
    if (!hs->has_k) {
        memmove(out, ct, len);
        nz_mix_hash(hs, ct, len);
        return (long)len;
    }
    if (len < 16) {
        return -1;
    }
    pn = len - 16;
    memcpy(h, hs->h, 32);
    memcpy(tag, ct + pn, 16);
    nz_mix_hash(hs, ct, len); /* the hash covers the ciphertext, so take it before OUT may overwrite it */
    /* Only the plaintext's bytes go to OUT: a caller sizes OUT for the plaintext alone. */
    memmove(out, ct, pn);
    nz_nonce(nonce, hs->n);
    if (!nz_gcm_tag(hs->k, 32, nonce, h, 32, out, pn, 0, tag)) {
        nz_wipe(out, pn);
        return -1;
    }
    hs->n++;
    return (long)pn;
}

/* ---- the handshake ------------------------------------------------------------- */

void pic_noise_hs_init(pic_noise_hs *hs, int initiator, const pic_noise_keypair *s, const unsigned char *rs,
                       const unsigned char *psk, const unsigned char *prologue, size_t prologue_len) {
    const char *name = psk ? NZ_IKPSK1 : NZ_IK;
    memset(hs, 0, sizeof *hs);
    hs->initiator = initiator;
    hs->psk_mode = psk != NULL;
    memcpy(hs->h, name, strlen(name)); /* both names are shorter than 32 bytes: zero-padded (5.2) */
    memcpy(hs->ck, hs->h, 32);
    hs->s = *s;
    if (psk) {
        memcpy(hs->psk, psk, 32);
    }
    nz_mix_hash(hs, prologue, prologue_len);
    if (initiator) { /* <- s, the pre-message */
        memcpy(hs->rs, rs, PIC_NOISE_PUB);
        nz_mix_hash(hs, hs->rs, PIC_NOISE_PUB);
    } else {
        nz_mix_hash(hs, hs->s.pub, PIC_NOISE_PUB);
    }
}

int pic_noise_hs_ephemeral(pic_noise_hs *hs, const unsigned char *priv) {
    hs->fixed_e = 1;
    return pic_noise_keypair_make(&hs->e, priv);
}

/* The token e: this side's ephemeral to OUT. */
static int nz_write_e(pic_noise_hs *hs, unsigned char *out) {
    if (!hs->fixed_e && pic_noise_keypair_make(&hs->e, NULL) != 0) {
        return -1;
    }
    memcpy(out, hs->e.pub, PIC_NOISE_PUB);
    nz_mix_hash(hs, hs->e.pub, PIC_NOISE_PUB);
    if (hs->psk_mode) { /* 9.2 */
        nz_mix_key(hs, hs->e.pub, PIC_NOISE_PUB);
    }
    return 0;
}

static int nz_read_e(pic_noise_hs *hs, const unsigned char *in) {
    memcpy(hs->re, in, PIC_NOISE_PUB);
    if (!pic_noise_pub_valid(hs->re)) {
        return -1;
    }
    nz_mix_hash(hs, hs->re, PIC_NOISE_PUB);
    if (hs->psk_mode) {
        nz_mix_key(hs, hs->re, PIC_NOISE_PUB);
    }
    return 0;
}

static int nz_mix_dh(pic_noise_hs *hs, const unsigned char priv[32], const unsigned char pub[PIC_NOISE_PUB]) {
    unsigned char d[32];
    if (nz_dh(d, priv, pub) != 0) {
        return -1;
    }
    nz_mix_key(hs, d, 32);
    nz_wipe(d, sizeof d);
    return 0;
}

int pic_noise_write1(pic_noise_hs *hs, const void *payload, size_t len, unsigned char *out, size_t cap, size_t *n) {
    size_t o = PIC_NOISE_PUB;
    if (!hs->initiator || hs->step != 0 || cap < PIC_NOISE_PUB + PIC_NOISE_PUB + 16 + len + 16) {
        return -1;
    }
    if (nz_write_e(hs, out) != 0 || nz_mix_dh(hs, hs->e.priv, hs->rs) != 0) { /* e, es */
        return -1;
    }
    o += nz_encrypt_and_hash(hs, hs->s.pub, PIC_NOISE_PUB, out + o); /* s */
    if (nz_mix_dh(hs, hs->s.priv, hs->rs) != 0) {                     /* ss */
        return -1;
    }
    if (hs->psk_mode) {
        nz_mix_key_and_hash(hs, hs->psk, 32);
    }
    o += nz_encrypt_and_hash(hs, payload, len, out + o);
    hs->step = 1;
    *n = o;
    return 0;
}

int pic_noise_read1(pic_noise_hs *hs, const unsigned char *msg, size_t len, unsigned char *out, size_t cap, size_t *n) {
    unsigned char s[PIC_NOISE_PUB + 16];
    long pn;
    if (hs->initiator || hs->step != 0 || len < PIC_NOISE_PUB + PIC_NOISE_PUB + 16 + 16 ||
        cap < len - (PIC_NOISE_PUB + PIC_NOISE_PUB + 16 + 16)) {
        return -1;
    }
    if (nz_read_e(hs, msg) != 0 || nz_mix_dh(hs, hs->s.priv, hs->re) != 0) { /* e, es */
        return -1;
    }
    if (nz_decrypt_and_hash(hs, msg + PIC_NOISE_PUB, PIC_NOISE_PUB + 16, s) != PIC_NOISE_PUB) { /* s */
        return -1;
    }
    memcpy(hs->rs, s, PIC_NOISE_PUB);
    if (!pic_noise_pub_valid(hs->rs) || nz_mix_dh(hs, hs->s.priv, hs->rs) != 0) { /* ss */
        return -1;
    }
    if (hs->psk_mode) {
        nz_mix_key_and_hash(hs, hs->psk, 32);
    }
    pn = nz_decrypt_and_hash(hs, msg + PIC_NOISE_PUB + PIC_NOISE_PUB + 16, len - (PIC_NOISE_PUB + PIC_NOISE_PUB + 16), out);
    if (pn < 0) {
        return -1;
    }
    *n = (size_t)pn;
    hs->step = 1;
    return 0;
}

int pic_noise_write2(pic_noise_hs *hs, const void *payload, size_t len, unsigned char *out, size_t cap, size_t *n) {
    size_t o = PIC_NOISE_PUB;
    if (hs->initiator || hs->step != 1 || cap < PIC_NOISE_PUB + len + 16) {
        return -1;
    }
    if (nz_write_e(hs, out) != 0 || nz_mix_dh(hs, hs->e.priv, hs->re) != 0 || /* e, ee */
        nz_mix_dh(hs, hs->e.priv, hs->rs) != 0) {                             /* se */
        return -1;
    }
    o += nz_encrypt_and_hash(hs, payload, len, out + o);
    hs->step = 2;
    *n = o;
    return 0;
}

int pic_noise_read2(pic_noise_hs *hs, const unsigned char *msg, size_t len, unsigned char *out, size_t cap, size_t *n) {
    long pn;
    if (!hs->initiator || hs->step != 1 || len < PIC_NOISE_PUB + 16 || cap < len - PIC_NOISE_PUB - 16) {
        return -1;
    }
    if (nz_read_e(hs, msg) != 0 || nz_mix_dh(hs, hs->e.priv, hs->re) != 0 || /* e, ee */
        nz_mix_dh(hs, hs->s.priv, hs->re) != 0) {                            /* se */
        return -1;
    }
    pn = nz_decrypt_and_hash(hs, msg + PIC_NOISE_PUB, len - PIC_NOISE_PUB, out);
    if (pn < 0) {
        return -1;
    }
    *n = (size_t)pn;
    hs->step = 2;
    return 0;
}

void pic_noise_split(const pic_noise_hs *hs, unsigned char up[32], unsigned char down[32]) {
    nz_hkdf(hs->ck, NULL, 0, up, down, NULL);
}

void pic_noise_sas(const unsigned char h[32], char out[7]) {
    unsigned char d[32];
    uint32_t v;
    static const char label[] = "pic-rc/1 sas";
    pic_noise_hmac(d, h, 32, label, sizeof label - 1, NULL, 0);
    v = ((uint32_t)d[0] << 24) | ((uint32_t)d[1] << 16) | ((uint32_t)d[2] << 8) | (uint32_t)d[3];
    v %= 1000000u;
    for (int i = 5; i >= 0; i--) {
        out[i] = (char)('0' + v % 10);
        v /= 10;
    }
    out[6] = '\0';
}

void pic_noise_hs_wipe(pic_noise_hs *hs) { nz_wipe(hs, sizeof *hs); }

/* ---- records and the transport (section 3) ------------------------------------- */

size_t pic_noise_head(int type, const unsigned char sid[PIC_NOISE_SID], const unsigned char *msg, size_t len,
                      unsigned char *out) {
    out[0] = (unsigned char)type;
    memcpy(out + 1, sid, PIC_NOISE_SID);
    if (len) {
        memmove(out + 1 + PIC_NOISE_SID, msg, len);
    }
    return 1 + PIC_NOISE_SID + len;
}

void pic_noise_transport_init(pic_noise_transport *t, int initiator, const unsigned char sid[PIC_NOISE_SID],
                              const unsigned char up[32], const unsigned char down[32]) {
    memset(t, 0, sizeof *t);
    memcpy(t->sid, sid, PIC_NOISE_SID);
    memcpy(t->send_k, initiator ? up : down, 32);
    memcpy(t->recv_k, initiator ? down : up, 32);
    t->last = -1;
}

size_t pic_noise_record(pic_noise_transport *t, int flag, const void *data, size_t len, unsigned char *out) {
    unsigned char nonce[12];
    uint64_t n = t->send_n++;
    size_t o = 1 + PIC_NOISE_SID;
    if (len > PIC_NOISE_CHUNK) {
        len = PIC_NOISE_CHUNK;
    }
    out[0] = PIC_NOISE_REC_DATA;
    memcpy(out + 1, t->sid, PIC_NOISE_SID);
    for (int i = 0; i < 8; i++) {
        out[o + (size_t)i] = (unsigned char)(n >> (8 * (7 - i)));
    }
    o += 8;
    out[o] = (unsigned char)flag;
    if (len) {
        memcpy(out + o + 1, data, len);
    }
    nz_nonce(nonce, n);
    (void)nz_gcm(t->send_k, 32, nonce, NULL, 0, out + o, len + 1, 1);
    return o + len + 1 + 16;
}

int pic_noise_open_record(pic_noise_transport *t, const unsigned char *rec, size_t len, int *flag, unsigned char *out,
                          size_t *n, int *gap) {
    unsigned char buf[PIC_NOISE_RECORD_CAP], nonce[12];
    uint64_t c = 0;
    size_t body;
    const size_t head = 1 + PIC_NOISE_SID + 8;
    if (len < head + 1 + 16 || len > PIC_NOISE_RECORD_CAP || rec[0] != PIC_NOISE_REC_DATA ||
        memcmp(rec + 1, t->sid, PIC_NOISE_SID) != 0) {
        return -1;
    }
    for (int i = 0; i < 8; i++) {
        c = (c << 8) | rec[1 + PIC_NOISE_SID + (size_t)i];
    }
    if (c >= (1ull << 32) || (int64_t)c <= t->last) { /* past 2^32, as the page, a replay or a duplicate: dropped unread */
        return -1;
    }
    body = len - head - 16;
    memcpy(buf, rec + head, len - head);
    nz_nonce(nonce, c);
    if (!nz_gcm(t->recv_k, 32, nonce, NULL, 0, buf, body, 0)) {
        nz_wipe(buf, sizeof buf);
        return -1;
    }
    if (buf[0] > 1) {
        nz_wipe(buf, sizeof buf);
        return -1;
    }
    *gap = (int64_t)c > t->last + 1;
    t->last = (int64_t)c;
    *flag = buf[0];
    *n = body - 1;
    memcpy(out, buf + 1, body - 1);
    nz_wipe(buf, sizeof buf);
    return 0;
}

/* ---- base64url ------------------------------------------------------------------ */

static const char nz_b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

size_t pic_b64u_enc(const unsigned char *in, size_t n, char *out) {
    size_t o = 0, i = 0;
    for (; i + 3 <= n; i += 3) {
        uint32_t v = ((uint32_t)in[i] << 16) | ((uint32_t)in[i + 1] << 8) | in[i + 2];
        out[o++] = nz_b64[(v >> 18) & 63];
        out[o++] = nz_b64[(v >> 12) & 63];
        out[o++] = nz_b64[(v >> 6) & 63];
        out[o++] = nz_b64[v & 63];
    }
    if (n - i == 1) {
        uint32_t v = (uint32_t)in[i] << 16;
        out[o++] = nz_b64[(v >> 18) & 63];
        out[o++] = nz_b64[(v >> 12) & 63];
    } else if (n - i == 2) {
        uint32_t v = ((uint32_t)in[i] << 16) | ((uint32_t)in[i + 1] << 8);
        out[o++] = nz_b64[(v >> 18) & 63];
        out[o++] = nz_b64[(v >> 12) & 63];
        out[o++] = nz_b64[(v >> 6) & 63];
    }
    out[o] = '\0';
    return o;
}

static int nz_b64v(char c) {
    if (c >= 'A' && c <= 'Z') {
        return c - 'A';
    }
    if (c >= 'a' && c <= 'z') {
        return c - 'a' + 26;
    }
    if (c >= '0' && c <= '9') {
        return c - '0' + 52;
    }
    return c == '-' ? 62 : c == '_' ? 63 : -1;
}

long pic_b64u_dec(const char *in, size_t n, unsigned char *out, size_t cap) {
    size_t o = 0;
    uint32_t acc = 0;
    int bits = 0;
    if (n % 4 == 1) {
        return -1;
    }
    for (size_t i = 0; i < n; i++) {
        int v = nz_b64v(in[i]);
        if (v < 0) {
            return -1;
        }
        acc = (acc << 6) | (uint32_t)v;
        bits += 6;
        if (bits >= 8) {
            bits -= 8;
            if (o >= cap) {
                return -1;
            }
            out[o++] = (unsigned char)(acc >> bits);
        }
    }
    if (bits && (acc & ((1u << bits) - 1)) != 0) { /* leftover bits must be zero */
        return -1;
    }
    return (long)o;
}

/* ---- Web Push (section 5): VAPID and RFC 8291 --------------------------------------- */

int pic_noise_es256(const unsigned char priv[PIC_NOISE_PRIV], const char *input, unsigned char sig[64]) {
    unsigned char h[32], x[PIC_NOISE_PRIV];
    br_ec_private_key sk;
    size_t n;
    memcpy(x, priv, sizeof x);
    sk.curve = BR_EC_secp256r1;
    sk.x = x;
    sk.xlen = sizeof x;
    pic_noise_sha256(h, input, strlen(input), NULL, 0);
    n = br_ecdsa_i31_sign_raw(&br_ec_p256_m31, &br_sha256_vtable, h, &sk, sig);
    nz_wipe(x, sizeof x);
    return n == 64 ? 0 : -1;
}

size_t pic_noise_webpush(const pic_noise_keypair *as, const unsigned char salt[16], const unsigned char ua_pub[65],
                         const unsigned char auth[16], const void *pt, size_t len, unsigned char *out) {
    unsigned char ecdh[32], t[32], ikm[32], prk[32], cek[32], nk[32], info[14 + 65 + 65 + 1];
    static const char wp[] = "WebPush: info", ce[] = "Content-Encoding: aes128gcm", cn[] = "Content-Encoding: nonce";
    static const unsigned char z1[2] = {0, 1};
    size_t o = 0;
    if (nz_dh(ecdh, as->priv, ua_pub) != 0) {
        return 0;
    }
    memcpy(info, wp, sizeof wp); /* its NUL is the 0x00 */
    memcpy(info + sizeof wp, ua_pub, 65);
    memcpy(info + sizeof wp + 65, as->pub, 65);
    info[sizeof wp + 130] = 1;
    pic_noise_hmac(t, auth, 16, ecdh, 32, NULL, 0);
    pic_noise_hmac(ikm, t, 32, info, sizeof wp + 131, NULL, 0);
    pic_noise_hmac(prk, salt, 16, ikm, 32, NULL, 0);
    pic_noise_hmac(cek, prk, 32, ce, sizeof ce - 1, z1, 2);
    pic_noise_hmac(nk, prk, 32, cn, sizeof cn - 1, z1, 2);
    memcpy(out, salt, 16);
    o = 16;
    out[o++] = 0x00;
    out[o++] = 0x00;
    out[o++] = 0x10;
    out[o++] = 0x00;
    out[o++] = 65;
    memcpy(out + o, as->pub, 65);
    o += 65;
    if (len) {
        memcpy(out + o, pt, len);
    }
    out[o + len] = 0x02;
    (void)nz_gcm(cek, 16, nk, NULL, 0, out + o, len + 1, 1);
    o += len + 1 + 16;
    nz_wipe(ecdh, sizeof ecdh);
    nz_wipe(t, sizeof t);
    nz_wipe(ikm, sizeof ikm);
    nz_wipe(prk, sizeof prk);
    nz_wipe(cek, sizeof cek);
    nz_wipe(nk, sizeof nk);
    return o;
}