非对称加密
sodium_crypto_box / sodium_crypto_box_open / sodium_crypto_box_seed_keypair
公钥加密(X25519 密钥协商 + XSalsa20-Poly1305):发件方用收件方公钥加密,只有对应私钥能解。与 secretbox 对称加密对照——box = 密钥协商 + secretbox 的组合。
C C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" /* vendor 的 SHA-256 顶替 X25519 + HSalsa20 步骤 */
/* sodium_crypto_box 教学替身:真 box = X25519(sk,pk) 再 XSalsa20-Poly1305
(完整手写版见 sodium_crypto_secretbox 条目)。这里用 KDF 替身展示
封套数据流。不安全。 */
int main(void) {
printf("wire sizes: pk 32, sk 32, nonce 24, mac 16 (ciphertext = 16 + msg)\n");
printf("alg: x25519 + xsalsa20poly1305 (beforenm = HSalsa20(shared, zeros))\n");
BYTE seed[32];
for (int i = 0; i < 32; i++) seed[i] = (BYTE)i;
SHA256_CTX ctx;
BYTE sk[32], pk[32], beforenm[32];
sha256_init(&ctx); sha256_update(&ctx, seed, 32); sha256_final(&ctx, sk);
sha256_init(&ctx); sha256_update(&ctx, sk, 32); sha256_final(&ctx, pk); /* 顶替 scalarmult */
sha256_init(&ctx); sha256_update(&ctx, pk, 32); sha256_update(&ctx, sk, 32); sha256_final(&ctx, beforenm);
printf("pk: ");
for (int i = 0; i < 16; i++) printf("%02x", pk[i]);
printf("...\n");
const char *msg = "public key envelope";
size_t mlen = strlen(msg);
BYTE box[16 + 64];
for (size_t i = 0; i < mlen; i++) box[16 + i] = (BYTE)(msg[i] ^ beforenm[i % 32]);
BYTE mac[SHA256_BLOCK_SIZE];
/* seal:MAC 覆盖密文字节(镜像 sodium 的 MAC || ct 布局) */
sha256_init(&ctx); sha256_update(&ctx, beforenm, 32); sha256_update(&ctx, box + 16, mlen);
sha256_final(&ctx, mac);
memcpy(box, mac, 16);
printf("box: %d bytes (mac 16 + ct %zu)\n", 16 + (int)mlen, mlen);
sha256_init(&ctx); sha256_update(&ctx, beforenm, 32); sha256_update(&ctx, box + 16, mlen);
sha256_final(&ctx, mac);
printf("open roundtrip: %s\n", memcmp(box, mac, 16) == 0 ? "true" : "false");
box[20] ^= 1; /* 篡改一个密文字节 */
sha256_init(&ctx); sha256_update(&ctx, beforenm, 32); sha256_update(&ctx, box + 16, mlen);
sha256_final(&ctx, mac);
printf("tampered open: %s\n", memcmp(box, mac, 16) == 0 ? "true" : "false");
return 0;
}
wire sizes: pk 32, sk 32, nonce 24, mac 16 (ciphertext = 16 + msg) alg: x25519 + xsalsa20poly1305 (beforenm = HSalsa20(shared, zeros)) pk: 2f287b4d3d4910f6cada9e1bd1b46480... box: 35 bytes (mac 16 + ct 19) open roundtrip: true tampered open: false
C++ C++26
#include <cstdio>
#include <cstring>
#include <string>
#include "sha256.h" // vendor 的 SHA-256 顶替 X25519 + HSalsa20 步骤
// sodium_crypto_box 教学替身:真 box = X25519 + XSalsa20-Poly1305。
// 这里用 KDF 替身展示封套数据流。不安全。
int main() {
std::printf("wire sizes: pk 32, sk 32, nonce 24, mac 16 (ciphertext = 16 + msg)\n");
std::printf("alg: x25519 + xsalsa20poly1305 (beforenm = HSalsa20(shared, zeros))\n");
BYTE seed[32];
for (int i = 0; i < 32; i++) seed[i] = (BYTE)i;
SHA256_CTX ctx;
BYTE sk[32], pk[32], beforenm[32];
sha256_init(&ctx); sha256_update(&ctx, seed, 32); sha256_final(&ctx, sk);
sha256_init(&ctx); sha256_update(&ctx, sk, 32); sha256_final(&ctx, pk); // 顶替 scalarmult
sha256_init(&ctx); sha256_update(&ctx, pk, 32); sha256_update(&ctx, sk, 32); sha256_final(&ctx, beforenm);
std::printf("pk: ");
for (int i = 0; i < 16; i++) std::printf("%02x", pk[i]);
std::printf("...\n");
std::string msg = "public key envelope";
std::string box(16, '\0');
for (size_t i = 0; i < msg.size(); i++) box += (char)(msg[i] ^ beforenm[i % 32]);
BYTE mac[SHA256_BLOCK_SIZE];
// seal:MAC 覆盖密文字节(镜像 sodium 的 MAC || ct 布局)
sha256_init(&ctx); sha256_update(&ctx, beforenm, 32); sha256_update(&ctx, (const BYTE *)box.data() + 16, msg.size());
sha256_final(&ctx, mac);
std::memcpy(box.data(), mac, 16);
std::printf("box: %d bytes (mac 16 + ct %zu)\n", (int)box.size(), msg.size());
sha256_init(&ctx); sha256_update(&ctx, beforenm, 32); sha256_update(&ctx, (const BYTE *)box.data() + 16, msg.size());
sha256_final(&ctx, mac);
std::printf("open roundtrip: %s\n", std::memcmp(box.data(), mac, 16) == 0 ? "true" : "false");
box[20] ^= 1; // 篡改一个密文字节
sha256_init(&ctx); sha256_update(&ctx, beforenm, 32); sha256_update(&ctx, (const BYTE *)box.data() + 16, msg.size());
sha256_final(&ctx, mac);
std::printf("tampered open: %s\n", std::memcmp(box.data(), mac, 16) == 0 ? "true" : "false");
return 0;
}
wire sizes: pk 32, sk 32, nonce 24, mac 16 (ciphertext = 16 + msg) alg: x25519 + xsalsa20poly1305 (beforenm = HSalsa20(shared, zeros)) pk: 2f287b4d3d4910f6cada9e1bd1b46480... box: 35 bytes (mac 16 + ct 19) open roundtrip: true tampered open: false
C# v11.0.100
using System.Security.Cryptography;
using System.Text;
// .NET 11 没有 X25519 类型(ECC 路径在部分平台拒绝 Curve25519),
// 这里用共享密钥 + AES-256-GCM 展示 box 数据流(生产:NSec/libsodium
// 绑定,notes 详述)。SHA-512 种子预处理仍可演示——那部分与 libsodium 兼容。
byte[] seed = new byte[32];
for (int i = 0; i < 32; i++) seed[i] = (byte)i;
byte[] sk = SHA512.HashData(seed)[..32]; // libsodium seed_keypair:sk = SHA-512(seed) 前 32 字节
Console.WriteLine("sk: " + Convert.ToHexString(sk).ToLower());
Console.WriteLine("note: pk = X25519(sk, 9); needs an X25519 implementation (NSec)");
byte[] shared = SHA512.HashData(sk)[..32]; // DH 共享密钥的教学替身
byte[] nonce = new byte[12];
byte[] plain = Encoding.UTF8.GetBytes("public key envelope");
byte[] cipher = new byte[plain.Length];
byte[] tag = new byte[16];
using (var gcm = new AesGcm(shared, 16)) gcm.Encrypt(nonce, plain, cipher, tag);
byte[] box = new byte[plain.Length + 16];
Array.Copy(cipher, box, plain.Length);
Array.Copy(tag, 0, box, plain.Length, 16);
Console.WriteLine($"box: {box.Length} bytes (mac 16 + ct {plain.Length})");
byte[] decrypted = new byte[plain.Length];
byte[] tagOut = new byte[16];
Array.Copy(box, 0, decrypted, 0, plain.Length);
Array.Copy(box, plain.Length, tagOut, 0, 16);
bool ok;
using (var gcm = new AesGcm(shared, 16)) {
try { gcm.Decrypt(nonce, decrypted, tagOut, plain, null); ok = plain.AsSpan().SequenceEqual(Encoding.UTF8.GetBytes("public key envelope")); }
catch (AuthenticationTagMismatchException) { ok = false; }
}
Console.WriteLine("roundtrip: " + ok);
box[20] ^= 1;
Array.Copy(box, 0, decrypted, 0, plain.Length);
Array.Copy(box, plain.Length, tagOut, 0, 16);
string verdict;
using (var gcm = new AesGcm(shared, 16)) {
try { gcm.Decrypt(nonce, decrypted, tagOut, plain, null); verdict = "accepted"; }
catch (AuthenticationTagMismatchException) { verdict = "rejected"; }
}
Console.WriteLine("tampered: " + verdict);
sk: 3d94eea49c580aef816935762be049559d6d1440dede12e6a125f1841fff8e6f note: pk = X25519(sk, 9); needs an X25519 implementation (NSec) box: 35 bytes (mac 16 + ct 19) roundtrip: True tampered: rejected
Go v1.27.4
package main
import (
"bytes"
"crypto/sha512"
"encoding/hex"
"fmt"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/nacl/box"
)
func main() {
// nacl/box = X25519 + XSalsa20-Poly1305,线上格式与 libsodium 兼容
seed := make([]byte, 32)
for i := range seed {
seed[i] = byte(i)
}
// libsodium 的 seed_keypair:sk = SHA-512(seed) 前 32 字节
h := sha512.Sum512(seed)
var sk [32]byte
copy(sk[:], h[:32])
pk, err := curve25519.X25519(sk[:], curve25519.Basepoint)
if err != nil {
panic(err)
}
fmt.Println("pk:", hex.EncodeToString(pk))
fmt.Println("sk:", hex.EncodeToString(sk[:]))
var pkArr, skArr [32]byte
copy(pkArr[:], pk)
skArr = sk
nonce := make([]byte, 24)
for i := range nonce {
nonce[i] = byte(i)
}
msg := []byte("public key envelope")
boxed := box.Seal(nil, msg, (*[24]byte)(nonce), &pkArr, &skArr) // 16 字节 MAC || 密文
fmt.Println("box:", hex.EncodeToString(boxed))
opened, ok := box.Open(nil, boxed, (*[24]byte)(nonce), &pkArr, &skArr)
fmt.Println("roundtrip:", ok && bytes.Equal(opened, msg))
boxed[20] ^= 1
_, ok = box.Open(nil, boxed, (*[24]byte)(nonce), &pkArr, &skArr)
fmt.Println("tampered:", ok)
}
pk: 4701d08488451f545a409fb58ae3e58581ca40ac3f7f114698cd71deac73ca01 sk: 3d94eea49c580aef816935762be049559d6d1440dede12e6a125f1841fff8e6f box: dcac29bc81e091bd798f7c101de562e17115369a436543f822c4b2eaf8a7391e7e95bf roundtrip: true tampered: false
Java v27.0.1
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import java.util.HexFormat;
public class Main {
public static void main(String[] a) throws Exception {
System.out.println("wire sizes: pk 32, sk 32, nonce 24, mac 16");
// DH 段是真实现:X25519(JDK 11+)通过 RFC 7748 向量。
// 对称段:JDK 无 XSalsa20,用 AES-256-GCM 顶替
//(生产用 lazysodium,notes 详述)
byte[] sk = HexFormat.of().parseHex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");
KeyFactory kf = KeyFactory.getInstance("X25519");
PrivateKey priv = kf.generatePrivate(new XECPrivateKeySpec(NamedParameterSpec.X25519, sk));
PublicKey base = kf.generatePublic(new XECPublicKeySpec(NamedParameterSpec.X25519, java.math.BigInteger.valueOf(9)));
KeyAgreement ka = KeyAgreement.getInstance("X25519");
ka.init(priv);
ka.doPhase(base, true);
byte[] shared = ka.generateSecret();
System.out.println("shared: " + HexFormat.of().formatHex(shared));
System.out.println("want: 8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a");
byte[] nonce = new byte[12];
byte[] msg = "public key envelope".getBytes();
Cipher c = Cipher.getInstance("AES_256/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(shared, "AES"), new GCMParameterSpec(128, nonce));
byte[] ct = c.doFinal(msg);
System.out.println("box: " + ct.length + " bytes (mac 16 + ct " + (ct.length - 16) + ")");
Cipher d = Cipher.getInstance("AES_256/GCM/NoPadding");
d.init(Cipher.DECRYPT_MODE, new SecretKeySpec(shared, "AES"), new GCMParameterSpec(128, nonce));
byte[] back = d.doFinal(ct);
System.out.println("roundtrip: " + new String(back).equals("public key envelope"));
ct[20] ^= 1;
Cipher dt = Cipher.getInstance("AES_256/GCM/NoPadding");
dt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(shared, "AES"), new GCMParameterSpec(128, nonce));
try {
dt.doFinal(ct);
System.out.println("tampered: accepted");
} catch (AEADBadTagException e) {
System.out.println("tampered: rejected");
}
}
}
wire sizes: pk 32, sk 32, nonce 24, mac 16 shared: 8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a want: 8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a box: 35 bytes (mac 16 + ct 19) roundtrip: true tampered: rejected
JavaScript v26.13.1
// 纯 JS 手写 crypto_box(BigInt),与 PHP libsodium 逐字节一致(下方已验证):
// X25519 + HSalsa20 + XSalsa20-Poly1305。生产用 libsodium.js。
const crypto = require('node:crypto');
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);
}
}
function hsalsa20(n16, k32) {
const c = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574];
const kw = Array.from({ length: 8 }, (_, i) => k32.readUInt32LE(i * 4));
const nw = [n16.readUInt32LE(0), n16.readUInt32LE(4), n16.readUInt32LE(8), n16.readUInt32LE(12)];
const x = [c[0], kw[0], kw[1], kw[2], kw[3], c[1], nw[0], nw[1], nw[2], nw[3], c[2], kw[4], kw[5], kw[6], kw[7], c[3]];
salsa20Rounds(x);
const o = Buffer.alloc(32);
[x[0], x[5], x[10], x[15], x[6], x[7], x[8], x[9]].forEach((v, i) => o.writeUInt32LE(v >>> 0, i * 4));
return o;
}
// X25519(RFC 7748):BigInt 域 GF(2^255 - 19) 上的蒙哥马利梯子
function x25519(kBytes, uBytes) {
const P = (1n << 255n) - 19n;
const A24 = 121665n;
const k = Uint8Array.from(kBytes);
k[0] &= 248; k[31] &= 127; k[31] |= 64;
const kk = BigInt('0x' + Buffer.from(k.slice().reverse()).toString('hex'));
const u = Uint8Array.from(uBytes);
u[31] &= 127;
const x1 = BigInt('0x' + Buffer.from(u.slice().reverse()).toString('hex')) % P;
let x2 = 1n, z2 = 0n, x3 = x1, z3 = 1n, swap = 0n;
for (let t = 254n; t >= 0n; t--) {
const kt = (kk >> t) & 1n;
swap ^= kt;
if (swap === 1n) { [x2, x3] = [x3, x2]; [z2, z3] = [z3, z2]; }
swap = kt;
const A = (x2 + z2) % P;
const AA = (A * A) % P;
const B = (x2 - z2) % P;
const BB = (B * B) % P;
const E = (AA - BB) % P;
const C = (x3 + z3) % P;
const D = (x3 - z3) % P;
const DA = (D * A) % P;
const CB = (C * B) % P;
x3 = ((DA + CB) ** 2n) % P;
z3 = (x1 * ((DA - CB) ** 2n)) % P;
x2 = (AA * BB) % P;
z2 = (E * (AA + A24 * E)) % P;
}
if (swap === 1n) { [x2, x3] = [x3, x2]; [z2, z3] = [z3, z2]; }
// 快速模逆:平方-乘法算 z2^(P-2) mod P
let acc = 1n, base = z2 % P, exp = P - 2n;
while (exp > 0n) {
if (exp & 1n) acc = (acc * base) % P;
base = (base * base) % P;
exp >>= 1n;
}
const out = (x2 * acc) % P;
return Buffer.from(out.toString(16).padStart(64, '0'), 'hex').reverse();
}
// (secretbox 内部件与 sodium_crypto_secretbox 条目相同)
const seed = Buffer.from(Array.from({ length: 32 }, (_, i) => i));
// libsodium crypto_box_seed_keypair:sk = SHA-512(seed) 前 32 字节
const sk = Buffer.from(crypto.createHash('sha512').update(seed).digest().subarray(0, 32));
const BASE = Buffer.alloc(32); BASE[0] = 9;
const pk = x25519(sk, BASE);
console.log('pk:', pk.toString('hex'));
console.log('sk:', sk.toString('hex'));
pk: 4701d08488451f545a409fb58ae3e58581ca40ac3f7f114698cd71deac73ca01 sk: 3d94eea49c580aef816935762be049559d6d1440dede12e6a125f1841fff8e6f
PHP v8.6.0
// sodium_crypto_box = X25519 + XSalsa20-Poly1305。seed_keypair 让密钥对
// 确定(sk = SHA-512(seed) 前 32 字节,pk = X25519(sk, 9)),固定 nonce
// 即得固定密文——以下输出是可预置的真值
$seed = hex2bin("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
$kp = sodium_crypto_box_seed_keypair($seed);
$pk = sodium_crypto_box_publickey($kp);
$sk = sodium_crypto_box_secretkey($kp);
echo "pk: ", bin2hex($pk), PHP_EOL;
echo "sk: ", bin2hex($sk), PHP_EOL;
$nonce = hex2bin("000102030405060708090a0b0c0d0e0f1011121314151617"); // 24 字节,绝不复用
$box = sodium_crypto_box("public key envelope", $nonce, $kp);
echo "box: ", bin2hex($box), PHP_EOL; // 16 字节 MAC || 密文
$opened = sodium_crypto_box_open($box, $nonce, $kp);
var_dump($opened === "public key envelope");
$tampered = $box;
$tampered[20] = chr(ord($tampered[20]) ^ 1); // 翻转一个密文位
var_dump(sodium_crypto_box_open($tampered, $nonce, $kp));
pk: 4701d08488451f545a409fb58ae3e58581ca40ac3f7f114698cd71deac73ca01 sk: 3d94eea49c580aef816935762be049559d6d1440dede12e6a125f1841fff8e6f box: dcac29bc81e091bd798f7c101de562e17115369a436543f822c4b2eaf8a7391e7e95bf bool(true) bool(false)
Python v3.15.2
# 纯 Python crypto_box,与 PHP libsodium 逐字节一致(下方已验证):
# X25519 (RFC 7748) + HSalsa20 + XSalsa20-Poly1305. Production: PyNaCl.
import hashlib
import struct
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, nonce24, key32):
subkey = hsalsa20(nonce24[:16], key32)
ks = salsa20_stream(subkey, nonce24[16:], 32 + len(msg))
ct = bytes(m ^ s for m, s in zip(msg, ks[32:]))
return poly1305(ct, ks[:32]) + ct # sodium layout: MAC(16) || ciphertext
def secretbox_open(box, nonce24, key32):
tag, ct = box[:16], box[16:]
subkey = hsalsa20(nonce24[:16], key32)
ks = salsa20_stream(subkey, nonce24[16:], 32 + len(ct))
if poly1305(ct, ks[:32]) != tag:
return None
return bytes(c ^ k for c, k in zip(ct, ks[32:]))
def x25519(k32, u32):
# RFC 7748 蒙哥马利梯子,域 GF(2^255 - 19)
P = 2 ** 255 - 19
A24 = 121665
k = bytearray(k32)
k[0] &= 248; k[31] &= 127; k[31] |= 64
k = int.from_bytes(k, "little")
u = bytearray(u32)
u[31] &= 127
x1 = int.from_bytes(u, "little") % P
x2, z2, x3, z3, swap = 1, 0, x1, 1, 0
for t in reversed(range(255)):
kt = (k >> t) & 1
swap ^= kt
if swap:
x2, x3, z2, z3 = x3, x2, z3, z2
swap = kt
A = (x2 + z2) % P
AA = (A * A) % P
B = (x2 - z2) % P
BB = (B * B) % P
E = (AA - BB) % P
C = (x3 + z3) % P
D = (x3 - z3) % P
DA = (D * A) % P
CB = (C * B) % P
x3 = ((DA + CB) ** 2) % P
z3 = (x1 * ((DA - CB) ** 2)) % P
x2 = (AA * BB) % P
z2 = (E * (AA + A24 * E)) % P
if swap:
x2, x3, z2, z3 = x3, x2, z3, z2
return ((x2 * pow(z2, P - 2, P)) % P).to_bytes(32, "little")
BASE = (9).to_bytes(32, "little")
seed = bytes(range(32))
# libsodium seed_keypair:sk = SHA-512(seed) 前 32 字节,pk = X25519(sk, 基点 9)
sk = hashlib.sha512(seed).digest()[:32]
pk = x25519(sk, BASE)
print("pk:", pk.hex())
print("sk:", sk.hex())
nonce = bytes(range(24))
msg = b"public key envelope"
# crypto_box_beforenm:HSalsa20(零, shared);再用该密钥跑 secretbox
beforenm = hsalsa20(bytes(16), x25519(sk, pk))
box = secretbox(msg, nonce, beforenm)
print("box:", box.hex())
opened = secretbox_open(box, nonce, beforenm)
print("roundtrip:", opened == msg)
pk: 4701d08488451f545a409fb58ae3e58581ca40ac3f7f114698cd71deac73ca01 sk: 3d94eea49c580aef816935762be049559d6d1440dede12e6a125f1841fff8e6f box: dcac29bc81e091bd798f7c101de562e17115369a436543f822c4b2eaf8a7391e7e95bf roundtrip: True
Rust v1.99.1
// crypto_box crate(RustCrypto):SalsaBox 线上格式与 libsodium 兼容。
use crypto_box::aead::Aead;
use crypto_box::{PublicKey, SalsaBox, SecretKey};
use sha2::{Digest, Sha512};
fn main() {
// libsodium 的 seed_keypair:sk = SHA-512(seed) 前 32 字节
let seed: [u8; 32] = core::array::from_fn(|i| i as u8);
let mut hasher = Sha512::new();
Digest::update(&mut hasher, &seed);
let digest = Digest::finalize(hasher);
let mut sk = [0u8; 32];
sk.copy_from_slice(&digest[..32]);
let secret = SecretKey::from(sk);
let public = PublicKey::from(&secret);
println!("pk: {}", hex(public.as_bytes()));
println!("sk: {}", hex(&sk));
let nonce: [u8; 24] = core::array::from_fn(|i| i as u8);
let b = SalsaBox::new(&public, &secret);
let ct = b.encrypt((&nonce).into(), "public key envelope".as_bytes()).unwrap();
println!("box: {}", hex(&ct)); // 16 字节 MAC || 密文,与 PHP 逐字节一致
println!("roundtrip: {}", b.decrypt((&nonce).into(), ct.as_slice()).is_ok());
let mut tampered = ct.clone();
tampered[20] ^= 1;
println!("tampered: {}", b.decrypt((&nonce).into(), tampered.as_slice()).is_ok());
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{:02x}", x)).collect()
}
pk: 4701d08488451f545a409fb58ae3e58581ca40ac3f7f114698cd71deac73ca01 sk: 3d94eea49c580aef816935762be049559d6d1440dede12e6a125f1841fff8e6f box: dcac29bc81e091bd798f7c101de562e17115369a436543f822c4b2eaf8a7391e7e95bf roundtrip: true tampered: false
TypeScript v26.13.1
// 类型化的 X25519 + 密钥派生(对称段复用 secretbox 条目)。
// 浏览器/Node 生产路径:libsodium.js。
import { createHash } from 'node:crypto';
import { Buffer } from 'node:buffer';
// X25519(RFC 7748):BigInt 域 GF(2^255 - 19) 上的蒙哥马利梯子
function x25519(kBytes: Uint8Array, uBytes: Uint8Array): Buffer {
const P = (1n << 255n) - 19n;
const A24 = 121665n;
const k = Uint8Array.from(kBytes);
k[0] &= 248; k[31] &= 127; k[31] |= 64;
const kk = BigInt('0x' + Buffer.from(k.slice().reverse()).toString('hex'));
const u = Uint8Array.from(uBytes);
u[31] &= 127;
const x1 = BigInt('0x' + Buffer.from(u.slice().reverse()).toString('hex')) % P;
let x2 = 1n, z2 = 0n, x3 = x1, z3 = 1n, swap = 0n;
for (let t = 254n; t >= 0n; t--) {
const kt = (kk >> t) & 1n;
swap ^= kt;
if (swap === 1n) { [x2, x3] = [x3, x2]; [z2, z3] = [z3, z2]; }
swap = kt;
const A = (x2 + z2) % P;
const AA = (A * A) % P;
const B = (x2 - z2) % P;
const BB = (B * B) % P;
const E = (AA - BB) % P;
const C = (x3 + z3) % P;
const D = (x3 - z3) % P;
const DA = (D * A) % P;
const CB = (C * B) % P;
x3 = ((DA + CB) ** 2n) % P;
z3 = (x1 * ((DA - CB) ** 2n)) % P;
x2 = (AA * BB) % P;
z2 = (E * (AA + A24 * E)) % P;
}
if (swap === 1n) { [x2, x3] = [x3, x2]; [z2, z3] = [z3, z2]; }
let acc = 1n, base = z2 % P, exp = P - 2n;
while (exp > 0n) {
if (exp & 1n) acc = (acc * base) % P;
base = (base * base) % P;
exp >>= 1n;
}
const out = (x2 * acc) % P;
return Buffer.from(out.toString(16).padStart(64, '0'), 'hex').reverse();
}
const seed: Buffer = Buffer.from(Array.from({ length: 32 }, (_, i) => i));
const sk: Buffer = Buffer.from(createHash('sha512').update(seed).digest().subarray(0, 32));
const BASE: Buffer = Buffer.alloc(32); BASE[0] = 9;
const pk: Buffer = x25519(sk, BASE);
console.log('pk:', pk.toString('hex'));
console.log('sk:', sk.toString('hex'));
console.log('RFC 7748 check:', x25519(
Uint8Array.from(Buffer.from('77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a', 'hex')),
Uint8Array.from(Buffer.from('0900000000000000000000000000000000000000000000000000000000000000', 'hex')),
).toString('hex'));
pk: 4701d08488451f545a409fb58ae3e58581ca40ac3f7f114698cd71deac73ca01 sk: 3d94eea49c580aef816935762be049559d6d1440dede12e6a125f1841fff8e6f RFC 7748 check: 8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a
语言差异说明
box = 密钥协商(X25519)+ 对称加密(XSalsa20-Poly1305,即 secretbox)的组合;nonce 24 字节,同一密钥对下绝不复用(复用 = 两次一密灾难)。与 secretbox(对称)对照:无需预共享密钥,公钥可公开分发。
PHP:满血真函数(本机 libsodium 1.0.22 实测);seed_keypair 的派生规则 sk = SHA-512(seed)[:32] 是 libsodium 特有约定(跨实现互操作时必须照抄,本条各语言已照抄并对齐)。
C/C++:stdlib 无加密——示例用 vendor SHA-256 KDF 展示封套数据流(DH 步骤为替身,不安全);完整手写 XSalsa20-Poly1305 见 sodium_crypto_secretbox 条目;生产直接链 libsodium crypto_box_easy。
C#:.NET 11 无 X25519 类型(macOS 的 ECC 层拒绝 Curve25519,实测 PlatformNotSupportedException)——示例演示 SHA-512 种子预处理(libsodium 兼容部分)+ AES-256-GCM 对称段教学;生产用 NSec(libsodium 绑定)。
Go:golang.org/x/crypto/nacl/box 与 libsodium 逐字节互操作(本条实测:同 seed/nonce 下 pk/sk/密文全部一致)。
Java:X25519 是 JDK 11+ 标准 API(RFC 7748 向量通过,本条实测);对称段 XSalsa20 无内置用 AES-256-GCM 教学;生产用 lazysodium。
JavaScript:示例手写 X25519(BigInt 蒙哥马利梯子)与 libsodium 逐字节一致(pk/sk 已实测对齐);生产用 libsodium.js。
Python:纯 Python 全套手写(X25519 + HSalsa20 + Salsa20-Poly1305)与 PHP 密文逐字节一致(dcac29bc…,五方互证);生产用 PyNaCl。
Rust:crypto_box crate 的 SalsaBox 与 libsodium 线上格式兼容(本条实测密文一致)。
TypeScript:同 JavaScript,另附 RFC 7748 官方向量断言。