sodium_crypto_secretbox
sodium_crypto_secretbox(string $message, string $nonce, string $key): string
用共享密钥做带认证的加密:XSalsa20-Poly1305 生成「16 字节 MAC + 密文」,解密时验签失败返回 false。
C C23
#include <stdio.h>
#include <string.h>
#include <stdint.h>
// ---- Salsa20 流密码核心(RFC 8439 第 2.3 节,20 轮)----
static uint32_t rotl(uint32_t x, int n) { return (x << n) | (x >> (32 - n)); }
// 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++) {
// 列轮
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]);
// 行轮
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 字节输入,输出 32 字节子密钥
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 输出序:先取常量位置 0/5/10/15,再取输入块 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 流异或:nonce8 为 24 字节 secretbox nonce 的后一半。
// 状态布局:key 位于 1-4/11-14,8 字节 nonce 位于 6-7,64 位小端块计数器位于 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 位小端块计数器,从 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];
// 64 位小端块计数器加一
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 一次性认证码(RFC 8439 第 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 = 密钥前 16 字节,钳位
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; // 每个 17 字节块的隐含高位
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;
}
// 全进位并模 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;
// h >= p 时选 h + 5 - 2^130,否则保留 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; // 借位说明 h < p:保留 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;
// 取模 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(密钥后 16 字节),带进位传播
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 流异或 + 密文的 Poly1305 认证标签 ----
// 密钥流前 32 字节用作一次性 Poly1305 密钥,
// 因此消息从密钥流第 32 字节起加密。
// 输出序与 sodium_crypto_secretbox 一致:16 字节 MAC || 密文
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); // 对零缓冲区异或 = 从计数器 0 起的原始密钥流
memcpy(polykey, ks, 32); // 一次性 Poly1305 密钥
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);
}
// 成功返回 0,tag 校验失败返回 -1
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; // 常量时间 tag 比较
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; // 翻转一个密文位(位于 16 字节 MAC 之后)
printf("tampered open: %s\n", secretbox_open(opened, out, mlen + 16, nonce, key) == 0 ? "true" : "false");
return 0;
}
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
C++ C++26
#include <cstdio>
#include <cstring>
#include <cstdint>
// ---- Salsa20 流密码核心(RFC 8439 第 2.3 节,20 轮)----
static uint32_t rotl(uint32_t x, int n) { return (x << n) | (x >> (32 - n)); }
// 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++) {
// 列轮
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]);
// 行轮
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 字节输入,输出 32 字节子密钥
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 输出序:先取常量位置 0/5/10/15,再取输入块 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 流异或:nonce8 为 24 字节 secretbox nonce 的后一半。
// 状态布局:key 位于 1-4/11-14,8 字节 nonce 位于 6-7,64 位小端块计数器位于 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 位小端块计数器,从 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];
// 64 位小端块计数器加一
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 一次性认证码(RFC 8439 第 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 = 密钥前 16 字节,钳位
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; // 每个 17 字节块的隐含高位
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;
}
// 全进位并模 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;
// h >= p 时选 h + 5 - 2^130,否则保留 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; // 借位说明 h < p:保留 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;
// 取模 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(密钥后 16 字节),带进位传播
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 流异或 + 密文的 Poly1305 认证标签 ----
// 密钥流前 32 字节用作一次性 Poly1305 密钥,
// 因此消息从密钥流第 32 字节起加密。
// 输出序与 sodium_crypto_secretbox 一致:16 字节 MAC || 密文
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); // 对零缓冲区异或 = 从计数器 0 起的原始密钥流
memcpy(polykey, ks, 32); // 一次性 Poly1305 密钥
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);
}
// 成功返回 0,tag 校验失败返回 -1
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; // 常量时间 tag 比较
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; // 翻转一个密文位(位于 16 字节 MAC 之后)
printf("tampered open: %s\n", secretbox_open(opened, out, mlen + 16, nonce, key) == 0 ? "true" : "false");
return 0;
}
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
C# v11.0.100
using System;
using System.Linq;
// 纯 C# 手写 XSalsa20-Poly1305(libsodium secretbox),教学向实现
// 生产环境用 NSec/libsodium 绑定;这里展开内部结构
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 只取常量位与输入块位置的值
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 位小端块计数器位于状态字 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 把输入状态加回;HSalsa20 不加
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 风格:5 个 26 位 limb,乘积放入 64 位 ulong
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; // 每个 17 字节块的隐含高位
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;
}
// 全进位并模 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;
// h >= p 时选 h + 5 - 2^130,否则保留 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);
// g4 借位(32 位语义下 bit31 置位)说明 h < p:保留 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;
// 取模 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(密钥后 16 字节),带进位传播
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);
// 密钥流前 32 字节 = 一次性 Poly1305 密钥;消息从第 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 输出序:MAC(16) || 密文
}
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; // 常量时间 tag 比较
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")}");
}
}
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
Go v1.27.4
package main
import (
"bytes"
"encoding/hex"
"fmt"
"golang.org/x/crypto/nacl/secretbox" // XSalsa20-Poly1305 secretbox,与 libsodium 同源
)
func main() {
key := new([32]byte) // 固定演示 key(生产:随机生成并保密)
for i := range key {
key[i] = byte(i)
}
var nonce [24]byte // 固定演示 nonce(生产:随机生成,同一 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)) // 输出序:16 字节 MAC || 密文
opened, ok := secretbox.Open(nil, box, &nonce, key)
fmt.Println("roundtrip:", ok && bytes.Equal(opened, msg))
bad := bytes.Clone(box)
bad[16] ^= 1 // 翻转一个密文位(位于 16 字节 MAC 之后)
_, ok = secretbox.Open(nil, bad, &nonce, key)
fmt.Println("tampered open:", ok)
}
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
Java v27.0.1
import java.util.HexFormat;
// 纯 Java 手写 XSalsa20-Poly1305(libsodium secretbox),教学向实现
// 生产环境用 lazysodium 等 libsodium 绑定;这里展开内部结构
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 只取常量位与输入块位置的值
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 把输入状态加回;HSalsa20 不加
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 风格:5 个 26 位 limb,乘积放入 64 位 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; // 每个 17 字节块的隐含高位
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;
}
// 全进位并模 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;
// h >= p 时选 h + 5 - 2^130,否则保留 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;
// 取模 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(密钥后 16 字节),带进位传播
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);
// 密钥流前 32 字节 = 一次性 Poly1305 密钥;消息从第 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 输出序:MAC(16) || 密文
}
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; // 常量时间 tag 比较
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));
}
}
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
JavaScript v26.13.1
// 纯 JS 手写 XSalsa20-Poly1305(libsodium secretbox),教学向实现
// 生产环境用 libsodium.js 绑定;这里展开内部结构
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 只取常量位与输入块位置的值
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 位小端块计数器位于状态字 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 把输入状态加回;HSalsa20 不加
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 数值只有 53 位精度:130 位累加需要 BigInt。
// 数学与 C 参考实现一致,逐块处理
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; // r 钳位
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)); // 每块隐含的高位
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);
// 密钥流前 32 字节 = 一次性 Poly1305 密钥;消息从第 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 输出序:MAC(16) || 密文
}
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);
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
PHP v8.6.0
// sodium_crypto_secretbox: XSalsa20-Poly1305 带认证加密。
// 固定 key/nonce 使输出可跨语言确定性对照。
$key = hex2bin("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); // 32 字节共享密钥(仅演示)
$nonce = hex2bin("000102030405060708090a0b0c0d0e0f1011121314151617"); // 24 字节 nonce:同一 key 下绝不复用
$msg = "attack at dawn";
$box = sodium_crypto_secretbox($msg, $nonce, $key);
echo "box: ", bin2hex($box), "\n"; // sodium 输出序:16 字节 MAC || 密文
$open = sodium_crypto_secretbox_open($box, $nonce, $key);
echo "roundtrip: ", var_export($open === $msg, true), "\n";
$box[16] = chr(ord($box[16]) ^ 1); // 翻转一个密文位
echo "tampered open: ", var_export(sodium_crypto_secretbox_open($box, $nonce, $key) !== false, true), "\n";
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
Python v3.15.2
import struct
# 纯 Python 手写 XSalsa20-Poly1305(libsodium secretbox),教学向实现
# 生产环境用 PyNaCl(libsodium 绑定)一行搞定;这里展开内部结构
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):
# 密钥流:64 位小端块计数器位于状态字 8-9,8 字节 nonce 位于 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 输出序:MAC(16) || 密文
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")
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
Rust v1.99.1
use crypto_secretbox::aead::Aead;
use crypto_secretbox::{KeyInit, XSalsa20Poly1305};
// crypto_secretbox(RustCrypto):与 libsodium 同源的 XSalsa20-Poly1305 secretbox。
// 其 AEAD 输出序与 sodium_crypto_secretbox 逐字节一致(已与 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; // 翻转一个密文位
println!("tampered open: {}", cipher.decrypt(nonce, bad.as_slice()).is_ok());
}
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
TypeScript v26.13.1
// 纯 TypeScript 手写 XSalsa20-Poly1305(libsodium secretbox),教学向实现
// 生产环境用 libsodium.js 绑定;这里展开内部结构
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 只取常量位与输入块位置的值
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 位小端块计数器位于状态字 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 把输入状态加回;HSalsa20 不加
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 数值只有 53 位精度:130 位累加需要 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; // r 钳位
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)); // 每块隐含的高位
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);
// 密钥流前 32 字节 = 一次性 Poly1305 密钥;消息从第 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 输出序:MAC(16) || 密文
}
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);
box: 11f50cc082ee7c49b76cb911c749e03e3f8b4c2ea4a18271cf1ceb5f1fe1 roundtrip: true tampered open: false
语言差异说明
本批 special:经典 sodium/openssl 函数在 CI 的 libsodium 1.0.18 上完全可跑,四条均为真函数满血演示 + 确定性预置输出,与前批 8.6 新函数的受限形态形成对照。
C:stdlib 无加密——示例纯 C 手写 XSalsa20-Poly1305(输出与 libsodium 逐字节一致);实战直接链 libsodium crypto_secretbox_easy 或 OpenSSL。
C++:同 C 手写;实战用 libsodium 或 NSec(libsodium 绑定)。
C#:stdlib 无 XSalsa20——示例手写同款实现(与 libsodium 逐字节一致);实战用 NSec SecretBox(libsodium 绑定)。
Go:golang.org/x/crypto/nacl/secretbox 与 libsodium 同源,密文逐字节一致。
Java:stdlib 无 XSalsa20——示例手写;实战用 lazysodium(libsodium 绑定)。
JavaScript:Node stdlib 无 XSalsa20——示例纯 JS 手写(Poly1305 用 BigInt 保证 130 位精度);生产用 libsodium.js。
PHP:sodium_crypto_secretbox 返回序为 16 字节 MAC || 密文(不是密文 || MAC!);nonce 24 字节,同一 key 下绝不复用——复用即灾难(两次一密)。
Python:stdlib 无对称 AEAD——示例纯 Python 手写;生产用 PyNaCl SecretBox(libsodium 绑定)。
Rust:crypto_secretbox crate(RustCrypto)的 AEAD 布局与 sodium_crypto_secretbox 逐字节一致(已实测),encrypt/decrypt 一站搞定。
TypeScript:同 JavaScript。libsodium 绑定族(PyNaCl/libsodium.js/lazysodium/NSec)vs 标准库拼装(Go nacl/x/crypto、Rust crypto_secretbox、各手写)两条路线等价可互解:固定 key/nonce/明文下密文逐字节相同。