sodium_crypto_secretbox

sodium_crypto_secretbox(string $message, string $nonce, string $key): string

Authenticated encryption with a shared key: XSalsa20-Poly1305 produces a 16-byte MAC followed by the ciphertext; decryption returns false when the tag does not verify.

C C23

C23
#include <stdio.h>
#include <string.h>
#include <stdint.h>

// ---- Salsa20 stream cipher core (RFC 8439 section 2.3, 20 rounds) ----
static uint32_t rotl(uint32_t x, int n) { return (x << n) | (x >> (32 - n)); }

// the Salsa20 quarter round: b ^= rotl(a+d,7); c ^= rotl(b+a,9); d ^= rotl(c+b,13); a ^= rotl(d+c,18)
#define QR(a, b, c, d)          \
    do {                        \
        b ^= rotl(a + d, 7);    \
        c ^= rotl(b + a, 9);    \
        d ^= rotl(c + b, 13);   \
        a ^= rotl(d + c, 18);   \
    } while (0)

static void salsa20_rounds(uint32_t x[16]) {
    for (int i = 0; i < 10; i++) {
        // column rounds
        QR(x[0], x[4], x[8], x[12]);
        QR(x[5], x[9], x[13], x[1]);
        QR(x[10], x[14], x[2], x[6]);
        QR(x[15], x[3], x[7], x[11]);
        // row rounds
        QR(x[0], x[1], x[2], x[3]);
        QR(x[5], x[6], x[7], x[4]);
        QR(x[10], x[11], x[8], x[9]);
        QR(x[15], x[12], x[13], x[14]);
    }
}

