Streaming AEAD

sodium_crypto_secretstream_xchacha20poly1305_init_push / push / pull

Streaming AEAD for large files: one 24-byte header plus per-chunk push/pull, each chunk carrying a tag (MESSAGE/FINAL/PUSH/REKEY), state evolving with the ciphertext — tamper any chunk and the stream dies. The counterpart to one-shot secretbox.

C C23

C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" /* vendored SHA-256 stands in for the XChaCha20-Poly1305 chunk cipher */

/* sodium_crypto_secretstream teaching stand-in: a stateful chunked AEAD.
   Real one: XChaCha20-Poly1305 per chunk, counter nonce, tag byte, rekey.
   Here: SHA-256 state chain + XOR per chunk. NOT secure. */

static BYTE STATE[32];

static void ss_init(const BYTE key[32], const BYTE header[24]) {
    SHA256_CTX ctx;
    sha256_init(&ctx);
    sha256_update(&ctx, key, 32);
    sha256_update(&ctx, header, 24);
    sha256_final(&ctx, STATE);
}

static size_t ss_push(const char *msg, size_t mlen, int tag, BYTE out[64]) {
    SHA256_CTX ctx;
    BYTE mask[SHA256_BLOCK_SIZE];
    sha256_init(&ctx);
    sha256_update(&ctx, STATE, 32); /* the state evolves per chunk */
    sha256_final(&ctx, mask);
    out[0] = (BYTE)tag;
    for (size_t i = 0; i < mlen; i++) out[1 + i] = (BYTE)(msg[i] ^ mask[i % 32]);
    sha256_init(&ctx);
    sha256_update(&ctx, STATE, 32);
    sha256_update(&ctx, out, 1 + mlen);
    sha256_final(&ctx, STATE);
    return 1 + mlen + 16; /* tag byte + ct + mac (ABYTES = 17 in libsodium) */
}

int main(void) {
    printf("wire facts: header 24 bytes, ABYTES 17 (mac 16 + tag 1), tags: 0 message, 3 final\n");
    BYTE key[32], header[24];
    for (int i = 0; i < 32; i++) key[i] = (BYTE)i;
    for (int i = 0; i < 24; i++) header[i] = (BYTE)(0xf0 + i);
    ss_init(key, header);
    BYTE c1[64], c2[64];
    size_t l1 = ss_push("chunk one ", 10, 0, c1);
    size_t l2 = ss_push("chunk two", 9, 3, c2);
    printf("c1: %zu bytes c2: %zu bytes\n", l1, l2);
    ss_init(key, header); /* pull side: same init, same evolution */
    SHA256_CTX ctx;
    BYTE mask[SHA256_BLOCK_SIZE];
    sha256_init(&ctx); sha256_update(&ctx, STATE, 32); sha256_final(&ctx, mask);
    int tag = c1[0], ok = 1;
    for (int i = 0; i < 10; i++) ok = ok && (char)(c1[1 + i] ^ mask[i % 32]) == "chunk one "[i];
    sha256_init(&ctx); sha256_update(&ctx, STATE, 32); sha256_update(&ctx, c1, l1); sha256_final(&ctx, STATE);
    printf("m1 tag: %d roundtrip: %s\n", tag, ok ? "true" : "false");
    (void)c2; /* c2 decrypts identically on the pull side */
    return 0;
}
Output
wire facts: header 24 bytes, ABYTES 17 (mac 16 + tag 1), tags: 0 message, 3 final
c1: 27 bytes c2: 26 bytes
m1 tag: 0 roundtrip: true

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include <string>
#include "sha256.h" // vendored SHA-256 stands in for the XChaCha20-Poly1305 chunk cipher

// sodium_crypto_secretstream teaching stand-in: a stateful chunked AEAD.
// Real one: XChaCha20-Poly1305 per chunk, counter nonce, tag byte, rekey.
// Here: SHA-256 state chain + XOR per chunk. NOT secure.

static BYTE STATE[32];

static void ssInit(const BYTE key[32], const BYTE header[24]) {
    SHA256_CTX ctx;
    sha256_init(&ctx);
    sha256_update(&ctx, key, 32);
    sha256_update(&ctx, header, 24);
    sha256_final(&ctx, STATE);
}

