流式 AEAD
sodium_crypto_secretstream_xchacha20poly1305_init_push / push / pull
分块加密大文件的流式 AEAD:一个 24 字节 header + 逐 chunk push/pull,每块带类型标签(MESSAGE/FINAL/PUSH/REKEY),状态随密文演进,篡改任意一块即断流。与一次性 secretbox 对照。
C C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" /* vendor 的 SHA-256 顶替每块 XChaCha20-Poly1305 密码 */
/* sodium_crypto_secretstream 教学替身:带状态的分块 AEAD。
真实现:每块 XChaCha20-Poly1305、计数器 nonce、tag 字节、rekey。
这里:SHA-256 状态链 + 每块 XOR。不安全。 */
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); /* 状态随块演进 */
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 字节 + 密文 + mac(libsodium 的 ABYTES = 17) */
}
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 侧:同初始化,同演进 */
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 在 pull 侧同样解密 */
return 0;
}
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
#include <cstdio>
#include <cstring>
#include <string>
#include "sha256.h" // vendor 的 SHA-256 顶替每块 XChaCha20-Poly1305 密码
// sodium_crypto_secretstream 教学替身:带状态的分块 AEAD。
// 真实现:每块 XChaCha20-Poly1305、计数器 nonce、tag 字节、rekey。
// 这里:SHA-256 状态链 + 每块 XOR。不安全。
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); // 状态随块演进
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 字节 + 密文 + mac(libsodium 的 ABYTES = 17)
}
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 侧:同初始化,同演进
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 在 pull 侧同样解密
return 0;
}
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
using System.Security.Cryptography;
using System.Text;
// 分块 AEAD 教学流(AES-256-GCM;libsodium 的 secretstream 用
// XChaCha20-Poly1305——同一状态机形状,notes 详述)
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) 小端 || 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);
c1: 10 + 16 bytes, c2: 9 + 16 bytes (MAC 16 per chunk) m1: chunk one (tag 0) tampered: rejected
Go v1.27.4
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"fmt"
)
// 分块 AEAD 流(libsodium secretstream 用 XChaCha20-Poly1305;本教学流用
// AES-256-GCM 展示同一状态机——线上格式不同,notes 详述)
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...) // 线上形状:tag 字节 + 密文 + 16 字节 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 的 GCM Open 期望密文+MAC 连在一起
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)
}
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
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.Arrays;
public class Main {
public static void main(String[] a) throws Exception {
// 分块 AEAD 教学流(libsodium secretstream = XChaCha20-Poly1305;
// JDK 无 ChaCha20,AES-256-GCM 展示同一状态机形状)
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}); // tag 字节作 AD
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 风格布局
return n;
}
}
c1: 26 bytes c2: 25 bytes (MAC 16 per chunk) m1: chunk one (tag 0) tampered: rejected
JavaScript v26.13.1
// Node 的分块 AEAD 流:每块 AES-256-GCM(libsodium 的 secretstream 用
// XChaCha20-Poly1305;下方线上形状镜像其 tag 字节 + 密文 + MAC 布局)。
// 生产用 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 字节作 AD,与 libsodium 一致
const ct = Buffer.concat([cipher.update(msg), cipher.final()]);
// 线上形状镜像 libsodium:tag 字节 + 密文 + 16 字节 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);
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
// 流式 AEAD:init_push 返回 [state, header]——24 字节 header 随流传输
//(承载每流子密钥材料);header 由 libsodium 内部生成(随机),
// 因此断言采用形状断言
$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); // tag 0
$c2 = sodium_crypto_secretstream_xchacha20poly1305_push($state, "chunk two", "", SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL); // tag 3
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); // 返回 false
var_dump($bad);
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
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) ---
# 每块:明文前置 tag 字节、按计数派生的 24 字节 nonce、
# 以及上面函数里的真 XSalsa20-Poly1305(Salsa20 + Poly1305)——教学流协议,
import struct
def make_stream(key32, header24): # libsodium 线上格式不同,见 notes
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")
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
// crypto_secretstream crate(RustCrypto):libsodium 构造的忠实移植——
// 同 header 长度、同 ABYTES、同 tag 语义
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 内部随机生成
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());
}
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
// 类型化分块 AEAD 流(与 JS 块同构)。
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);
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
语言差异说明
流式 vs 一次性:secretbox(见 sodium_crypto_secretbox)一口气加密整个消息;secretstream 分块加密(大文件/网络流),header 24 字节随流传输、每块 17 字节开销(16 MAC + 1 tag)、tag 语义化(0 MESSAGE / 1 PUSH / 2 REKEY / 3 FINAL)、篡改任意块即断流(状态耦合)。
PHP:满血真函数(本地 libsodium 1.0.22 / CI 1.0.18 均支持,1.0.14+ 可用);init_push 的 header 由内部随机生成(不可注入),故确定性断言只能到「形状」层(长度/往返/tag/篡改)。
C/C++:stdlib 无 AEAD——示例 SHA-256 状态链展示状态化分块数据流(不安全替身);生产直接链 libsodium。
C#:.NET 无 secretstream——AES-256-GCM 分块教学(AesGcm 带 AD);生产用 NSec。
Go:教学流用 AES-256-GCM(counter nonce + tag AD);x/crypto 有 chacha20poly1305 原语但无现成 secretstream 封装。
Java:JDK 无 ChaCha20——AES-256-GCM 分块教学(updateAAD 传 tag 字节);生产用 lazysodium。
JavaScript/TypeScript:Node 无 ChaCha20——AES-256-GCM 分块教学(setAAD 传 tag 字节);线上形状镜像 libsodium(tag 字节 || 密文 || MAC);生产用 libsodium.js。
Python:真组件教学流——secretbox 条目手写的 XSalsa20-Poly1305 + 计数器 nonce 派生 + tag 前缀,输出形状(27/26 字节)与 libsodium 完全一致(密文不同:协议是教学版);生产 PyNaCl(不暴露 secretstream,需 cffi 直调)。
Rust:crypto_secretstream crate(RustCrypto)是 libsodium 构造的忠实移植——header 24 字节、ABYTES 17、tag 语义全一致(本条实测与 PHP 形状逐项相同)。