// HSalsa20 (libsodium crypto_core_hsalsa20): 16-byte input, 32-byte subkey out
static void hsalsa20(uint8_t out[32], const uint8_t in[16], const uint8_t k[32]) {
    static const uint32_t sigma[4] = {0x61707865u, 0x3320646eu, 0x79622d32u, 0x6b206574u};
    uint32_t x[16] = {
        sigma[0],
        (uint32_t)k[0] | ((uint32_t)k[1] << 8) | ((uint32_t)k[2] << 16) | ((uint32_t)k[3] << 24),
        (uint32_t)k[4] | ((uint32_t)k[5] << 8) | ((uint32_t)k[6] << 16) | ((uint32_t)k[7] << 24),
        (uint32_t)k[8] | ((uint32_t)k[9] << 8) | ((uint32_t)k[10] << 16) | ((uint32_t)k[11] << 24),
        (uint32_t)k[12] | ((uint32_t)k[13] << 8) | ((uint32_t)k[14] << 16) | ((uint32_t)k[15] << 24),
        sigma[1],
        (uint32_t)in[0] | ((uint32_t)in[1] << 8) | ((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24),
        (uint32_t)in[4] | ((uint32_t)in[5] << 8) | ((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24),
        (uint32_t)in[8] | ((uint32_t)in[9] << 8) | ((uint32_t)in[10] << 16) | ((uint32_t)in[11] << 24),
        (uint32_t)in[12] | ((uint32_t)in[13] << 8) | ((uint32_t)in[14] << 16) | ((uint32_t)in[15] << 24),
        sigma[2],
        (uint32_t)k[16] | ((uint32_t)k[17] << 8) | ((uint32_t)k[18] << 16) | ((uint32_t)k[19] << 24),
        (uint32_t)k[20] | ((uint32_t)k[21] << 8) | ((uint32_t)k[22] << 16) | ((uint32_t)k[23] << 24),
        (uint32_t)k[24] | ((uint32_t)k[25] << 8) | ((uint32_t)k[26] << 16) | ((uint32_t)k[27] << 24),
        (uint32_t)k[28] | ((uint32_t)k[29] << 8) | ((uint32_t)k[30] << 16) | ((uint32_t)k[31] << 24),
        sigma[3]};
    salsa20_rounds(x);
    // HSalsa20 output order: the constant positions 0/5/10/15, then the input block 6/7/8/9
    static const int keep[8] = {0, 5, 10, 15, 6, 7, 8, 9};
    for (int i = 0; i < 8; i++) {
        uint32_t v = x[keep[i]];
        out[4 * i] = (uint8_t)v;
        out[4 * i + 1] = (uint8_t)(v >> 8);
        out[4 * i + 2] = (uint8_t)(v >> 16);
        out[4 * i + 3] = (uint8_t)(v >> 24);
    }
}

// Salsa20 stream xor: nonce8 = second half of the 24-byte secretbox nonce.
// State layout: key at 1-4/11-14, the 8-byte nonce at 6-7, 64-bit LE block counter at 8-9
static void salsa20_xor(uint8_t *m, size_t mlen, const uint8_t subkey[32], const uint8_t nonce8[8]) {
    static const uint32_t sigma[4] = {0x61707865u, 0x3320646eu, 0x79622d32u, 0x6b206574u};
    uint32_t st[16] = {
        sigma[0],
        (uint32_t)subkey[0] | ((uint32_t)subkey[1] << 8) | ((uint32_t)subkey[2] << 16) | ((uint32_t)subkey[3] << 24),
        (uint32_t)subkey[4] | ((uint32_t)subkey[5] << 8) | ((uint32_t)subkey[6] << 16) | ((uint32_t)subkey[7] << 24),
        (uint32_t)subkey[8] | ((uint32_t)subkey[9] << 8) | ((uint32_t)subkey[10] << 16) | ((uint32_t)subkey[11] << 24),
        (uint32_t)subkey[12] | ((uint32_t)subkey[13] << 8) | ((uint32_t)subkey[14] << 16) | ((uint32_t)subkey[15] << 24),
        sigma[1],
        (uint32_t)nonce8[0] | ((uint32_t)nonce8[1] << 8) | ((uint32_t)nonce8[2] << 16) | ((uint32_t)nonce8[3] << 24),
        (uint32_t)nonce8[4] | ((uint32_t)nonce8[5] << 8) | ((uint32_t)nonce8[6] << 16) | ((uint32_t)nonce8[7] << 24),
        0, 0, // 64-bit little-endian block counter, starts at 0
        sigma[2],
        (uint32_t)subkey[16] | ((uint32_t)subkey[17] << 8) | ((uint32_t)subkey[18] << 16) | ((uint32_t)subkey[19] << 24),
        (uint32_t)subkey[20] | ((uint32_t)subkey[21] << 8) | ((uint32_t)subkey[22] << 16) | ((uint32_t)subkey[23] << 24),
        (uint32_t)subkey[24] | ((uint32_t)subkey[25] << 8) | ((uint32_t)subkey[26] << 16) | ((uint32_t)subkey[27] << 24),
        (uint32_t)subkey[28] | ((uint32_t)subkey[29] << 8) | ((uint32_t)subkey[30] << 16) | ((uint32_t)subkey[31] << 24),
        sigma[3]};
    for (size_t off = 0; off < mlen; off += 64) {
        uint32_t x[16];
        memcpy(x, st, sizeof x);
        salsa20_rounds(x);
        uint8_t ks[64];
        for (int i = 0; i < 16; i++) {
            uint32_t v = x[i] + st[i]; // Salsa20 adds the input state back; HSalsa20 does not
            ks[4 * i] = (uint8_t)v;
            ks[4 * i + 1] = (uint8_t)(v >> 8);
            ks[4 * i + 2] = (uint8_t)(v >> 16);
            ks[4 * i + 3] = (uint8_t)(v >> 24);
        }
        size_t n = mlen - off < 64 ? mlen - off : 64;
        for (size_t i = 0; i < n; i++) m[off + i] ^= ks[i];
        // increment the 64-bit little-endian block counter
        uint64_t ctr = (uint64_t)st[8] | ((uint64_t)st[9] << 32);
        ctr++;
        st[8] = (uint32_t)ctr;
        st[9] = (uint32_t)(ctr >> 32);
    }
}

// ---- Poly1305 one-time authenticator (RFC 8439 section 2.5, donna-32) ----
static uint32_t u8to32(const uint8_t *p) {
    return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}

static void poly1305_auth(uint8_t out[16], const uint8_t *m, size_t inlen, const uint8_t k[32]) {
    uint32_t r0, r1, r2, r3, r4, s1, s2, s3, s4;
    uint32_t h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0;
    uint64_t d0, d1, d2, d3, d4;
    uint64_t c;
    // r = first half of the key, clamped
    r0 = u8to32(&k[0]) & 0x3ffffff;
    r1 = (u8to32(&k[3]) >> 2) & 0x3ffff03;
    r2 = (u8to32(&k[6]) >> 4) & 0x3ffc0ff;
    r3 = (u8to32(&k[9]) >> 6) & 0x3f03fff;
    r4 = (u8to32(&k[12]) >> 8) & 0x00fffff;
    s1 = r1 * 5;
    s2 = r2 * 5;
    s3 = r3 * 5;
    s4 = r4 * 5;
    while (inlen > 0) {
        size_t n = inlen < 16 ? inlen : 16;
        uint8_t block[17] = {0};
        memcpy(block, m, n);
        block[n] = 1; // the implicit high bit of each 17-byte block
        h0 += u8to32(&block[0]) & 0x3ffffff;
        h1 += (u8to32(&block[3]) >> 2) & 0x3ffffff;
        h2 += (u8to32(&block[6]) >> 4) & 0x3ffffff;
        h3 += (u8to32(&block[9]) >> 6) & 0x3ffffff;
        h4 += (u8to32(&block[12]) >> 8) | ((uint32_t)block[16] << 24);
        d0 = (uint64_t)h0 * r0 + (uint64_t)h1 * s4 + (uint64_t)h2 * s3 + (uint64_t)h3 * s2 + (uint64_t)h4 * s1;
        d1 = (uint64_t)h0 * r1 + (uint64_t)h1 * r0 + (uint64_t)h2 * s4 + (uint64_t)h3 * s3 + (uint64_t)h4 * s2;
        d2 = (uint64_t)h0 * r2 + (uint64_t)h1 * r1 + (uint64_t)h2 * r0 + (uint64_t)h3 * s4 + (uint64_t)h4 * s3;
        d3 = (uint64_t)h0 * r3 + (uint64_t)h1 * r2 + (uint64_t)h2 * r1 + (uint64_t)h3 * r0 + (uint64_t)h4 * s4;
        d4 = (uint64_t)h0 * r4 + (uint64_t)h1 * r3 + (uint64_t)h2 * r2 + (uint64_t)h3 * r1 + (uint64_t)h4 * r0;
        c = d0 >> 26;
        h0 = (uint32_t)d0 & 0x3ffffff;
        d1 += c;
        c = d1 >> 26;
        h1 = (uint32_t)d1 & 0x3ffffff;
        d2 += c;
        c = d2 >> 26;
        h2 = (uint32_t)d2 & 0x3ffffff;
        d3 += c;
        c = d3 >> 26;
        h3 = (uint32_t)d3 & 0x3ffffff;
        d4 += c;
        c = d4 >> 26;
        h4 = (uint32_t)d4 & 0x3ffffff;
        h0 += (uint32_t)c * 5;
        c = h0 >> 26;
        h0 &= 0x3ffffff;
        h1 += (uint32_t)c;
        m += n;
        inlen -= n;
    }
    // full carry and reduction modulo 2^130 - 5
    c = h1 >> 26;
    h1 &= 0x3ffffff;
    h2 += (uint32_t)c;
    c = h2 >> 26;
    h2 &= 0x3ffffff;
    h3 += (uint32_t)c;
    c = h3 >> 26;
    h3 &= 0x3ffffff;
    h4 += (uint32_t)c;
    c = h4 >> 26;
    h4 &= 0x3ffffff;
    h0 += (uint32_t)c * 5;
    c = h0 >> 26;
    h0 &= 0x3ffffff;
    h1 += (uint32_t)c;
    // select h + 5 - 2^130 when h >= p, otherwise h
    uint32_t g0 = h0 + 5;
    c = g0 >> 26;
    g0 &= 0x3ffffff;
    uint32_t g1 = h1 + (uint32_t)c;
    c = g1 >> 26;
    g1 &= 0x3ffffff;
    uint32_t g2 = h2 + (uint32_t)c;
    c = g2 >> 26;
    g2 &= 0x3ffffff;
    uint32_t g3 = h3 + (uint32_t)c;
    c = g3 >> 26;
    g3 &= 0x3ffffff;
    uint32_t g4 = h4 + (uint32_t)c - (1UL << 26);
    uint32_t mask = (g4 >> 31) - 1; // borrow -> h was below p, keep h
    g0 &= mask;
    g1 &= mask;
    g2 &= mask;
    g3 &= mask;
    g4 &= mask;
    mask = ~mask;
    h0 = (h0 & mask) | g0;
    h1 = (h1 & mask) | g1;
    h2 = (h2 & mask) | g2;
    h3 = (h3 & mask) | g3;
    h4 = (h4 & mask) | g4;
    // h mod 2^128
    h0 = (h0 | (h1 << 26)) & 0xffffffff;
    h1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffff;
    h2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffff;
    h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffff;
    // h + s (second half of the key), with 32-bit carries
    uint64_t f = (uint64_t)h0 + u8to32(&k[16]);
    h0 = (uint32_t)f;
    f = (uint64_t)h1 + u8to32(&k[20]) + (f >> 32);
    h1 = (uint32_t)f;
    f = (uint64_t)h2 + u8to32(&k[24]) + (f >> 32);
    h2 = (uint32_t)f;
    f = (uint64_t)h3 + u8to32(&k[28]) + (f >> 32);
    h3 = (uint32_t)f;
    out[0] = (uint8_t)h0;
    out[1] = (uint8_t)(h0 >> 8);
    out[2] = (uint8_t)(h0 >> 16);
    out[3] = (uint8_t)(h0 >> 24);
    out[4] = (uint8_t)h1;
    out[5] = (uint8_t)(h1 >> 8);
    out[6] = (uint8_t)(h1 >> 16);
    out[7] = (uint8_t)(h1 >> 24);
    out[8] = (uint8_t)h2;
    out[9] = (uint8_t)(h2 >> 8);
    out[10] = (uint8_t)(h2 >> 16);
    out[11] = (uint8_t)(h2 >> 24);
    out[12] = (uint8_t)h3;
    out[13] = (uint8_t)(h3 >> 8);
    out[14] = (uint8_t)(h3 >> 16);
    out[15] = (uint8_t)(h3 >> 24);
}

// ---- secretbox = XSalsa20 stream xor + Poly1305 tag over the ciphertext ----
// The first 32 keystream bytes are consumed as the one-time Poly1305 key,
// so the message is encrypted with the keystream starting at byte 32.
// Output layout follows sodium_crypto_secretbox: 16-byte MAC || ciphertext
static void secretbox(uint8_t *out, const uint8_t *msg, size_t mlen, const uint8_t nonce[24], const uint8_t key[32]) {
    uint8_t subkey[32], ks[32 + 256], polykey[32], tag[16];
    hsalsa20(subkey, nonce, key);
    memset(ks, 0, sizeof ks);
    salsa20_xor(ks, 32 + 256, subkey, nonce + 16); // xor into zeros = raw keystream from counter 0
    memcpy(polykey, ks, 32);                       // one-time Poly1305 key
    for (size_t i = 0; i < mlen; i++) out[16 + i] = msg[i] ^ ks[32 + i];
    poly1305_auth(tag, out + 16, mlen, polykey);
    memcpy(out, tag, 16);
}

// returns 0 on success, -1 when the tag does not verify
static int secretbox_open(uint8_t *out, const uint8_t *box, size_t boxlen, const uint8_t nonce[24], const uint8_t key[32]) {
    if (boxlen < 16) return -1;
    uint8_t subkey[32], ks[32 + 256], polykey[32], tag[16];
    size_t mlen = boxlen - 16;
    hsalsa20(subkey, nonce, key);
    memset(ks, 0, sizeof ks);
    salsa20_xor(ks, 32 + 256, subkey, nonce + 16);
    memcpy(polykey, ks, 32);
    poly1305_auth(tag, box + 16, mlen, polykey);
    uint8_t diff = 0; // constant-time tag compare
    for (int i = 0; i < 16; i++) diff |= tag[i] ^ box[i];
    if (diff != 0) return -1;
    for (size_t i = 0; i < mlen; i++) out[i] = box[16 + i] ^ ks[32 + i];
    return 0;
}

static int hexval(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    return c - 'A' + 10;
}

int main(void) {
    const char *keyhex = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
    const char *noncehex = "000102030405060708090a0b0c0d0e0f1011121314151617";
    const char *msg = "attack at dawn";
    uint8_t key[32], nonce[24], out[256], opened[256];
    for (int i = 0; i < 32; i++) key[i] = (uint8_t)(hexval(keyhex[2 * i]) * 16 + hexval(keyhex[2 * i + 1]));
    for (int i = 0; i < 24; i++) nonce[i] = (uint8_t)(hexval(noncehex[2 * i]) * 16 + hexval(noncehex[2 * i + 1]));
    size_t mlen = strlen(msg);
    secretbox(out, (const uint8_t *)msg, mlen, nonce, key);
    printf("box: ");
    for (size_t i = 0; i < mlen + 16; i++) printf("%02x", out[i]);
    printf("\n");
    printf("roundtrip: %s\n", secretbox_open(opened, out, mlen + 16, nonce, key) == 0 ? "true" : "false");
    out[16] ^= 1; // flip one ciphertext bit (past the 16-byte MAC)
    printf("tampered open: %s\n", secretbox_open(opened, out, mlen + 16, nonce, key) == 0 ? "true" : "false");
    return 0;
}
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include <cstdint>

// ---- Salsa20 stream cipher core (RFC 8439 section 2.3, 20 rounds) ----
static uint32_t rotl(uint32_t x, int n) { return (x << n) | (x >> (32 - n)); }

// the Salsa20 quarter round: b ^= rotl(a+d,7); c ^= rotl(b+a,9); d ^= rotl(c+b,13); a ^= rotl(d+c,18)
#define QR(a, b, c, d)          \
    do {                        \
        b ^= rotl(a + d, 7);    \
        c ^= rotl(b + a, 9);    \
        d ^= rotl(c + b, 13);   \
        a ^= rotl(d + c, 18);   \
    } while (0)

static void salsa20_rounds(uint32_t x[16]) {
    for (int i = 0; i < 10; i++) {
        // column rounds
        QR(x[0], x[4], x[8], x[12]);
        QR(x[5], x[9], x[13], x[1]);
        QR(x[10], x[14], x[2], x[6]);
        QR(x[15], x[3], x[7], x[11]);
        // row rounds
        QR(x[0], x[1], x[2], x[3]);
        QR(x[5], x[6], x[7], x[4]);
        QR(x[10], x[11], x[8], x[9]);
        QR(x[15], x[12], x[13], x[14]);
    }
}

// HSalsa20 (libsodium crypto_core_hsalsa20): 16-byte input, 32-byte subkey out
static void hsalsa20(uint8_t out[32], const uint8_t in[16], const uint8_t k[32]) {
    static const uint32_t sigma[4] = {0x61707865u, 0x3320646eu, 0x79622d32u, 0x6b206574u};
    uint32_t x[16] = {
        sigma[0],
        (uint32_t)k[0] | ((uint32_t)k[1] << 8) | ((uint32_t)k[2] << 16) | ((uint32_t)k[3] << 24),
        (uint32_t)k[4] | ((uint32_t)k[5] << 8) | ((uint32_t)k[6] << 16) | ((uint32_t)k[7] << 24),
        (uint32_t)k[8] | ((uint32_t)k[9] << 8) | ((uint32_t)k[10] << 16) | ((uint32_t)k[11] << 24),
        (uint32_t)k[12] | ((uint32_t)k[13] << 8) | ((uint32_t)k[14] << 16) | ((uint32_t)k[15] << 24),
        sigma[1],
        (uint32_t)in[0] | ((uint32_t)in[1] << 8) | ((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24),
        (uint32_t)in[4] | ((uint32_t)in[5] << 8) | ((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24),
        (uint32_t)in[8] | ((uint32_t)in[9] << 8) | ((uint32_t)in[10] << 16) | ((uint32_t)in[11] << 24),
        (uint32_t)in[12] | ((uint32_t)in[13] << 8) | ((uint32_t)in[14] << 16) | ((uint32_t)in[15] << 24),
        sigma[2],
        (uint32_t)k[16] | ((uint32_t)k[17] << 8) | ((uint32_t)k[18] << 16) | ((uint32_t)k[19] << 24),
        (uint32_t)k[20] | ((uint32_t)k[21] << 8) | ((uint32_t)k[22] << 16) | ((uint32_t)k[23] << 24),
        (uint32_t)k[24] | ((uint32_t)k[25] << 8) | ((uint32_t)k[26] << 16) | ((uint32_t)k[27] << 24),
        (uint32_t)k[28] | ((uint32_t)k[29] << 8) | ((uint32_t)k[30] << 16) | ((uint32_t)k[31] << 24),
        sigma[3]};
    salsa20_rounds(x);
    // HSalsa20 output order: the constant positions 0/5/10/15, then the input block 6/7/8/9
    static const int keep[8] = {0, 5, 10, 15, 6, 7, 8, 9};
    for (int i = 0; i < 8; i++) {
        uint32_t v = x[keep[i]];
        out[4 * i] = (uint8_t)v;
        out[4 * i + 1] = (uint8_t)(v >> 8);
        out[4 * i + 2] = (uint8_t)(v >> 16);
        out[4 * i + 3] = (uint8_t)(v >> 24);
    }
}

// Salsa20 stream xor: nonce8 = second half of the 24-byte secretbox nonce.
// State layout: key at 1-4/11-14, the 8-byte nonce at 6-7, 64-bit LE block counter at 8-9
static void salsa20_xor(uint8_t *m, size_t mlen, const uint8_t subkey[32], const uint8_t nonce8[8]) {
    static const uint32_t sigma[4] = {0x61707865u, 0x3320646eu, 0x79622d32u, 0x6b206574u};
    uint32_t st[16] = {
        sigma[0],
        (uint32_t)subkey[0] | ((uint32_t)subkey[1] << 8) | ((uint32_t)subkey[2] << 16) | ((uint32_t)subkey[3] << 24),
        (uint32_t)subkey[4] | ((uint32_t)subkey[5] << 8) | ((uint32_t)subkey[6] << 16) | ((uint32_t)subkey[7] << 24),
        (uint32_t)subkey[8] | ((uint32_t)subkey[9] << 8) | ((uint32_t)subkey[10] << 16) | ((uint32_t)subkey[11] << 24),
        (uint32_t)subkey[12] | ((uint32_t)subkey[13] << 8) | ((uint32_t)subkey[14] << 16) | ((uint32_t)subkey[15] << 24),
        sigma[1],
        (uint32_t)nonce8[0] | ((uint32_t)nonce8[1] << 8) | ((uint32_t)nonce8[2] << 16) | ((uint32_t)nonce8[3] << 24),
        (uint32_t)nonce8[4] | ((uint32_t)nonce8[5] << 8) | ((uint32_t)nonce8[6] << 16) | ((uint32_t)nonce8[7] << 24),
        0, 0, // 64-bit little-endian block counter, starts at 0
        sigma[2],
        (uint32_t)subkey[16] | ((uint32_t)subkey[17] << 8) | ((uint32_t)subkey[18] << 16) | ((uint32_t)subkey[19] << 24),
        (uint32_t)subkey[20] | ((uint32_t)subkey[21] << 8) | ((uint32_t)subkey[22] << 16) | ((uint32_t)subkey[23] << 24),
        (uint32_t)subkey[24] | ((uint32_t)subkey[25] << 8) | ((uint32_t)subkey[26] << 16) | ((uint32_t)subkey[27] << 24),
        (uint32_t)subkey[28] | ((uint32_t)subkey[29] << 8) | ((uint32_t)subkey[30] << 16) | ((uint32_t)subkey[31] << 24),
        sigma[3]};
    for (size_t off = 0; off < mlen; off += 64) {
        uint32_t x[16];
        memcpy(x, st, sizeof x);
        salsa20_rounds(x);
        uint8_t ks[64];
        for (int i = 0; i < 16; i++) {
            uint32_t v = x[i] + st[i]; // Salsa20 adds the input state back; HSalsa20 does not
            ks[4 * i] = (uint8_t)v;
            ks[4 * i + 1] = (uint8_t)(v >> 8);
            ks[4 * i + 2] = (uint8_t)(v >> 16);
            ks[4 * i + 3] = (uint8_t)(v >> 24);
        }
        size_t n = mlen - off < 64 ? mlen - off : 64;
        for (size_t i = 0; i < n; i++) m[off + i] ^= ks[i];
        // increment the 64-bit little-endian block counter
        uint64_t ctr = (uint64_t)st[8] | ((uint64_t)st[9] << 32);
        ctr++;
        st[8] = (uint32_t)ctr;
        st[9] = (uint32_t)(ctr >> 32);
    }
}

// ---- Poly1305 one-time authenticator (RFC 8439 section 2.5, donna-32) ----
static uint32_t u8to32(const uint8_t *p) {
    return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}

static void poly1305_auth(uint8_t out[16], const uint8_t *m, size_t inlen, const uint8_t k[32]) {
    uint32_t r0, r1, r2, r3, r4, s1, s2, s3, s4;
    uint32_t h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0;
    uint64_t d0, d1, d2, d3, d4;
    uint64_t c;
    // r = first half of the key, clamped
    r0 = u8to32(&k[0]) & 0x3ffffff;
    r1 = (u8to32(&k[3]) >> 2) & 0x3ffff03;
    r2 = (u8to32(&k[6]) >> 4) & 0x3ffc0ff;
    r3 = (u8to32(&k[9]) >> 6) & 0x3f03fff;
    r4 = (u8to32(&k[12]) >> 8) & 0x00fffff;
    s1 = r1 * 5;
    s2 = r2 * 5;
    s3 = r3 * 5;
    s4 = r4 * 5;
    while (inlen > 0) {
        size_t n = inlen < 16 ? inlen : 16;
        uint8_t block[17] = {0};
        memcpy(block, m, n);
        block[n] = 1; // the implicit high bit of each 17-byte block
        h0 += u8to32(&block[0]) & 0x3ffffff;
        h1 += (u8to32(&block[3]) >> 2) & 0x3ffffff;
        h2 += (u8to32(&block[6]) >> 4) & 0x3ffffff;
        h3 += (u8to32(&block[9]) >> 6) & 0x3ffffff;
        h4 += (u8to32(&block[12]) >> 8) | ((uint32_t)block[16] << 24);
        d0 = (uint64_t)h0 * r0 + (uint64_t)h1 * s4 + (uint64_t)h2 * s3 + (uint64_t)h3 * s2 + (uint64_t)h4 * s1;
        d1 = (uint64_t)h0 * r1 + (uint64_t)h1 * r0 + (uint64_t)h2 * s4 + (uint64_t)h3 * s3 + (uint64_t)h4 * s2;
        d2 = (uint64_t)h0 * r2 + (uint64_t)h1 * r1 + (uint64_t)h2 * r0 + (uint64_t)h3 * s4 + (uint64_t)h4 * s3;
        d3 = (uint64_t)h0 * r3 + (uint64_t)h1 * r2 + (uint64_t)h2 * r1 + (uint64_t)h3 * r0 + (uint64_t)h4 * s4;
        d4 = (uint64_t)h0 * r4 + (uint64_t)h1 * r3 + (uint64_t)h2 * r2 + (uint64_t)h3 * r1 + (uint64_t)h4 * r0;
        c = d0 >> 26;
        h0 = (uint32_t)d0 & 0x3ffffff;
        d1 += c;
        c = d1 >> 26;
        h1 = (uint32_t)d1 & 0x3ffffff;
        d2 += c;
        c = d2 >> 26;
        h2 = (uint32_t)d2 & 0x3ffffff;
        d3 += c;
        c = d3 >> 26;
        h3 = (uint32_t)d3 & 0x3ffffff;
        d4 += c;
        c = d4 >> 26;
        h4 = (uint32_t)d4 & 0x3ffffff;
        h0 += (uint32_t)c * 5;
        c = h0 >> 26;
        h0 &= 0x3ffffff;
        h1 += (uint32_t)c;
        m += n;
        inlen -= n;
    }
    // full carry and reduction modulo 2^130 - 5
    c = h1 >> 26;
    h1 &= 0x3ffffff;
    h2 += (uint32_t)c;
    c = h2 >> 26;
    h2 &= 0x3ffffff;
    h3 += (uint32_t)c;
    c = h3 >> 26;
    h3 &= 0x3ffffff;
    h4 += (uint32_t)c;
    c = h4 >> 26;
    h4 &= 0x3ffffff;
    h0 += (uint32_t)c * 5;
    c = h0 >> 26;
    h0 &= 0x3ffffff;
    h1 += (uint32_t)c;
    // select h + 5 - 2^130 when h >= p, otherwise h
    uint32_t g0 = h0 + 5;
    c = g0 >> 26;
    g0 &= 0x3ffffff;
    uint32_t g1 = h1 + (uint32_t)c;
    c = g1 >> 26;
    g1 &= 0x3ffffff;
    uint32_t g2 = h2 + (uint32_t)c;
    c = g2 >> 26;
    g2 &= 0x3ffffff;
    uint32_t g3 = h3 + (uint32_t)c;
    c = g3 >> 26;
    g3 &= 0x3ffffff;
    uint32_t g4 = h4 + (uint32_t)c - (1UL << 26);
    uint32_t mask = (g4 >> 31) - 1; // borrow -> h was below p, keep h
    g0 &= mask;
    g1 &= mask;
    g2 &= mask;
    g3 &= mask;
    g4 &= mask;
    mask = ~mask;
    h0 = (h0 & mask) | g0;
    h1 = (h1 & mask) | g1;
    h2 = (h2 & mask) | g2;
    h3 = (h3 & mask) | g3;
    h4 = (h4 & mask) | g4;
    // h mod 2^128
    h0 = (h0 | (h1 << 26)) & 0xffffffff;
    h1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffff;
    h2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffff;
    h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffff;
    // h + s (second half of the key), with 32-bit carries
    uint64_t f = (uint64_t)h0 + u8to32(&k[16]);
    h0 = (uint32_t)f;
    f = (uint64_t)h1 + u8to32(&k[20]) + (f >> 32);
    h1 = (uint32_t)f;
    f = (uint64_t)h2 + u8to32(&k[24]) + (f >> 32);
    h2 = (uint32_t)f;
    f = (uint64_t)h3 + u8to32(&k[28]) + (f >> 32);
    h3 = (uint32_t)f;
    out[0] = (uint8_t)h0;
    out[1] = (uint8_t)(h0 >> 8);
    out[2] = (uint8_t)(h0 >> 16);
    out[3] = (uint8_t)(h0 >> 24);
    out[4] = (uint8_t)h1;
    out[5] = (uint8_t)(h1 >> 8);
    out[6] = (uint8_t)(h1 >> 16);
    out[7] = (uint8_t)(h1 >> 24);
    out[8] = (uint8_t)h2;
    out[9] = (uint8_t)(h2 >> 8);
    out[10] = (uint8_t)(h2 >> 16);
    out[11] = (uint8_t)(h2 >> 24);
    out[12] = (uint8_t)h3;
    out[13] = (uint8_t)(h3 >> 8);
    out[14] = (uint8_t)(h3 >> 16);
    out[15] = (uint8_t)(h3 >> 24);
}

// ---- secretbox = XSalsa20 stream xor + Poly1305 tag over the ciphertext ----
// The first 32 keystream bytes are consumed as the one-time Poly1305 key,
// so the message is encrypted with the keystream starting at byte 32.
// Output layout follows sodium_crypto_secretbox: 16-byte MAC || ciphertext
static void secretbox(uint8_t *out, const uint8_t *msg, size_t mlen, const uint8_t nonce[24], const uint8_t key[32]) {
    uint8_t subkey[32], ks[32 + 256], polykey[32], tag[16];
    hsalsa20(subkey, nonce, key);
    memset(ks, 0, sizeof ks);
    salsa20_xor(ks, 32 + 256, subkey, nonce + 16); // xor into zeros = raw keystream from counter 0
    memcpy(polykey, ks, 32);                       // one-time Poly1305 key
    for (size_t i = 0; i < mlen; i++) out[16 + i] = msg[i] ^ ks[32 + i];
    poly1305_auth(tag, out + 16, mlen, polykey);
    memcpy(out, tag, 16);
}

// returns 0 on success, -1 when the tag does not verify
static int secretbox_open(uint8_t *out, const uint8_t *box, size_t boxlen, const uint8_t nonce[24], const uint8_t key[32]) {
    if (boxlen < 16) return -1;
    uint8_t subkey[32], ks[32 + 256], polykey[32], tag[16];
    size_t mlen = boxlen - 16;
    hsalsa20(subkey, nonce, key);
    memset(ks, 0, sizeof ks);
    salsa20_xor(ks, 32 + 256, subkey, nonce + 16);
    memcpy(polykey, ks, 32);
    poly1305_auth(tag, box + 16, mlen, polykey);
    uint8_t diff = 0; // constant-time tag compare
    for (int i = 0; i < 16; i++) diff |= tag[i] ^ box[i];
    if (diff != 0) return -1;
    for (size_t i = 0; i < mlen; i++) out[i] = box[16 + i] ^ ks[32 + i];
    return 0;
}

static int hexval(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    return c - 'A' + 10;
}

int main() {
    const char *keyhex = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
    const char *noncehex = "000102030405060708090a0b0c0d0e0f1011121314151617";
    const char *msg = "attack at dawn";
    uint8_t key[32], nonce[24], out[256], opened[256];
    for (int i = 0; i < 32; i++) key[i] = (uint8_t)(hexval(keyhex[2 * i]) * 16 + hexval(keyhex[2 * i + 1]));
    for (int i = 0; i < 24; i++) nonce[i] = (uint8_t)(hexval(noncehex[2 * i]) * 16 + hexval(noncehex[2 * i + 1]));
    size_t mlen = strlen(msg);
    secretbox(out, (const uint8_t *)msg, mlen, nonce, key);
    printf("box: ");
    for (size_t i = 0; i < mlen + 16; i++) printf("%02x", out[i]);
    printf("\n");
    printf("roundtrip: %s\n", secretbox_open(opened, out, mlen + 16, nonce, key) == 0 ? "true" : "false");
    out[16] ^= 1; // flip one ciphertext bit (past the 16-byte MAC)
    printf("tampered open: %s\n", secretbox_open(opened, out, mlen + 16, nonce, key) == 0 ? "true" : "false");
    return 0;
}
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

C# v11.0.100

v11.0.100
using System;
using System.Linq;

// XSalsa20-Poly1305 (libsodium secretbox) written out in plain C#, teaching style.
// NSec/libsodium bindings are the production route; this shows the internals.
static class SecretBox {
    static uint Rotl(uint x, int n) => (x << n) | (x >> (32 - n));

    static void Qr(uint[] x, int a, int b, int c, int d) {
        x[b] ^= Rotl(x[a] + x[d], 7);
        x[c] ^= Rotl(x[b] + x[a], 9);
        x[d] ^= Rotl(x[c] + x[b], 13);
        x[a] ^= Rotl(x[d] + x[c], 18);
    }

    static void Salsa20Rounds(uint[] x) {
        for (int i = 0; i < 10; i++) {
            Qr(x, 0, 4, 8, 12);
            Qr(x, 5, 9, 13, 1);
            Qr(x, 10, 14, 2, 6);
            Qr(x, 15, 3, 7, 11);
            Qr(x, 0, 1, 2, 3);
            Qr(x, 5, 6, 7, 4);
            Qr(x, 10, 11, 8, 9);
            Qr(x, 15, 12, 13, 14);
        }
    }

    static readonly uint[] Sigma = { 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 };

    static uint[] WordsLE(byte[] buf, int off, int len) {
        var outw = new uint[len / 4];
        for (int i = 0; i < outw.Length; i++)
            outw[i] = BitConverter.ToUInt32(buf, off + 4 * i);
        return outw;
    }

    static byte[] HSalSa20(byte[] n16, byte[] k32) {
        var kw = WordsLE(k32, 0, 32);
        var nw = WordsLE(n16, 0, 16);
        var x = new uint[] { Sigma[0], kw[0], kw[1], kw[2], kw[3], Sigma[1], nw[0], nw[1], nw[2], nw[3], Sigma[2], kw[4], kw[5], kw[6], kw[7], Sigma[3] };
        Salsa20Rounds(x);
        // HSalsa20 keeps the words at the constant positions and the input block
        return BitConverter.GetBytes(x[0]).Concat(BitConverter.GetBytes(x[5])).Concat(BitConverter.GetBytes(x[10])).Concat(BitConverter.GetBytes(x[15]))
            .Concat(BitConverter.GetBytes(x[6])).Concat(BitConverter.GetBytes(x[7])).Concat(BitConverter.GetBytes(x[8])).Concat(BitConverter.GetBytes(x[9])).ToArray();
    }

    static byte[] Salsa20Stream(byte[] subkey, byte[] n8, int n) {
        var kw = WordsLE(subkey, 0, 32);
        var nw = WordsLE(n8, 0, 8);
        var outp = new byte[n];
        ulong counter = 0; // 64-bit little-endian block counter at state words 8-9
        for (int off = 0; off < n; off += 64) {
            var st = new uint[] { Sigma[0], kw[0], kw[1], kw[2], kw[3], Sigma[1], nw[0], nw[1], (uint)counter, (uint)(counter >> 32), Sigma[2], kw[4], kw[5], kw[6], kw[7], Sigma[3] };
            var x = (uint[])st.Clone();
            Salsa20Rounds(x);
            // Salsa20 adds the input state back; HSalsa20 does not
            var block = new byte[64];
            for (int i = 0; i < 16; i++) {
                BitConverter.GetBytes(x[i] + st[i]).CopyTo(block, 4 * i);
            }
            Array.Copy(block, 0, outp, off, Math.Min(64, n - off));
            counter++;
        }
        return outp;
    }

    static uint U32(byte[] b, int off) => BitConverter.ToUInt32(b, off);

    static byte[] Poly1305(byte[] msg, byte[] key) {
        // donna-32 style: five 26-bit limbs, 64-bit products
        ulong r0 = U32(key, 0) & 0x3ffffffUL;
        ulong r1 = (U32(key, 3) >> 2) & 0x3ffff03UL;
        ulong r2 = (U32(key, 6) >> 4) & 0x3ffc0ffUL;
        ulong r3 = (U32(key, 9) >> 6) & 0x3f03fffUL;
        ulong r4 = (U32(key, 12) >> 8) & 0x00fffffUL;
        ulong s1 = r1 * 5, s2 = r2 * 5, s3 = r3 * 5, s4 = r4 * 5;
        ulong h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        for (int off = 0; off < msg.Length; off += 16) {
            int n = Math.Min(16, msg.Length - off);
            var block = new byte[17];
            Array.Copy(msg, off, block, 0, n);
            block[n] = 1; // the implicit high bit of each 17-byte block
            h0 += U32(block, 0) & 0x3ffffffUL;
            h1 += (U32(block, 3) >> 2) & 0x3ffffffUL;
            h2 += (U32(block, 6) >> 4) & 0x3ffffffUL;
            h3 += (U32(block, 9) >> 6) & 0x3ffffffUL;
            h4 += (U32(block, 12) >> 8) | ((ulong)block[16] << 24);
            ulong d0 = h0 * r0 + h1 * s4 + h2 * s3 + h3 * s2 + h4 * s1;
            ulong d1 = h0 * r1 + h1 * r0 + h2 * s4 + h3 * s3 + h4 * s2;
            ulong d2 = h0 * r2 + h1 * r1 + h2 * r0 + h3 * s4 + h4 * s3;
            ulong d3 = h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * s4;
            ulong d4 = h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
            ulong c = d0 >> 26; h0 = d0 & 0x3ffffffUL;
            ulong e1 = d1 + c; c = e1 >> 26; h1 = e1 & 0x3ffffffUL;
            ulong e2 = d2 + c; c = e2 >> 26; h2 = e2 & 0x3ffffffUL;
            ulong e3 = d3 + c; c = e3 >> 26; h3 = e3 & 0x3ffffffUL;
            ulong e4 = d4 + c; c = e4 >> 26; h4 = e4 & 0x3ffffffUL;
            h0 += c * 5; c = h0 >> 26; h0 &= 0x3ffffffUL;
            h1 += c;
        }
        // full carry and reduction modulo 2^130 - 5
        ulong cc = h1 >> 26; h1 &= 0x3ffffffUL; h2 += cc;
        cc = h2 >> 26; h2 &= 0x3ffffffUL; h3 += cc;
        cc = h3 >> 26; h3 &= 0x3ffffffUL; h4 += cc;
        cc = h4 >> 26; h4 &= 0x3ffffffUL; h0 += cc * 5;
        cc = h0 >> 26; h0 &= 0x3ffffffUL; h1 += cc;
        // select h + 5 - 2^130 when h >= p, otherwise h
        ulong g0 = h0 + 5; cc = g0 >> 26; g0 &= 0x3ffffffUL;
        ulong g1 = h1 + cc; cc = g1 >> 26; g1 &= 0x3ffffffUL;
        ulong g2 = h2 + cc; cc = g2 >> 26; g2 &= 0x3ffffffUL;
        ulong g3 = h3 + cc; cc = g3 >> 26; g3 &= 0x3ffffffUL;
        ulong g4 = h4 + cc - (1UL << 26);
        // if g4 underflowed (its bit 31 would be set in 32-bit arithmetic), h was below p: keep h
        ulong mask = ((long)g4 >> 31 & 1) == 1 ? 0UL : ulong.MaxValue;
        g0 &= mask; g1 &= mask; g2 &= mask; g3 &= mask; g4 &= mask;
        mask = ~mask;
        h0 = (h0 & mask) | g0; h1 = (h1 & mask) | g1; h2 = (h2 & mask) | g2;
        h3 = (h3 & mask) | g3; h4 = (h4 & mask) | g4;
        // h mod 2^128
        ulong w0 = h0 | (h1 << 26);
        ulong w1 = (h1 >> 6) | (h2 << 20);
        ulong w2 = (h2 >> 12) | (h3 << 14);
        ulong w3 = (h3 >> 18) | (h4 << 8);
        // h + s (second half of the key), with 32-bit carries
        ulong f = (w0 & 0xffffffffUL) + U32(key, 16);
        w0 = f & 0xffffffffUL;
        f = (w1 & 0xffffffffUL) + U32(key, 20) + (f >> 32);
        w1 = f & 0xffffffffUL;
        f = (w2 & 0xffffffffUL) + U32(key, 24) + (f >> 32);
        w2 = f & 0xffffffffUL;
        f = (w3 & 0xffffffffUL) + U32(key, 28) + (f >> 32);
        w3 = f & 0xffffffffUL;
        var outp = new byte[16];
        BitConverter.GetBytes((uint)w0).CopyTo(outp, 0);
        BitConverter.GetBytes((uint)w1).CopyTo(outp, 4);
        BitConverter.GetBytes((uint)w2).CopyTo(outp, 8);
        BitConverter.GetBytes((uint)w3).CopyTo(outp, 12);
        return outp;
    }

    public static byte[] Seal(byte[] msg, byte[] nonce, byte[] key) {
        var subkey = HSalSa20(nonce.Take(16).ToArray(), key);
        // first 32 keystream bytes = one-time Poly1305 key; message starts at byte 32
        var ks = Salsa20Stream(subkey, nonce.Skip(16).Take(8).ToArray(), 32 + msg.Length);
        var ct = new byte[msg.Length];
        for (int i = 0; i < msg.Length; i++) ct[i] = (byte)(msg[i] ^ ks[32 + i]);
        var tag = Poly1305(ct, ks.Take(32).ToArray());
        return tag.Concat(ct).ToArray(); // sodium layout: MAC(16) || ciphertext
    }

    public static byte[] Open(byte[] box, byte[] nonce, byte[] key) {
        var tag = box.Take(16).ToArray();
        var ct = box.Skip(16).ToArray();
        var subkey = HSalSa20(nonce.Take(16).ToArray(), key);
        var ks = Salsa20Stream(subkey, nonce.Skip(16).Take(8).ToArray(), 32 + ct.Length);
        var expect = Poly1305(ct, ks.Take(32).ToArray());
        int diff = 0; // constant-time tag compare
        for (int i = 0; i < 16; i++) diff |= expect[i] ^ tag[i];
        if (diff != 0) return null;
        var outp = new byte[ct.Length];
        for (int i = 0; i < ct.Length; i++) outp[i] = (byte)(ct[i] ^ ks[32 + i]);
        return outp;
    }
}

class Program {
    static void Main() {
        byte[] key = Enumerable.Range(0, 32).Select(i => (byte)i).ToArray();
        byte[] nonce = Enumerable.Range(0, 24).Select(i => (byte)i).ToArray();
        byte[] msg = System.Text.Encoding.ASCII.GetBytes("attack at dawn");
        byte[] box = SecretBox.Seal(msg, nonce, key);
        Console.WriteLine($"box: {Convert.ToHexString(box).ToLower()}");
        var opened = SecretBox.Open(box, nonce, key);
        bool ok = opened != null && System.Text.Encoding.ASCII.GetString(opened) == "attack at dawn";
Console.WriteLine($"roundtrip: {(ok ? "true" : "false")}");
        box[16] ^= 1;
        Console.WriteLine($"tampered open: {(SecretBox.Open(box, nonce, key) != null ? "true" : "false")}");
    }
}
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"encoding/hex"
	"fmt"

	"golang.org/x/crypto/nacl/secretbox" // the XSalsa20-Poly1305 secretbox, same as libsodium
)

func main() {
	key := new([32]byte) // fixed demo key (production: random key, keep it secret)
	for i := range key {
		key[i] = byte(i)
	}
	var nonce [24]byte // fixed demo nonce (production: random nonce, never reuse per key)
	for i := range nonce {
		nonce[i] = byte(i)
	}
	msg := []byte("attack at dawn")
	box := secretbox.Seal(nil, msg, &nonce, key)
	fmt.Println("box:", hex.EncodeToString(box)) // layout: 16-byte MAC || ciphertext
	opened, ok := secretbox.Open(nil, box, &nonce, key)
	fmt.Println("roundtrip:", ok && bytes.Equal(opened, msg))
	bad := bytes.Clone(box)
	bad[16] ^= 1 // flip one ciphertext bit (past the 16-byte MAC)
	_, ok = secretbox.Open(nil, bad, &nonce, key)
	fmt.Println("tampered open:", ok)
}
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

Java v27.0.1

v27.0.1
import java.util.HexFormat;

// XSalsa20-Poly1305 (libsodium secretbox) written out in plain Java, teaching style.
// lazysodium/NSec-style libsodium bindings are the production route; this shows the internals.
public class Main {
    static int rotl(int x, int n) {
        return (x << n) | (x >>> (32 - n));
    }

    static void qr(int[] x, int a, int b, int c, int d) {
        x[b] ^= rotl(x[a] + x[d], 7);
        x[c] ^= rotl(x[b] + x[a], 9);
        x[d] ^= rotl(x[c] + x[b], 13);
        x[a] ^= rotl(x[d] + x[c], 18);
    }

    static void salsa20Rounds(int[] x) {
        for (int i = 0; i < 10; i++) {
            qr(x, 0, 4, 8, 12);
            qr(x, 5, 9, 13, 1);
            qr(x, 10, 14, 2, 6);
            qr(x, 15, 3, 7, 11);
            qr(x, 0, 1, 2, 3);
            qr(x, 5, 6, 7, 4);
            qr(x, 10, 11, 8, 9);
            qr(x, 15, 12, 13, 14);
        }
    }

    static final int[] SIGMA = {0x61707865, 0x3320646e, 0x79622d32, 0x6b206574};

    static int[] wordsLE(byte[] buf, int off, int len) {
        int[] out = new int[len / 4];
        for (int i = 0; i < out.length; i++) {
            out[i] = (buf[off + 4 * i] & 0xff) | ((buf[off + 4 * i + 1] & 0xff) << 8)
                    | ((buf[off + 4 * i + 2] & 0xff) << 16) | ((buf[off + 4 * i + 3] & 0xff) << 24);
        }
        return out;
    }

    static byte[] hsalsa20(byte[] n16, byte[] k32) {
        int[] kw = wordsLE(k32, 0, 32);
        int[] nw = wordsLE(n16, 0, 16);
        int[] x = {SIGMA[0], kw[0], kw[1], kw[2], kw[3], SIGMA[1], nw[0], nw[1], nw[2], nw[3], SIGMA[2], kw[4], kw[5], kw[6], kw[7], SIGMA[3]};
        salsa20Rounds(x);
        // HSalsa20 keeps the words at the constant positions and the input block
        byte[] out = new byte[32];
        int[] keep = {x[0], x[5], x[10], x[15], x[6], x[7], x[8], x[9]};
        for (int i = 0; i < 8; i++) {
            out[4 * i] = (byte) keep[i];
            out[4 * i + 1] = (byte) (keep[i] >> 8);
            out[4 * i + 2] = (byte) (keep[i] >> 16);
            out[4 * i + 3] = (byte) (keep[i] >> 24);
        }
        return out;
    }

    static byte[] salsa20Stream(byte[] subkey, byte[] n8, int n) {
        int[] kw = wordsLE(subkey, 0, 32);
        int[] nw = wordsLE(n8, 0, 8);
        byte[] out = new byte[n];
        long counter = 0; // 64-bit little-endian block counter at state words 8-9
        for (int off = 0; off < n; off += 64) {
            int[] st = {SIGMA[0], kw[0], kw[1], kw[2], kw[3], SIGMA[1], nw[0], nw[1],
                    (int) counter, (int) (counter >>> 32), SIGMA[2], kw[4], kw[5], kw[6], kw[7], SIGMA[3]};
            int[] x = st.clone();
            salsa20Rounds(x);
            // Salsa20 adds the input state back; HSalsa20 does not
            byte[] block = new byte[64];
            for (int i = 0; i < 16; i++) {
                int v = x[i] + st[i];
                block[4 * i] = (byte) v;
                block[4 * i + 1] = (byte) (v >> 8);
                block[4 * i + 2] = (byte) (v >> 16);
                block[4 * i + 3] = (byte) (v >> 24);
            }
            System.arraycopy(block, 0, out, off, Math.min(64, n - off));
            counter++;
        }
        return out;
    }

    static byte[] poly1305(byte[] msg, byte[] key) {
        // donna-32 style: five 26-bit limbs, 64-bit products fit in Java long
        long r0 = (u32(key, 0)) & 0x3ffffffL;
        long r1 = (u32(key, 3) >>> 2) & 0x3ffff03L;
        long r2 = (u32(key, 6) >>> 4) & 0x3ffc0ffL;
        long r3 = (u32(key, 9) >>> 6) & 0x3f03fffL;
        long r4 = (u32(key, 12) >>> 8) & 0x00fffffL;
        long s1 = r1 * 5, s2 = r2 * 5, s3 = r3 * 5, s4 = r4 * 5;
        long h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        for (int off = 0; off < msg.length; off += 16) {
            int n = Math.min(16, msg.length - off);
            byte[] block = new byte[17];
            System.arraycopy(msg, off, block, 0, n);
            block[n] = 1; // the implicit high bit of each 17-byte block
            h0 += (u32(block, 0)) & 0x3ffffffL;
            h1 += (u32(block, 3) >>> 2) & 0x3ffffffL;
            h2 += (u32(block, 6) >>> 4) & 0x3ffffffL;
            h3 += (u32(block, 9) >>> 6) & 0x3ffffffL;
            h4 += (u32(block, 12) >>> 8) | ((long) block[16] << 24);
            long d0 = h0 * r0 + h1 * s4 + h2 * s3 + h3 * s2 + h4 * s1;
            long d1 = h0 * r1 + h1 * r0 + h2 * s4 + h3 * s3 + h4 * s2;
            long d2 = h0 * r2 + h1 * r1 + h2 * r0 + h3 * s4 + h4 * s3;
            long d3 = h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * s4;
            long d4 = h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
            long c = d0 >>> 26; h0 = d0 & 0x3ffffffL;
            long e1 = d1 + c; c = e1 >>> 26; h1 = e1 & 0x3ffffffL;
            long e2 = d2 + c; c = e2 >>> 26; h2 = e2 & 0x3ffffffL;
            long e3 = d3 + c; c = e3 >>> 26; h3 = e3 & 0x3ffffffL;
            long e4 = d4 + c; c = e4 >>> 26; h4 = e4 & 0x3ffffffL;
            h0 += c * 5; c = h0 >>> 26; h0 &= 0x3ffffffL;
            h1 += c;
        }
        // full carry and reduction modulo 2^130 - 5
        long c = h1 >>> 26; h1 &= 0x3ffffffL; h2 += c;
        c = h2 >>> 26; h2 &= 0x3ffffffL; h3 += c;
        c = h3 >>> 26; h3 &= 0x3ffffffL; h4 += c;
        c = h4 >>> 26; h4 &= 0x3ffffffL; h0 += c * 5;
        c = h0 >>> 26; h0 &= 0x3ffffffL; h1 += c;
        // select h + 5 - 2^130 when h >= p, otherwise h
        long g0 = h0 + 5; c = g0 >>> 26; g0 &= 0x3ffffffL;
        long g1 = h1 + c; c = g1 >>> 26; g1 &= 0x3ffffffL;
        long g2 = h2 + c; c = g2 >>> 26; g2 &= 0x3ffffffL;
        long g3 = h3 + c; c = g3 >>> 26; g3 &= 0x3ffffffL;
        long g4 = h4 + c - (1L << 26);
        long mask = ((int) g4 >>> 31) - 1; // borrow -> h was below p, keep h (C uint32 semantics)
        g0 &= mask; g1 &= mask; g2 &= mask; g3 &= mask; g4 &= mask;
        mask = ~mask;
        h0 = (h0 & mask) | g0; h1 = (h1 & mask) | g1; h2 = (h2 & mask) | g2;
        h3 = (h3 & mask) | g3; h4 = (h4 & mask) | g4;
        // h mod 2^128
        long w0 = h0 | (h1 << 26);
        long w1 = (h1 >>> 6) | (h2 << 20);
        long w2 = (h2 >>> 12) | (h3 << 14);
        long w3 = (h3 >>> 18) | (h4 << 8);
        // h + s (second half of the key), with 32-bit carries
        long f = (w0 & 0xffffffffL) + u32(key, 16);
        w0 = f & 0xffffffffL;
        f = (w1 & 0xffffffffL) + u32(key, 20) + (f >>> 32);
        w1 = f & 0xffffffffL;
        f = (w2 & 0xffffffffL) + u32(key, 24) + (f >>> 32);
        w2 = f & 0xffffffffL;
        f = (w3 & 0xffffffffL) + u32(key, 28) + (f >>> 32);
        w3 = f & 0xffffffffL;
        byte[] out = new byte[16];
        for (int i = 0; i < 4; i++) {
            long v = switch (i) {
                case 0 -> w0; case 1 -> w1; case 2 -> w2; default -> w3;
            };
            out[4 * i] = (byte) v;
            out[4 * i + 1] = (byte) (v >> 8);
            out[4 * i + 2] = (byte) (v >> 16);
            out[4 * i + 3] = (byte) (v >> 24);
        }
        return out;
    }

    static long u32(byte[] b, int off) {
        return ((b[off] & 0xffL) | ((b[off + 1] & 0xffL) << 8)
                | ((b[off + 2] & 0xffL) << 16) | ((b[off + 3] & 0xffL) << 24));
    }

    static byte[] secretbox(byte[] msg, byte[] nonce, byte[] key) {
        byte[] subkey = hsalsa20(slice(nonce, 0, 16), key);
        // first 32 keystream bytes = one-time Poly1305 key; message starts at byte 32
        byte[] ks = salsa20Stream(subkey, slice(nonce, 16, 8), 32 + msg.length);
        byte[] ct = new byte[msg.length];
        for (int i = 0; i < msg.length; i++) ct[i] = (byte) (msg[i] ^ ks[32 + i]);
        byte[] tag = poly1305(ct, slice(ks, 0, 32));
        byte[] out = new byte[16 + msg.length];
        System.arraycopy(tag, 0, out, 0, 16);
        System.arraycopy(ct, 0, out, 16, msg.length);
        return out; // sodium layout: MAC(16) || ciphertext
    }

    static byte[] secretboxOpen(byte[] box, byte[] nonce, byte[] key) {
        byte[] tag = slice(box, 0, 16);
        byte[] ct = slice(box, 16, box.length - 16);
        byte[] subkey = hsalsa20(slice(nonce, 0, 16), key);
        byte[] ks = salsa20Stream(subkey, slice(nonce, 16, 8), 32 + ct.length);
        byte[] expect = poly1305(ct, slice(ks, 0, 32));
        int diff = 0; // constant-time tag compare
        for (int i = 0; i < 16; i++) diff |= expect[i] ^ tag[i];
        if (diff != 0) return null;
        byte[] out = new byte[ct.length];
        for (int i = 0; i < ct.length; i++) out[i] = (byte) (ct[i] ^ ks[32 + i]);
        return out;
    }

    static byte[] slice(byte[] b, int off, int len) {
        byte[] out = new byte[len];
        System.arraycopy(b, off, out, 0, len);
        return out;
    }

    public static void main(String[] args) {
        byte[] key = new byte[32];
        for (int i = 0; i < 32; i++) key[i] = (byte) i;
        byte[] nonce = new byte[24];
        for (int i = 0; i < 24; i++) nonce[i] = (byte) i;
        byte[] msg = "attack at dawn".getBytes();
        byte[] box = secretbox(msg, nonce, key);
        System.out.println("box: " + HexFormat.of().formatHex(box));
        byte[] opened = secretboxOpen(box, nonce, key);
        System.out.println("roundtrip: " + (opened != null && new String(opened).equals("attack at dawn")));
        box[16] ^= 1;
        System.out.println("tampered open: " + (secretboxOpen(box, nonce, key) != null));
    }
}
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

JavaScript v26.13.1

v26.13.1
// XSalsa20-Poly1305 (libsodium secretbox) in plain JS, teaching style.
// libsodium.js is the production binding; this shows the internals.

function rotl(x, n) {
  return ((x << n) | (x >>> (32 - n))) >>> 0;
}

function qr(x, a, b, c, d) {
  x[b] ^= rotl((x[a] + x[d]) >>> 0, 7);
  x[c] ^= rotl((x[b] + x[a]) >>> 0, 9);
  x[d] ^= rotl((x[c] + x[b]) >>> 0, 13);
  x[a] ^= rotl((x[d] + x[c]) >>> 0, 18);
}

function salsa20Rounds(x) {
  for (let i = 0; i < 10; i++) {
    qr(x, 0, 4, 8, 12);
    qr(x, 5, 9, 13, 1);
    qr(x, 10, 14, 2, 6);
    qr(x, 15, 3, 7, 11);
    qr(x, 0, 1, 2, 3);
    qr(x, 5, 6, 7, 4);
    qr(x, 10, 11, 8, 9);
    qr(x, 15, 12, 13, 14);
  }
}

const SIGMA = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574];

function wordsLE(buf) {
  const out = new Array(buf.length / 4);
  for (let i = 0; i < out.length; i++) out[i] = buf.readUInt32LE(i * 4);
  return out;
}

function packWords(words) {
  const out = Buffer.alloc(words.length * 4);
  words.forEach((w, i) => out.writeUInt32LE(w >>> 0, i * 4));
  return out;
}

function hsalsa20(n16, k32) {
  const kw = wordsLE(k32);
  const nw = wordsLE(n16);
  const x = [SIGMA[0], kw[0], kw[1], kw[2], kw[3], SIGMA[1], nw[0], nw[1], nw[2], nw[3], SIGMA[2], kw[4], kw[5], kw[6], kw[7], SIGMA[3]];
  salsa20Rounds(x);
  // HSalsa20 keeps the words at the constant positions and the input block
  return packWords([x[0], x[5], x[10], x[15], x[6], x[7], x[8], x[9]]);
}

function salsa20Stream(subkey, n8, n) {
  const kw = wordsLE(subkey);
  const nw = wordsLE(n8);
  const out = Buffer.alloc(n);
  let counter = 0n; // 64-bit little-endian block counter at state words 8-9
  for (let off = 0; off < n; off += 64) {
    const st = [SIGMA[0], kw[0], kw[1], kw[2], kw[3], SIGMA[1], nw[0], nw[1], Number(counter & 0xffffffffn), Number((counter >> 32n) & 0xffffffffn), SIGMA[2], kw[4], kw[5], kw[6], kw[7], SIGMA[3]];
    const x = [...st];
    salsa20Rounds(x);
    // Salsa20 adds the input state back; HSalsa20 does not
    const block = packWords(x.map((v, i) => (v + st[i]) >>> 0));
    block.copy(out, off, 0, Math.min(64, n - off));
    counter += 1n;
  }
  return out;
}

function poly1305(msg, key) {
  // JS numbers only have 53-bit precision: the 130-bit accumulator needs BigInt.
  // Same math as the C reference implementation, one block at a time.
  const le = (buf) => {
    let v = 0n;
    for (let i = buf.length - 1; i >= 0; i--) v = (v << 8n) | BigInt(buf[i]);
    return v;
  };
  const r = le(key.subarray(0, 16)) & 0x0ffffffc0ffffffc0ffffffc0fffffffn; // clamped
  const s = le(key.subarray(16));
  const p = (1n << 130n) - 5n;
  let acc = 0n;
  for (let off = 0; off < msg.length; off += 16) {
    const block = msg.subarray(off, off + 16);
    const n = le(block) + (1n << BigInt(8 * block.length)); // the implicit high bit
    acc = ((acc + n) * r) % p;
  }
  return Buffer.from(((acc + s) % (1n << 128n)).toString(16).padStart(32, "0"), "hex").reverse();
}

function secretbox(msg, nonce, key) {
  const subkey = hsalsa20(nonce.subarray(0, 16), key);
  // first 32 keystream bytes = one-time Poly1305 key; message starts at byte 32
  const ks = salsa20Stream(subkey, nonce.subarray(16), 32 + msg.length);
  const ct = Buffer.from(msg);
  for (let i = 0; i < ct.length; i++) ct[i] ^= ks[32 + i];
  return Buffer.concat([poly1305(ct, ks.subarray(0, 32)), ct]); // sodium layout: MAC(16) || ciphertext
}

function secretboxOpen(box, nonce, key) {
  const tag = box.subarray(0, 16);
  const ct = box.subarray(16);
  const subkey = hsalsa20(nonce.subarray(0, 16), key);
  const ks = salsa20Stream(subkey, nonce.subarray(16), 32 + ct.length);
  if (!poly1305(ct, ks.subarray(0, 32)).equals(tag)) return null;
  const out = Buffer.from(ct);
  for (let i = 0; i < out.length; i++) out[i] ^= ks[32 + i];
  return out;
}

const key = Buffer.from(Array.from({ length: 32 }, (_, i) => i));
const nonce = Buffer.from(Array.from({ length: 24 }, (_, i) => i));
const msg = Buffer.from("attack at dawn");
const box = secretbox(msg, nonce, key);
console.log("box:", box.toString("hex"));
console.log("roundtrip:", secretboxOpen(box, nonce, key).equals(msg));
const bad = Buffer.from(box);
bad[16] ^= 1;
console.log("tampered open:", secretboxOpen(bad, nonce, key) !== null);
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

PHP v8.6.0

v8.6.0
// sodium_crypto_secretbox: XSalsa20-Poly1305 authenticated encryption.
// Fixed key/nonce make the output deterministic for comparison across languages.
$key   = hex2bin("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); // 32-byte shared key (demo only)
$nonce = hex2bin("000102030405060708090a0b0c0d0e0f1011121314151617"); // 24-byte nonce: never reuse with the same key
$msg   = "attack at dawn";
$box   = sodium_crypto_secretbox($msg, $nonce, $key);
echo "box: ", bin2hex($box), "\n"; // sodium layout: 16-byte MAC || ciphertext
$open  = sodium_crypto_secretbox_open($box, $nonce, $key);
echo "roundtrip: ", var_export($open === $msg, true), "\n";
$box[16] = chr(ord($box[16]) ^ 1); // flip one ciphertext bit
echo "tampered open: ", var_export(sodium_crypto_secretbox_open($box, $nonce, $key) !== false, true), "\n";
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

Python v3.15.2

v3.15.2
import struct

# XSalsa20-Poly1305 (libsodium secretbox) in pure python, teaching style.
# PyNaCl (libsodium binding) is the production one-liner; this shows the internals.

def _rotl(x, n):
    return ((x << n) | (x >> (32 - n))) & 0xFFFFFFFF

def _qr(x, a, b, c, d):
    x[b] ^= _rotl((x[a] + x[d]) & 0xFFFFFFFF, 7)
    x[c] ^= _rotl((x[b] + x[a]) & 0xFFFFFFFF, 9)
    x[d] ^= _rotl((x[c] + x[b]) & 0xFFFFFFFF, 13)
    x[a] ^= _rotl((x[d] + x[c]) & 0xFFFFFFFF, 18)

def _salsa20_rounds(x):
    for _ in range(10):
        _qr(x, 0, 4, 8, 12)
        _qr(x, 5, 9, 13, 1)
        _qr(x, 10, 14, 2, 6)
        _qr(x, 15, 3, 7, 11)
        _qr(x, 0, 1, 2, 3)
        _qr(x, 5, 6, 7, 4)
        _qr(x, 10, 11, 8, 9)
        _qr(x, 15, 12, 13, 14)

def hsalsa20(n16, k32):
    c = struct.unpack("<4I", b"expand 32-byte k")
    kw = struct.unpack("<8I", k32)
    x = [c[0], *kw[:4], c[1],
         *struct.unpack("<4I", n16),
         c[2], *kw[4:], c[3]]
    _salsa20_rounds(x)
    return struct.pack("<8I", x[0], x[5], x[10], x[15], x[6], x[7], x[8], x[9])

def salsa20_stream(subkey, n8, n):
    # keystream bytes: 64-bit LE counter at state words 8-9, 8-byte nonce at 6-7
    c = struct.unpack("<4I", b"expand 32-byte k")
    kw = struct.unpack("<8I", subkey)
    nw = struct.unpack("<2I", n8)
    out = bytearray()
    counter = 0
    while len(out) < n:
        x = [c[0], *kw[:4], c[1], nw[0], nw[1],
             counter & 0xFFFFFFFF, (counter >> 32) & 0xFFFFFFFF,
             c[2], *kw[4:], c[3]]
        _salsa20_rounds(x)
        init = [c[0], *kw[:4], c[1], nw[0], nw[1],
                counter & 0xFFFFFFFF, (counter >> 32) & 0xFFFFFFFF,
                c[2], *kw[4:], c[3]]
        out += struct.pack("<16I", *[(a + b) & 0xFFFFFFFF for a, b in zip(x, init)])
        counter += 1
    return bytes(out)

def poly1305(msg, key):
    r = int.from_bytes(key[:16], "little") & 0x0ffffffc0ffffffc0ffffffc0fffffff
    s = int.from_bytes(key[16:], "little")
    p = (1 << 130) - 5
    acc = 0
    for off in range(0, len(msg), 16):
        block = msg[off:off + 16]
        n = int.from_bytes(block, "little") + (1 << (8 * len(block)))
        acc = ((acc + n) * r) % p
    return ((acc + s) % (1 << 128)).to_bytes(16, "little")

def secretbox(msg, nonce, key):
    subkey = hsalsa20(nonce[:16], key)
    ks = salsa20_stream(subkey, nonce[16:], 32 + len(msg))
    ct = bytes(m ^ k for m, k in zip(msg, ks[32:]))
    return poly1305(ct, ks[:32]) + ct  # sodium layout: MAC(16) || ciphertext

def secretbox_open(box, nonce, key):
    tag, ct = box[:16], box[16:]
    subkey = hsalsa20(nonce[:16], key)
    ks = salsa20_stream(subkey, nonce[16:], 32 + len(ct))
    if poly1305(ct, ks[:32]) != tag:
        return None
    return bytes(c ^ k for c, k in zip(ct, ks[32:]))

key = bytes(range(32))
nonce = bytes(range(24))
msg = b"attack at dawn"
box = secretbox(msg, nonce, key)
print("box:", box.hex())
print("roundtrip:", "true" if secretbox_open(box, nonce, key) == msg else "false")
bad = bytearray(box)
bad[16] ^= 1
print("tampered open:", "true" if secretbox_open(bytes(bad), nonce, key) is not None else "false")
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

Rust v1.99.1

v1.99.1
use crypto_secretbox::aead::Aead;
use crypto_secretbox::{KeyInit, XSalsa20Poly1305};

// crypto_secretbox (RustCrypto): the same XSalsa20-Poly1305 secretbox as libsodium.
// Its Aead layout matches sodium_crypto_secretbox byte for byte (verified against PHP).
fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{:02x}", x)).collect()
}

fn main() {
    let key = [0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];
    let nonce_bytes = [0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
    let cipher = XSalsa20Poly1305::new_from_slice(&key).unwrap();
    let nonce = crypto_secretbox::Nonce::from_slice(&nonce_bytes);
    let msg = b"attack at dawn";
    let boxx = cipher.encrypt(nonce, msg.as_slice()).unwrap();
    println!("box: {}", hex(&boxx));
    let opened = cipher.decrypt(nonce, boxx.as_slice()).unwrap();
    println!("roundtrip: {}", opened == msg);
    let mut bad = boxx.clone();
    bad[16] ^= 1; // flip one ciphertext bit
    println!("tampered open: {}", cipher.decrypt(nonce, bad.as_slice()).is_ok());
}
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

TypeScript v26.13.1

v26.13.1
// XSalsa20-Poly1305 (libsodium secretbox) in plain TypeScript, teaching style.
// libsodium.js is the production binding; this shows the internals.
function rotl(x: number, n: number): number {
  return ((x << n) | (x >>> (32 - n))) >>> 0;
}

function qr(x: number[], a: number, b: number, c: number, d: number): void {
  x[b] ^= rotl((x[a] + x[d]) >>> 0, 7);
  x[c] ^= rotl((x[b] + x[a]) >>> 0, 9);
  x[d] ^= rotl((x[c] + x[b]) >>> 0, 13);
  x[a] ^= rotl((x[d] + x[c]) >>> 0, 18);
}

function salsa20Rounds(x: number[]): void {
  for (let i = 0; i < 10; i++) {
    qr(x, 0, 4, 8, 12);
    qr(x, 5, 9, 13, 1);
    qr(x, 10, 14, 2, 6);
    qr(x, 15, 3, 7, 11);
    qr(x, 0, 1, 2, 3);
    qr(x, 5, 6, 7, 4);
    qr(x, 10, 11, 8, 9);
    qr(x, 15, 12, 13, 14);
  }
}

const SIGMA: number[] = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574];

function wordsLE(buf: Buffer): number[] {
  const out: number[] = new Array(buf.length / 4);
  for (let i = 0; i < out.length; i++) out[i] = buf.readUInt32LE(i * 4);
  return out;
}

function packWords(words: number[]): Buffer {
  const out = Buffer.alloc(words.length * 4);
  words.forEach((w, i) => out.writeUInt32LE(w >>> 0, i * 4));
  return out;
}

function hsalsa20(n16: Buffer, k32: Buffer): Buffer {
  const kw = wordsLE(k32);
  const nw = wordsLE(n16);
  const x: number[] = [SIGMA[0], kw[0], kw[1], kw[2], kw[3], SIGMA[1], nw[0], nw[1], nw[2], nw[3], SIGMA[2], kw[4], kw[5], kw[6], kw[7], SIGMA[3]];
  salsa20Rounds(x);
  // HSalsa20 keeps the words at the constant positions and the input block
  return packWords([x[0], x[5], x[10], x[15], x[6], x[7], x[8], x[9]]);
}

function salsa20Stream(subkey: Buffer, n8: Buffer, n: number): Buffer {
  const kw = wordsLE(subkey);
  const nw = wordsLE(n8);
  const out = Buffer.alloc(n);
  let counter = 0n; // 64-bit little-endian block counter at state words 8-9
  for (let off = 0; off < n; off += 64) {
    const st: number[] = [SIGMA[0], kw[0], kw[1], kw[2], kw[3], SIGMA[1], nw[0], nw[1], Number(counter & 0xffffffffn), Number((counter >> 32n) & 0xffffffffn), SIGMA[2], kw[4], kw[5], kw[6], kw[7], SIGMA[3]];
    const x = [...st];
    salsa20Rounds(x);
    // Salsa20 adds the input state back; HSalsa20 does not
    const block = packWords(x.map((v, i) => (v + st[i]) >>> 0));
    block.copy(out, off, 0, Math.min(64, n - off));
    counter += 1n;
  }
  return out;
}

function poly1305(msg: Buffer, key: Buffer): Buffer {
  // JS numbers only have 53-bit precision: the 130-bit accumulator needs BigInt.
  const le = (buf: Buffer): bigint => {
    let v = 0n;
    for (let i = buf.length - 1; i >= 0; i--) v = (v << 8n) | BigInt(buf[i]);
    return v;
  };
  const r = le(key.subarray(0, 16)) & 0x0ffffffc0ffffffc0ffffffc0fffffffn; // clamped
  const s = le(key.subarray(16));
  const p = (1n << 130n) - 5n;
  let acc = 0n;
  for (let off = 0; off < msg.length; off += 16) {
    const block = msg.subarray(off, off + 16);
    const n = le(block) + (1n << BigInt(8 * block.length)); // the implicit high bit
    acc = ((acc + n) * r) % p;
  }
  return Buffer.from(((acc + s) % (1n << 128n)).toString(16).padStart(32, "0"), "hex").reverse();
}

function secretbox(msg: Buffer, nonce: Buffer, key: Buffer): Buffer {
  const subkey = hsalsa20(nonce.subarray(0, 16), key);
  // first 32 keystream bytes = one-time Poly1305 key; message starts at byte 32
  const ks = salsa20Stream(subkey, nonce.subarray(16), 32 + msg.length);
  const ct = Buffer.from(msg);
  for (let i = 0; i < ct.length; i++) ct[i] ^= ks[32 + i];
  return Buffer.concat([poly1305(ct, ks.subarray(0, 32)), ct]); // sodium layout: MAC(16) || ciphertext
}

function secretboxOpen(box: Buffer, nonce: Buffer, key: Buffer): Buffer | null {
  const tag = box.subarray(0, 16);
  const ct = box.subarray(16);
  const subkey = hsalsa20(nonce.subarray(0, 16), key);
  const ks = salsa20Stream(subkey, nonce.subarray(16), 32 + ct.length);
  if (!poly1305(ct, ks.subarray(0, 32)).equals(tag)) return null;
  const out = Buffer.from(ct);
  for (let i = 0; i < out.length; i++) out[i] ^= ks[32 + i];
  return out;
}

const key = Buffer.from(Array.from({ length: 32 }, (_, i) => i));
const nonce = Buffer.from(Array.from({ length: 24 }, (_, i) => i));
const msg = Buffer.from("attack at dawn");
const box = secretbox(msg, nonce, key);
console.log("box:", box.toString("hex"));
console.log("roundtrip:", secretboxOpen(box, nonce, key)?.equals(msg));
const bad = Buffer.from(box);
bad[16] ^= 1;
console.log("tampered open:", secretboxOpen(bad, nonce, key) !== null);
Output
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1
roundtrip: true
tampered open: false

Language differences

Batch special: the classic sodium/openssl functions run at full strength on CI's libsodium 1.0.18 — all four entries are real-function demos with deterministic preset output, unlike the restricted forms of the earlier PHP 8.6 additions.

C: no crypto in the standard library — the example hand-writes XSalsa20-Poly1305 (byte-identical to libsodium); real code links libsodium crypto_secretbox_easy or OpenSSL.

C++: same hand-rolled approach as C; real work uses libsodium or NSec (libsodium binding).

C#: no XSalsa20 in the BCL — the example hand-writes the same construction (byte-identical to libsodium); real code uses NSec SecretBox (libsodium binding).

Go: golang.org/x/crypto/nacl/secretbox shares lineage with libsodium, ciphertext matches byte for byte.

Java: no XSalsa20 in the JDK — the example hand-writes it; real code uses lazysodium (libsodium binding).

JavaScript: no XSalsa20 in the Node standard library — the example is plain JS (Poly1305 uses BigInt for the 130-bit accumulator); production uses libsodium.js.

PHP: sodium_crypto_secretbox returns 16-byte MAC || ciphertext (NOT ciphertext || MAC!); the nonce is 24 bytes and must never repeat under the same key — reuse is a two-time-pad disaster.

Python: no symmetric AEAD in the standard library — the example is pure Python; production uses PyNaCl SecretBox (libsodium binding).

Rust: the crypto_secretbox crate (RustCrypto) matches sodium_crypto_secretbox byte for byte (verified); encrypt/decrypt in one call.

TypeScript: same as JavaScript. The two routes — libsodium bindings (PyNaCl/libsodium.js/lazysodium/NSec) vs standard-library equivalents (Go nacl/x/crypto, Rust crypto_secretbox, hand-rolled) — interoperate: with a fixed key/nonce/message the ciphertext is byte-identical.