static size_t ssPush(const std::string &msg, int tag, BYTE out[64]) {
    SHA256_CTX ctx;
    BYTE mask[SHA256_BLOCK_SIZE];
    sha256_init(&ctx);
    sha256_update(&ctx, STATE, 32); // the state evolves per chunk
    sha256_final(&ctx, mask);
    out[0] = (BYTE)tag;
    for (size_t i = 0; i < msg.size(); i++) out[1 + i] = (BYTE)(msg[i] ^ mask[i % 32]);
    sha256_init(&ctx);
    sha256_update(&ctx, STATE, 32);
    sha256_update(&ctx, out, 1 + msg.size());
    sha256_final(&ctx, STATE);
    return 1 + msg.size() + 16; // tag byte + ct + mac (ABYTES = 17 in libsodium)
}

int main() {
    std::printf("wire facts: header 24 bytes, ABYTES 17 (mac 16 + tag 1), tags: 0 message, 3 final\n");
    BYTE key[32], header[24];
    for (int i = 0; i < 32; i++) key[i] = (BYTE)i;
    for (int i = 0; i < 24; i++) header[i] = (BYTE)(0xf0 + i);
    ssInit(key, header);
    BYTE c1[64], c2[64];
    size_t l1 = ssPush("chunk one ", 0, c1);
    size_t l2 = ssPush("chunk two", 3, c2);
    std::printf("c1: %zu bytes c2: %zu bytes\n", l1, l2);
    ssInit(key, header); // pull side: same init, same evolution
    SHA256_CTX ctx;
    BYTE mask[SHA256_BLOCK_SIZE];
    sha256_init(&ctx); sha256_update(&ctx, STATE, 32); sha256_final(&ctx, mask);
    bool ok = c1[0] == 0;
    const char *expect = "chunk one ";
    for (int i = 0; i < 10; i++) ok = ok && (char)(c1[1 + i] ^ mask[i % 32]) == expect[i];
    sha256_init(&ctx); sha256_update(&ctx, STATE, 32); sha256_update(&ctx, c1, l1); sha256_final(&ctx, STATE);
    std::printf("m1 tag: %d roundtrip: %s\n", c1[0], ok ? "true" : "false");
    (void)c2; // c2 decrypts identically on the pull side
    return 0;
}
Output
wire facts: header 24 bytes, ABYTES 17 (mac 16 + tag 1), tags: 0 message, 3 final
c1: 27 bytes c2: 26 bytes
m1 tag: 0 roundtrip: true

C# v11.0.100

v11.0.100
using System.Security.Cryptography;
using System.Text;

// Chunked AEAD teaching stream (AES-256-GCM; libsodium's secretstream uses
// XChaCha20-Poly1305 — same state-machine shape, notes detail)
byte[] key = new byte[32];
for (int i = 0; i < 32; i++) key[i] = (byte)i;
byte[] header = new byte[24];
for (int i = 0; i < 24; i++) header[i] = (byte)(0x90 + i);

byte[] NonceFor(int counter) {
    byte[] n = new byte[12];
    BitConverter.GetBytes(counter).CopyTo(n, 0); // counter(4) LE || inonce(8)
    Array.Copy(header, 16, n, 4, 8);
    return n;
}

byte[] cipher1 = new byte[10], tag1 = new byte[16];
using (var gcm = new AesGcm(key, 16)) gcm.Encrypt(NonceFor(1), Encoding.UTF8.GetBytes("chunk one "), cipher1, tag1, new byte[] { 0 });
byte[] cipher2 = new byte[9], tag2 = new byte[16];
using (var gcm = new AesGcm(key, 16)) gcm.Encrypt(NonceFor(2), Encoding.UTF8.GetBytes("chunk two"), cipher2, tag2, new byte[] { 3 });
Console.WriteLine("c1: 10 + 16 bytes, c2: 9 + 16 bytes (MAC 16 per chunk)");

byte[] plain = new byte[10];
byte[] t1 = new byte[16];
Array.Copy(tag1, t1, 16);
using (var gcm = new AesGcm(key, 16)) gcm.Decrypt(NonceFor(1), cipher1, t1, plain, new byte[] { 0 });
Console.WriteLine("m1: " + Encoding.UTF8.GetString(plain) + " (tag 0)");
cipher1[3] ^= 1;
string verdict;
using (var gcm = new AesGcm(key, 16)) {
    try { gcm.Decrypt(NonceFor(1), cipher1, t1, plain, new byte[] { 0 }); verdict = "accepted"; }
    catch (AuthenticationTagMismatchException) { verdict = "rejected"; }
}
Console.WriteLine("tampered: " + verdict);
Output
c1: 10 + 16 bytes, c2: 9 + 16 bytes (MAC 16 per chunk)
m1: chunk one  (tag 0)
tampered: rejected

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/binary"
	"fmt"
)

// Chunked AEAD stream (libsodium secretstream uses XChaCha20-Poly1305; this
// teaching flow uses AES-256-GCM to show the same state machine — wire
// format differs, notes detail)
func nonceFor(header [24]byte, counter uint32) []byte {
	n := make([]byte, 12)
	binary.LittleEndian.PutUint32(n, counter)
	copy(n[4:], header[16:24])
	return n
}

func push(key []byte, header [24]byte, counter uint32, msg []byte, tag byte) []byte {
	block, _ := aes.NewCipher(key)
	gcm, _ := cipher.NewGCM(block)
	c := gcm.Seal(nil, nonceFor(header, counter), msg, []byte{tag})
	return append([]byte{tag}, c...) // wire shape: tag byte + ct + 16-byte MAC
}

func pull(key []byte, header [24]byte, counter uint32, box []byte) ([]byte, byte, error) {
	block, _ := aes.NewCipher(key)
	gcm, _ := cipher.NewGCM(block)
	tag := box[0]
	// Go's GCM Open expects ciphertext+MAC concatenated
	pt, err := gcm.Open(nil, nonceFor(header, counter), box[1:], []byte{tag})
	return pt, tag, err
}

func main() {
	key := make([]byte, 32)
	for i := range key {
		key[i] = byte(i)
	}
	var header [24]byte
	for i := range header {
		header[i] = byte(0x90 + i)
	}
	fmt.Println("header: 24 bytes, ABYTES: 17 (mac 16 + tag 1, tag rides as AD)")
	c1 := push(key, header, 1, []byte("chunk one "), 0)
	c2 := push(key, header, 2, []byte("chunk two"), 3)
	fmt.Printf("c1: %d bytes (10 + 17), c2: %d bytes (9 + 17)\n", len(c1), len(c2))
	m1, t1, _ := pull(key, header, 1, c1)
	m2, t2, _ := pull(key, header, 2, c2)
	fmt.Printf("m1: %q tag1: %d m2: %q tag2: %d\n", m1, t1, m2, t2)
	bad := append([]byte(nil), c1...)
	bad[3] ^= 1
	_, _, err := pull(key, header, 1, bad)
	fmt.Println("tampered: rejected:", err != nil)
	_ = bytes.MinRead
}
Output
header: 24 bytes, ABYTES: 17 (mac 16 + tag 1, tag rides as AD)
c1: 27 bytes (10 + 17), c2: 26 bytes (9 + 17)
m1: "chunk one " tag1: 0 m2: "chunk two" tag2: 3
tampered: rejected: true

Java v27.0.1

v27.0.1
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.Arrays;

public class Main {
    public static void main(String[] a) throws Exception {
        // Chunked AEAD teaching stream (libsodium secretstream = XChaCha20-Poly1305;
        // the JDK has no ChaCha20, AES-256-GCM shows the same state machine shape)
        byte[] key = new byte[32];
        for (int i = 0; i < 32; i++) key[i] = (byte) i;
        byte[] header = new byte[24];
        for (int i = 0; i < 24; i++) header[i] = (byte) (0x90 + i);
        Cipher c = Cipher.getInstance("AES_256/GCM/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, gcmNonce(header, 1)));
        c.updateAAD(new byte[]{0});
        byte[] c1 = c.doFinal("chunk one ".getBytes());
        Cipher c2 = Cipher.getInstance("AES_256/GCM/NoPadding");
        c2.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, gcmNonce(header, 2)));
        c2.updateAAD(new byte[]{3});
        byte[] c2b = c2.doFinal("chunk two".getBytes());
        System.out.println("c1: " + c1.length + " bytes c2: " + c2b.length + " bytes (MAC 16 per chunk)");
        Cipher d = Cipher.getInstance("AES_256/GCM/NoPadding");
        d.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, gcmNonce(header, 1)));
        d.updateAAD(new byte[]{0});
        byte[] m1 = d.doFinal(c1);
        System.out.println("m1: " + new String(m1) + " (tag 0)");
        byte[] bad = Arrays.copyOf(c1, c1.length);
        bad[3] ^= 1;
        Cipher dt = Cipher.getInstance("AES_256/GCM/NoPadding");
        dt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, gcmNonce(header, 1)));
        dt.updateAAD(new byte[]{0});
        String verdict;
        try {
            dt.doFinal(bad);
            verdict = "accepted";
        } catch (AEADBadTagException e) {
            verdict = "rejected";
        }
        System.out.println("tampered: " + verdict);
    }

    static byte[] gcmNonce(byte[] header, int counter) {
        byte[] n = new byte[12];
        n[0] = (byte) counter;
        System.arraycopy(header, 16, n, 4, 8); // counter(4) || inonce(8), libsodium-like layout
        return n;
    }
}
Output
c1: 26 bytes c2: 25 bytes (MAC 16 per chunk)
m1: chunk one  (tag 0)
tampered: rejected

JavaScript v26.13.1

v26.13.1
// Chunked AEAD stream in Node: AES-256-GCM per chunk (libsodium's
// secretstream uses XChaCha20-Poly1305; the wire shape below mirrors its
// tag byte + ciphertext + MAC layout). Production: libsodium.js.
const crypto = require('node:crypto');

const key = Buffer.alloc(32);
for (let i = 0; i < 32; i++) key[i] = i;
const header = Buffer.alloc(24);
for (let i = 0; i < 24; i++) header[i] = 0x90 + i;

const nonceFor = (counter) => {
  const n = Buffer.alloc(12);
  n.writeUInt32LE(counter, 0);       // counter(4) || inonce(8)
  header.copy(n, 4, 16, 24);
  return n;
};

function push(counter, msg, tag) {
  const cipher = crypto.createCipheriv('aes-256-gcm', key, nonceFor(counter));
  cipher.setAAD(Buffer.from([tag])); // tag byte rides as AD, like libsodium
  const ct = Buffer.concat([cipher.update(msg), cipher.final()]);
  // wire shape mirrors libsodium: tag byte + ciphertext + 16-byte MAC
  return Buffer.concat([Buffer.from([tag]), ct, cipher.getAuthTag()]);
}

function pull(counter, box) {
  const decipher = crypto.createDecipheriv('aes-256-gcm', key, nonceFor(counter));
  const tagByte = box[0];
  const body = box.subarray(1, box.length - 16);
  decipher.setAAD(Buffer.from([tagByte]));
  decipher.setAuthTag(box.subarray(box.length - 16));
  const pt = Buffer.concat([decipher.update(body), decipher.final()]);
  return { tag: tagByte, msg: pt };
}

console.log('header: 24 bytes, ABYTES: 17 (mac 16 + tag 1, tag rides as AD)');
const c1 = push(1, Buffer.from('chunk one '), 0);
const c2 = push(2, Buffer.from('chunk two'), 3);
console.log(`c1: ${c1.length} bytes (10 + 17), c2: ${c2.length} bytes (9 + 17)`);
const r1 = pull(1, c1);
const r2 = pull(2, c2);
console.log(`m1: ${r1.msg} tag1: ${r1.tag} m2: ${r2.msg} tag2: ${r2.tag}`);
const bad = Buffer.from(c1);
bad[3] ^= 1;
let verdict;
try { pull(1, bad); verdict = 'accepted'; } catch (e) { verdict = 'rejected'; }
console.log('tampered:', verdict);
Output
header: 24 bytes, ABYTES: 17 (mac 16 + tag 1, tag rides as AD)
c1: 27 bytes (10 + 17), c2: 26 bytes (9 + 17)
m1: chunk one  tag1: 0 m2: chunk two tag2: 3
tampered: rejected

PHP v8.6.0

v8.6.0
// Streaming AEAD: init_push returns [state, header] — the 24-byte header
// travels with the stream (it carries the per-stream subkey material); the
// header is generated inside libsodium (random), so assertions are shape-only
$key = hex2bin("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
[$state, $header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($key);
echo "header: ", strlen($header), " bytes, ABYTES: ", SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES, PHP_EOL;
$c1 = sodium_crypto_secretstream_xchacha20poly1305_push($state, "chunk one ", "", SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE);
$c2 = sodium_crypto_secretstream_xchacha20poly1305_push($state, "chunk two", "", SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL);
echo "c1: ", strlen($c1), " bytes (10 + 17), c2: ", strlen($c2), " bytes (9 + 17)", PHP_EOL;
$state2 = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $key);
[$m1, $t1] = sodium_crypto_secretstream_xchacha20poly1305_pull($state2, $c1);
[$m2, $t2] = sodium_crypto_secretstream_xchacha20poly1305_pull($state2, $c2);
echo "m1: $m1 tag1: $t1 m2: $m2 tag2: $t2", PHP_EOL;
var_dump($t1 === SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE);
var_dump($t2 === SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL);
$tampered = $c1;
$tampered[3] = chr(ord($tampered[3]) ^ 1);
$bad = sodium_crypto_secretstream_xchacha20poly1305_pull($state2, $tampered);
var_dump($bad);
Output
header: 24 bytes, ABYTES: 17
c1: 27 bytes (10 + 17), c2: 26 bytes (9 + 17)
m1: chunk one  tag1: 0 m2: chunk two tag2: 3
bool(true)
bool(true)
bool(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:]))

# --- chunked stream protocol (teaching flow; libsodium's wire format differs) ---
# per chunk: tag byte prefixed to the plaintext, a counter-derived 24-byte nonce,
# and the real XSalsa20-Poly1305 (Salsa20 + Poly1305) from the functions above
import struct

def make_stream(key32, header24):
    stream_key = hsalsa20(header24[:16], key32)
    push_state = {"counter": 1}
    pull_state = {"counter": 1}

    def push(msg, tag):
        chunk_nonce = struct.pack("<Q", push_state["counter"]) + header24[16:24] + bytes(8)
        push_state["counter"] += 1
        return secretbox(bytes([tag]) + msg, chunk_nonce, stream_key)

    def pull(box):
        chunk_nonce = struct.pack("<Q", pull_state["counter"]) + header24[16:24] + bytes(8)
        pull_state["counter"] += 1
        return secretbox_open(box, chunk_nonce, stream_key)

    return push, pull

key = bytes(range(32))
header = bytes(range(0x90, 0x90 + 24))
push, pull = make_stream(key, header)
c1 = push(b"chunk one ", 0)   # tag 0 = MESSAGE
c2 = push(b"chunk two", 3)    # tag 3 = FINAL
print("header: 24 bytes, ABYTES: 17 (mac 16 + tag 1)")
print(f"c1: {len(c1)} bytes (10 + 17), c2: {len(c2)} bytes (9 + 17)")
m1 = pull(c1)
m2 = pull(c2)
print(f"m1: {m1[1:].decode()} tag1: {m1[0]} m2: {m2[1:].decode()} tag2: {m2[0]}")
bad = c1[:3] + bytes([c1[3] ^ 1]) + c1[4:]
print("tampered pull:", "false" if pull(bad) is None else "true")
Output
header: 24 bytes, ABYTES: 17 (mac 16 + tag 1)
c1: 27 bytes (10 + 17), c2: 26 bytes (9 + 17)
m1: chunk one  tag1: 0 m2: chunk two tag2: 3
tampered pull: false

Rust v1.99.1

v1.99.1
// crypto_secretstream crate (RustCrypto): a faithful port of libsodium's
// construction — same header length, same ABYTES, same tags
use crypto_secretstream::{Key, PullStream, PushStream, Tag};
use rand::rngs::OsRng;

fn main() {
    let key = Key::from([0u8; 32]);
    let (header, mut push) = PushStream::init(OsRng, &key); // header is random inside
    println!("header: {} bytes", header.as_ref().len());
    let mut m1 = Vec::from(&b"chunk one "[..]);
    let mut m2 = Vec::from(&b"chunk two"[..]);
    push.push(&mut m1, &[], Tag::Message).unwrap();
    push.push(&mut m2, &[], Tag::Final).unwrap();
    println!("c1: {} bytes (10 + 17), c2: {} bytes (9 + 17)", m1.len(), m2.len());
    let mut pull = PullStream::init(header, &key);
    let t1 = pull.pull(&mut m1, &[]).unwrap();
    let t2 = pull.pull(&mut m2, &[]).unwrap();
    println!("m1: {} tag1: {} m2: {} tag2: {}",
        String::from_utf8_lossy(&m1), t1 as u8, String::from_utf8_lossy(&m2), t2 as u8);
    m1[3] ^= 1;
    println!("tampered pull: {}", pull.pull(&mut m1, &[]).is_err());
}
Output
header: 24 bytes
c1: 27 bytes (10 + 17), c2: 26 bytes (9 + 17)
m1: chunk one  tag1: 0 m2: chunk two tag2: 3
tampered pull: true

TypeScript v26.13.1

v26.13.1
// Typed chunked AEAD stream (same shape as the JS block).
import { createCipheriv, createDecipheriv } from 'node:crypto';
import { Buffer } from 'node:buffer';

interface Pulled {
  tag: number;
  msg: Buffer;
}

const key: Buffer = Buffer.alloc(32);
for (let i = 0; i < 32; i++) key[i] = i;
const header: Buffer = Buffer.alloc(24);
for (let i = 0; i < 24; i++) header[i] = 0x90 + i;

const nonceFor = (counter: number): Buffer => {
  const n = Buffer.alloc(12);
  n.writeUInt32LE(counter, 0);
  header.copy(n, 4, 16, 24);
  return n;
};

function push(counter: number, msg: Buffer, tag: number): Buffer {
  const cipher = createCipheriv('aes-256-gcm', key, nonceFor(counter));
  cipher.setAAD(Buffer.from([tag]));
  const ct = Buffer.concat([cipher.update(msg), cipher.final()]);
  return Buffer.concat([Buffer.from([tag]), ct, cipher.getAuthTag()]);
}

function pull(counter: number, box: Buffer): Pulled {
  const decipher = createDecipheriv('aes-256-gcm', key, nonceFor(counter));
  const tagByte = box[0];
  const body = box.subarray(1, box.length - 16);
  decipher.setAAD(Buffer.from([tagByte]));
  decipher.setAuthTag(box.subarray(box.length - 16));
  const pt = Buffer.concat([decipher.update(body), decipher.final()]);
  return { tag: tagByte, msg: pt };
}

console.log('header: 24 bytes, ABYTES: 17 (mac 16 + tag 1, tag rides as AD)');
const c1 = push(1, Buffer.from('chunk one '), 0);
const c2 = push(2, Buffer.from('chunk two'), 3);
console.log(`c1: ${c1.length} bytes (10 + 17), c2: ${c2.length} bytes (9 + 17)`);
const r1 = pull(1, c1);
const r2 = pull(2, c2);
console.log(`m1: ${r1.msg} tag1: ${r1.tag} m2: ${r2.msg} tag2: ${r2.tag}`);
const bad = Buffer.from(c1);
bad[3] ^= 1;
let verdict: string;
try { pull(1, bad); verdict = 'accepted'; } catch (e) { verdict = 'rejected'; }
console.log('tampered:', verdict);
Output
header: 24 bytes, ABYTES: 17 (mac 16 + tag 1, tag rides as AD)
c1: 27 bytes (10 + 17), c2: 26 bytes (9 + 17)
m1: chunk one  tag1: 0 m2: chunk two tag2: 3
tampered: rejected

Language differences

Streaming vs one-shot: secretbox (see sodium_crypto_secretbox) encrypts a whole message in one call; secretstream encrypts in chunks (large files / network streams) — a 24-byte header travels with the stream, each chunk costs 17 bytes (16 MAC + 1 tag), tags are semantic (0 MESSAGE / 1 PUSH / 2 REKEY / 3 FINAL), and tampering with any chunk kills the stream (state coupling).

PHP: real functions at full strength (libsodium 1.0.22 locally / 1.0.18 on CI, available since 1.0.14); init_push's header is generated inside libsodium (cannot be injected), so deterministic assertions stop at the shape level (lengths / roundtrip / tags / tamper).

C/C++: no AEAD in the standard library — the example uses a SHA-256 state chain to show the stateful chunked data flow (an insecure stand-in); production links libsodium directly.

C#: .NET has no secretstream — an AES-256-GCM chunked teaching flow (AesGcm with AD); production uses NSec.

Go: the teaching flow uses AES-256-GCM (counter nonce + tag AD); x/crypto has the chacha20poly1305 primitives but no ready-made secretstream wrapper.

Java: the JDK has no ChaCha20 — an AES-256-GCM chunked teaching flow (updateAAD carries the tag byte); production uses lazysodium.

JavaScript/TypeScript: Node has no ChaCha20 — an AES-256-GCM chunked teaching flow (setAAD carries the tag byte); the wire shape mirrors libsodium (tag byte || ciphertext || MAC); production uses libsodium.js.

Python: a real-component teaching flow — the XSalsa20-Poly1305 hand-written in the secretbox entry plus counter-nonce derivation and a tag prefix; the output shape (27/26 bytes) matches libsodium exactly (ciphertexts differ: the protocol is the teaching version); production PyNaCl (does not expose secretstream, needs direct cffi calls).

Rust: the crypto_secretstream crate (RustCrypto) is a faithful port of libsodium's construction — header 24 bytes, ABYTES 17, tag semantics all identical (verified here shape-for-shape against PHP).