test: the six mandatory tests, pinned KAT vectors, fuzz target and cargo-deny config (written before the code)

This commit is contained in:
2026-11-25 07:28:48 +01:00
parent ed9b8a3b17
commit c7d050ed65
21 changed files with 3726 additions and 0 deletions
Generated
+530
View File
@@ -0,0 +1,530 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aead"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "arcanum"
version = "0.1.0"
dependencies = [
"chacha20",
"chacha20poly1305",
"hex",
"hkdf",
"hmac",
"ml-kem",
"rand_core",
"serde",
"serde_json",
"sha2",
"sha3",
"shake",
"x-wing",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
"zeroize",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"rand_core",
"zeroize",
]
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead",
"chacha20",
"cipher",
"poly1305",
"zeroize",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"block-buffer",
"crypto-common",
"inout",
]
[[package]]
name = "cmov"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
"rand_core",
]
[[package]]
name = "ctutils"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"fiat-crypto",
"rustc_version",
"subtle",
"zeroize",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"ctutils",
"zeroize",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hkdf"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"ctutils",
"typenum",
"zeroize",
]
[[package]]
name = "inout"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
dependencies = [
"hybrid-array",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "keccak"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598"
dependencies = [
"cfg-if",
"cpufeatures",
]
[[package]]
name = "kem"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"
dependencies = [
"crypto-common",
"rand_core",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "ml-kem"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84ca78b66f46050d49fa21693ae8adab2081d8101b65d8067316b6b70b64a0d1"
dependencies = [
"hybrid-array",
"kem",
"module-lattice",
"rand_core",
"sha3",
"shake",
"zeroize",
]
[[package]]
name = "module-lattice"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a1e412c8ee83a1c678f427806219c49c96b2511b9f07497514f0e43fb26155"
dependencies = [
"ctutils",
"hybrid-array",
"num-traits",
"zeroize",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "poly1305"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures",
"universal-hash",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha3"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759"
dependencies = [
"digest",
"keccak",
"sponge-cursor",
]
[[package]]
name = "shake"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"
dependencies = [
"digest",
"keccak",
"sponge-cursor",
]
[[package]]
name = "sponge-cursor"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
dependencies = [
"zeroize",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "universal-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
dependencies = [
"crypto-common",
"ctutils",
]
[[package]]
name = "x-wing"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01576e56599d01d75c5efcd5b30fa5de29e776f5a225e43fbf8c92c7302d4c8b"
dependencies = [
"kem",
"ml-kem",
"sha3",
"shake",
"x25519-dalek",
]
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
"curve25519-dalek",
"rand_core",
"zeroize",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+38
View File
@@ -0,0 +1,38 @@
[package]
name = "arcanum"
version = "0.1.0"
edition = "2024"
rust-version = "1.88"
license = "CPAL-1.0"
description = "Hybrid post-quantum key exchange (X-Wing: ML-KEM-768 + X25519), key schedule, WireGuard PSK derivation and sealing for the Domi ecosystem"
repository = "https://gitea.marek-novak.cz/mnovak/arcanum"
readme = "README.md"
publish = false
[dependencies]
# Primitives: every one from a vetted crate, none written here (docs/01_arcanum.md).
ml-kem = { version = "=0.3.4", default-features = false, features = ["zeroize"] }
x25519-dalek = { version = "=3.0.0", default-features = false, features = ["static_secrets", "zeroize"] }
sha3 = { version = "0.12", default-features = false, features = ["zeroize"] }
shake = { version = "0.1", default-features = false, features = ["zeroize"] }
sha2 = { version = "0.11", default-features = false, features = ["zeroize"] }
hkdf = { version = "0.13", default-features = false }
hmac = { version = "0.13", default-features = false, features = ["zeroize"] }
chacha20poly1305 = { version = "0.11", default-features = false, features = ["alloc", "zeroize"] }
rand_core = { version = "0.10", default-features = false }
zeroize = { version = "1.8", default-features = false, features = ["alloc", "zeroize_derive"] }
[dev-dependencies]
# Reference implementation for the differential test only; never linked into the library.
x-wing = { version = "=0.1.1" }
chacha20 = { version = "0.10", default-features = false, features = ["rng"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
hex = "0.4"
sha2 = "0.11"
# ML-KEM in a debug build is slow; the byte-flip tests run thousands of exchanges.
[profile.dev.package."*"]
opt-level = 2
[profile.test.package."*"]
opt-level = 2
+36
View File
@@ -0,0 +1,36 @@
# cargo deny configuration for Arcanum (mandatory test 6). Run: cargo deny check
[graph]
all-features = true
[advisories]
# Every RustSec advisory, including unmaintained and unsound crates, is an error.
version = 2
yanked = "deny"
ignore = []
[licenses]
version = 2
# Licences of the dependency tree; each was checked against the crates' own LICENSE files.
allow = [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"Unicode-3.0",
]
confidence-threshold = 0.9
[licenses.private]
ignore = true
[bans]
multiple-versions = "deny"
wildcards = "deny"
highlight = "all"
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
allow-git = []
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "arcanum-fuzz"
version = "0.0.0"
edition = "2024"
license = "CPAL-1.0"
publish = false
[package.metadata]
cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
arcanum = { path = ".." }
# Keep the fuzz crate out of the library's own dependency graph and checks.
[workspace]
members = ["."]
[[bin]]
name = "untrusted_input"
path = "fuzz_targets/untrusted_input.rs"
test = false
doc = false
bench = false
+78
View File
@@ -0,0 +1,78 @@
//! Mandatory test 5, fuzzed: every entry point that takes bytes from the network must return a
//! typed result for any input, and never panic.
//!
//! The first byte picks the mode. Modes 0-3 parse raw bytes. Modes 4-6 XOR the input into a valid
//! public key, ciphertext or sealed box, so the fuzzer reaches decapsulation and the AEAD instead
//! of stopping at the length checks.
#![no_main]
use arcanum::xwing::{Ciphertext, PublicKey, SecretKey};
use arcanum::{exchange, seal};
use libfuzzer_sys::fuzz_target;
const SEED: [u8; 32] = [0x42; 32];
const ESEED: [u8; 64] = [0x24; 64];
fn xor_into(base: &[u8], data: &[u8]) -> Vec<u8> {
let mut out = base.to_vec();
for (i, b) in data.iter().enumerate() {
if i < out.len() {
out[i] ^= b;
} else {
out.push(*b);
}
}
out
}
fuzz_target!(|input: &[u8]| {
let Some((&mode, data)) = input.split_first() else { return };
let sk = SecretKey::from_seed(SEED);
match mode % 7 {
0 => {
if let Ok(pk) = PublicKey::from_bytes(data) {
let _ = exchange::initiate_derand(&pk, b"fuzz", &ESEED);
}
}
1 => {
if let Ok(ct) = Ciphertext::from_bytes(data) {
let _ = exchange::respond(&sk, &ct, b"fuzz");
}
}
2 => {
let _ = seal::open(&sk, data, b"fuzz");
}
3 => {
if let Ok(k) = SecretKey::from_bytes(data) {
let _ = k.public_key().as_bytes();
}
}
4 => {
let pk = xor_into(sk.public_key().as_bytes(), data);
if let Ok(pk) = PublicKey::from_bytes(&pk) {
let _ = exchange::initiate_derand(&pk, b"fuzz", &ESEED);
}
}
5 => {
let (ct, honest) = exchange::initiate_derand(sk.public_key(), b"fuzz", &ESEED).unwrap();
let bad = xor_into(ct.as_bytes(), data);
if let Ok(bad) = Ciphertext::from_bytes(&bad) {
if let Ok(s) = exchange::respond(&sk, &bad, b"fuzz") {
// Only an unchanged ciphertext may reproduce the honest PSK.
if bad.as_bytes() != ct.as_bytes() {
assert_ne!(s.wireguard_psk(0).as_bytes(), honest.wireguard_psk(0).as_bytes());
}
}
}
}
_ => {
let sealed = seal::seal_derand(sk.public_key(), b"fuzz plaintext", b"fuzz", &ESEED).unwrap();
let bad = xor_into(&sealed, data);
if let Ok(pt) = seal::open(&sk, &bad, b"fuzz") {
// Only the unchanged box may open.
assert_eq!(bad, sealed);
assert_eq!(pt.as_slice(), b"fuzz plaintext");
}
}
}
});
+2
View File
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"
+68
View File
@@ -0,0 +1,68 @@
//! Mandatory test 3, at the combiner: replacing either component secret by zeros must change the
//! output, so both halves are bound. These are unit tests because the combiner is crate-private
//! (exposing it would invite misuse).
use crate::schedule::session_prk;
use crate::xwing::{SHARED_SECRET_LEN, combiner};
const SS_M: [u8; 32] = [0xa1; 32];
const SS_X: [u8; 32] = [0xb2; 32];
const CT_X: [u8; 32] = [0xc3; 32];
const PK_X: [u8; 32] = [0xd4; 32];
const ZERO: [u8; SHARED_SECRET_LEN] = [0; SHARED_SECRET_LEN];
#[test]
fn zeroing_the_ml_kem_secret_changes_the_output() {
let honest = combiner(&SS_M, &SS_X, &CT_X, &PK_X);
assert_ne!(combiner(&ZERO, &SS_X, &CT_X, &PK_X), honest);
}
#[test]
fn zeroing_the_x25519_secret_changes_the_output() {
let honest = combiner(&SS_M, &SS_X, &CT_X, &PK_X);
assert_ne!(combiner(&SS_M, &ZERO, &CT_X, &PK_X), honest);
}
#[test]
fn zeroing_both_differs_from_zeroing_either() {
let only_m = combiner(&ZERO, &SS_X, &CT_X, &PK_X);
let only_x = combiner(&SS_M, &ZERO, &CT_X, &PK_X);
let both = combiner(&ZERO, &ZERO, &CT_X, &PK_X);
assert_ne!(only_m, only_x);
assert_ne!(both, only_m);
assert_ne!(both, only_x);
}
/// Swapping the two secrets must not give the same output: the positions are bound, not just the set.
#[test]
fn the_two_halves_are_not_interchangeable() {
assert_ne!(combiner(&SS_M, &SS_X, &CT_X, &PK_X), combiner(&SS_X, &SS_M, &CT_X, &PK_X));
}
/// Every single bit of either component secret reaches the output.
#[test]
fn every_bit_of_each_component_reaches_the_output() {
let honest = combiner(&SS_M, &SS_X, &CT_X, &PK_X);
for byte in 0..32 {
for bit in 0..8 {
let mut m = SS_M;
m[byte] ^= 1 << bit;
assert_ne!(combiner(&m, &SS_X, &CT_X, &PK_X), honest, "ss_M byte {byte} bit {bit}");
let mut x = SS_X;
x[byte] ^= 1 << bit;
assert_ne!(combiner(&SS_M, &x, &CT_X, &PK_X), honest, "ss_X byte {byte} bit {bit}");
}
}
}
/// The binding survives the key schedule: a zeroed component gives a different session key too.
#[test]
fn zeroed_components_give_a_different_session() {
let pk = [0x5a; crate::xwing::PUBLIC_KEY_LEN];
let ct = [0x6b; crate::xwing::CIPHERTEXT_LEN];
let honest = session_prk(&combiner(&SS_M, &SS_X, &CT_X, &PK_X), &pk, &ct, b"ctx");
let no_m = session_prk(&combiner(&ZERO, &SS_X, &CT_X, &PK_X), &pk, &ct, b"ctx");
let no_x = session_prk(&combiner(&SS_M, &ZERO, &CT_X, &PK_X), &pk, &ct, b"ctx");
assert_ne!(*honest, *no_m);
assert_ne!(*honest, *no_x);
}
+1
View File
@@ -0,0 +1 @@
+58
View File
@@ -0,0 +1,58 @@
//! Mandatory test 3, through the public API: an attacker can force the X25519 half to zero by
//! sending a low-order point. Arcanum must refuse that with a typed error instead of producing a
//! secret that only one half protects. (The combiner-level half of test 3, which zeroes each
//! component directly, is `src/binding_tests.rs`.)
use arcanum::Error;
use arcanum::exchange;
use arcanum::xwing::{Ciphertext, PublicKey, SecretKey};
/// Curve25519 u-coordinates of small order, and non-canonical encodings of them (the list
/// libsodium rejects). X25519 of any of these with any clamped scalar is all zeros.
const LOW_ORDER: [&str; 7] = [
"0000000000000000000000000000000000000000000000000000000000000000",
"0100000000000000000000000000000000000000000000000000000000000000",
"e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",
"5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
];
fn low_order_points() -> impl Iterator<Item = [u8; 32]> {
LOW_ORDER.iter().map(|h| hex::decode(h).unwrap().try_into().unwrap())
}
#[test]
fn low_order_x25519_ciphertext_is_refused_by_the_responder() {
let sk = SecretKey::from_seed([0x44; 32]);
let (ct, _) = exchange::initiate_derand(sk.public_key(), b"ctx", &[0x55; 64]).unwrap();
for point in low_order_points() {
let mut bad = *ct.as_bytes();
bad[1088..].copy_from_slice(&point);
let bad = Ciphertext::from_bytes(&bad).unwrap();
assert_eq!(exchange::respond(&sk, &bad, b"ctx").err(), Some(Error::NonContributory));
assert_eq!(sk.decapsulate(&bad).err(), Some(Error::NonContributory));
}
}
#[test]
fn low_order_x25519_public_key_is_refused_by_the_initiator() {
let sk = SecretKey::from_seed([0x44; 32]);
for point in low_order_points() {
let mut bad = *sk.public_key().as_bytes();
bad[1184..].copy_from_slice(&point);
let pk = PublicKey::from_bytes(&bad).expect("the ML-KEM part is still valid");
assert_eq!(exchange::initiate_derand(&pk, b"ctx", &[0x55; 64]).err(), Some(Error::NonContributory));
assert_eq!(pk.encapsulate_derand(&[0x55; 64]).err(), Some(Error::NonContributory));
}
}
/// The honest exchange is not affected by the check: the same keys with honest points still agree.
#[test]
fn honest_points_pass_the_check() {
let sk = SecretKey::from_seed([0x44; 32]);
let (ct, a) = exchange::initiate_derand(sk.public_key(), b"ctx", &[0x55; 64]).unwrap();
let b = exchange::respond(&sk, &ct, b"ctx").unwrap();
assert_eq!(a.wireguard_psk(3).as_bytes(), b.wireguard_psk(3).as_bytes());
}
+25
View File
@@ -0,0 +1,25 @@
//! Helpers shared by the integration tests. Test fixtures only: no real keys, no network.
#![allow(dead_code)]
use chacha20::ChaCha20Rng;
use rand_core::SeedableRng;
use sha2::{Digest, Sha256};
/// A deterministic RNG for tests. Never used outside tests.
pub fn rng(label: u8) -> ChaCha20Rng {
ChaCha20Rng::from_seed([label; 32])
}
pub fn hex(s: &str) -> Vec<u8> {
hex::decode(s).expect("vector hex")
}
pub fn arr<const N: usize>(s: &str) -> [u8; N] {
hex(s).try_into().expect("vector length")
}
/// Fail loudly if a pinned vector file is not the one recorded in tests/vectors/SOURCES.md.
pub fn assert_sha256(bytes: &[u8], expected_hex: &str, name: &str) {
let got = hex::encode(Sha256::digest(bytes));
assert_eq!(got, expected_hex, "{name} is not the pinned file (see tests/vectors/SOURCES.md)");
}
+145
View File
@@ -0,0 +1,145 @@
//! Mandatory test 2: both sides of a hybrid exchange derive the same secret, and changing any
//! single input byte changes it.
//!
//! The inputs of one exchange are: the responder's seed, the initiator's encapsulation seed, the
//! responder's public key (as the initiator received it), the ciphertext (as the responder
//! received it), and the context each side passes. Every byte of the public key, the ciphertext,
//! the seeds and the context is flipped in turn.
mod common;
use arcanum::exchange::{self, Session};
use arcanum::xwing::{CIPHERTEXT_LEN, Ciphertext, PUBLIC_KEY_LEN, PublicKey, SecretKey};
use common::rng;
use std::collections::HashSet;
const SEED: [u8; 32] = [0x11; 32];
const ESEED: [u8; 64] = [0x22; 64];
const CONTEXT: &[u8] = b"via/test: device-a <-> device-b";
fn honest() -> ([u8; 32], Ciphertext) {
let sk = SecretKey::from_seed(SEED);
let (ct, session) = exchange::initiate_derand(sk.public_key(), CONTEXT, &ESEED).unwrap();
(*session.wireguard_psk(0).as_bytes(), ct)
}
fn psk(session: &Session) -> [u8; 32] {
*session.wireguard_psk(0).as_bytes()
}
#[test]
fn both_sides_derive_the_same_secret() {
let mut r = rng(1);
for _ in 0..32 {
let sk = SecretKey::generate(&mut r);
let (ct, initiator) = exchange::initiate(sk.public_key(), CONTEXT, &mut r).unwrap();
let responder = exchange::respond(&sk, &ct, CONTEXT).unwrap();
for epoch in [0, 1, 7, u64::MAX] {
assert_eq!(initiator.wireguard_psk(epoch).as_bytes(), responder.wireguard_psk(epoch).as_bytes());
}
}
}
#[test]
fn both_sides_agree_after_the_public_key_and_ciphertext_go_through_bytes() {
let sk = SecretKey::from_seed(SEED);
let pk = PublicKey::from_bytes(sk.public_key().as_bytes()).unwrap();
let (ct, initiator) = exchange::initiate_derand(&pk, CONTEXT, &ESEED).unwrap();
let ct = Ciphertext::from_bytes(ct.as_bytes()).unwrap();
let responder = exchange::respond(&sk, &ct, CONTEXT).unwrap();
assert_eq!(psk(&initiator), psk(&responder));
}
#[test]
fn fresh_randomness_gives_a_fresh_secret() {
let mut r = rng(2);
let sk = SecretKey::generate(&mut r);
let mut seen = HashSet::new();
for _ in 0..64 {
let (_, s) = exchange::initiate(sk.public_key(), CONTEXT, &mut r).unwrap();
assert!(seen.insert(psk(&s)), "two exchanges produced the same secret");
}
}
#[test]
fn every_ciphertext_byte_changes_the_responders_secret() {
let (honest_psk, ct) = honest();
let sk = SecretKey::from_seed(SEED);
let mut accepted = 0;
for i in 0..CIPHERTEXT_LEN {
let mut bad = *ct.as_bytes();
bad[i] ^= 0x01;
let bad = Ciphertext::from_bytes(&bad).unwrap();
// A refusal (a low-order X25519 value) is also "not the honest secret".
if let Ok(s) = exchange::respond(&sk, &bad, CONTEXT) {
assert_ne!(psk(&s), honest_psk, "ciphertext byte {i} did not change the secret");
accepted += 1;
}
}
assert!(accepted > CIPHERTEXT_LEN - 32, "flipped ciphertexts must mostly decapsulate (implicit rejection)");
}
#[test]
fn every_public_key_byte_changes_the_initiators_secret() {
let (honest_psk, _) = honest();
let sk = SecretKey::from_seed(SEED);
let mut refused = 0;
for i in 0..PUBLIC_KEY_LEN {
let mut bad = *sk.public_key().as_bytes();
bad[i] ^= 0x01;
// A flipped ML-KEM coefficient can fail the FIPS 203 modulus check: refused, not accepted.
let Ok(pk) = PublicKey::from_bytes(&bad) else {
refused += 1;
continue;
};
match exchange::initiate_derand(&pk, CONTEXT, &ESEED) {
Ok((_, s)) => assert_ne!(psk(&s), honest_psk, "public key byte {i} did not change the secret"),
Err(_) => refused += 1,
}
}
assert!(refused < PUBLIC_KEY_LEN, "most flipped keys still parse; the test must exercise them");
}
#[test]
fn every_seed_byte_changes_the_secret() {
let (honest_psk, _) = honest();
for i in 0..32 {
let mut seed = SEED;
seed[i] ^= 0x01;
let sk = SecretKey::from_seed(seed);
let (_, s) = exchange::initiate_derand(sk.public_key(), CONTEXT, &ESEED).unwrap();
assert_ne!(psk(&s), honest_psk, "seed byte {i}");
}
for i in 0..64 {
let mut eseed = ESEED;
eseed[i] ^= 0x01;
let sk = SecretKey::from_seed(SEED);
let (_, s) = exchange::initiate_derand(sk.public_key(), CONTEXT, &eseed).unwrap();
assert_ne!(psk(&s), honest_psk, "eseed byte {i}");
}
}
#[test]
fn every_context_byte_changes_the_secret_and_a_mismatch_disagrees() {
let (honest_psk, ct) = honest();
let sk = SecretKey::from_seed(SEED);
for i in 0..CONTEXT.len() {
let mut ctx = CONTEXT.to_vec();
ctx[i] ^= 0x01;
let s = exchange::respond(&sk, &ct, &ctx).unwrap();
assert_ne!(psk(&s), honest_psk, "context byte {i}");
}
// Length is bound too: a prefix or an extension of the context is a different context.
for ctx in [&CONTEXT[..CONTEXT.len() - 1], b"", &[CONTEXT, b"\0"].concat()[..]] {
let s = exchange::respond(&sk, &ct, ctx).unwrap();
assert_ne!(psk(&s), honest_psk);
}
}
#[test]
fn the_wrong_secret_key_does_not_agree() {
let (honest_psk, ct) = honest();
let other = SecretKey::from_seed([0x33; 32]);
let s = exchange::respond(&other, &ct, CONTEXT).unwrap();
assert_ne!(psk(&s), honest_psk);
}
+130
View File
@@ -0,0 +1,130 @@
//! Mandatory test 1a: ML-KEM-768 known-answer tests from NIST ACVP (FIPS 203).
//!
//! Runs the vetted `ml-kem` crate, exactly as Arcanum uses it, against the official vectors.
//! Provenance and sha256 pins: tests/vectors/SOURCES.md.
mod common;
use common::{assert_sha256, hex};
#[allow(deprecated)]
use ml_kem::ExpandedKeyEncoding;
use ml_kem::array::Array;
use ml_kem::{B32, Decapsulate, DecapsulationKey, EncapsulationKey, KeyExport, MlKem768, Seed};
use serde_json::Value;
const KEYGEN: &[u8] = include_bytes!("vectors/acvp-ml-kem-keyGen-FIPS203-internalProjection.json");
const KEYGEN_SHA256: &str = "d7a62a2c3476957f56dd8d24f9004ea6776ccfe995ffe71a65bb9506dc9c7b1b";
const ENCDEC: &[u8] = include_bytes!("vectors/acvp-ml-kem-encapDecap-FIPS203-internalProjection.json");
const ENCDEC_SHA256: &str = "a556952ce869bb89c3a3196a701dad89647c193a34c86eafb61a9d710d5b810f";
/// The ML-KEM-768 test groups for one `function` ("" for keyGen, which has none).
fn groups(file: &[u8], function: &str) -> Vec<Value> {
let v: Value = serde_json::from_slice(file).expect("ACVP json");
v["testGroups"]
.as_array()
.expect("testGroups")
.iter()
.filter(|g| g["parameterSet"] == "ML-KEM-768")
.filter(|g| g["function"].as_str().unwrap_or("") == function)
.cloned()
.collect()
}
fn tests_of(groups: &[Value]) -> Vec<Value> {
groups.iter().flat_map(|g| g["tests"].as_array().expect("tests").clone()).collect()
}
fn field(t: &Value, name: &str) -> Vec<u8> {
hex(t[name].as_str().unwrap_or_else(|| panic!("field {name}")))
}
fn ek_from(bytes: &[u8]) -> Result<EncapsulationKey<MlKem768>, ml_kem::InvalidKey> {
let arr = Array::try_from(bytes).expect("ek length");
EncapsulationKey::<MlKem768>::new(&arr)
}
#[allow(deprecated)]
fn dk_from_expanded(bytes: &[u8]) -> Result<DecapsulationKey<MlKem768>, ml_kem::InvalidKey> {
let arr = Array::try_from(bytes).expect("dk length");
DecapsulationKey::<MlKem768>::from_expanded_bytes(&arr)
}
#[test]
fn vector_files_are_the_pinned_ones() {
assert_sha256(KEYGEN, KEYGEN_SHA256, "ACVP keyGen");
assert_sha256(ENCDEC, ENCDEC_SHA256, "ACVP encapDecap");
}
#[test]
#[allow(deprecated)]
fn acvp_keygen_768() {
let tests = tests_of(&groups(KEYGEN, ""));
assert_eq!(tests.len(), 25, "ACVP keyGen ML-KEM-768 has 25 cases");
for t in &tests {
let mut seed = field(t, "d");
seed.extend(field(t, "z"));
let dk = DecapsulationKey::<MlKem768>::from_seed(Seed::try_from(seed.as_slice()).unwrap());
assert_eq!(dk.encapsulation_key().to_bytes().as_slice(), field(t, "ek").as_slice(), "tcId {}", t["tcId"]);
assert_eq!(dk.to_expanded_bytes().as_slice(), field(t, "dk").as_slice(), "tcId {}", t["tcId"]);
}
}
#[test]
fn acvp_encapsulation_768() {
let tests = tests_of(&groups(ENCDEC, "encapsulation"));
assert_eq!(tests.len(), 25);
for t in &tests {
let ek = ek_from(&field(t, "ek")).expect("valid ek");
let m = B32::try_from(field(t, "m").as_slice()).unwrap();
let (c, k) = ek.encapsulate_deterministic(&m);
assert_eq!(c.as_slice(), field(t, "c").as_slice(), "tcId {}", t["tcId"]);
assert_eq!(k.as_slice(), field(t, "k").as_slice(), "tcId {}", t["tcId"]);
}
}
/// Includes "modified ciphertext" cases: implicit rejection must return the vector's K-bar.
#[test]
fn acvp_decapsulation_768_including_implicit_rejection() {
let tests = tests_of(&groups(ENCDEC, "decapsulation"));
assert_eq!(tests.len(), 10);
let mut modified = 0;
for t in &tests {
let dk = dk_from_expanded(&field(t, "dk")).expect("valid dk");
let c = Array::try_from(field(t, "c").as_slice()).unwrap();
let k = dk.decapsulate(&c);
assert_eq!(k.as_slice(), field(t, "k").as_slice(), "tcId {}", t["tcId"]);
if t["reason"] == "modified ciphertext" {
modified += 1;
}
}
assert!(modified > 0, "the set must exercise implicit rejection");
}
/// FIPS 203 §7.2 encapsulation key check: the modulus check must reject the bad keys.
#[test]
fn acvp_encapsulation_key_check_768() {
let tests = tests_of(&groups(ENCDEC, "encapsulationKeyCheck"));
assert_eq!(tests.len(), 10);
let mut rejected = 0;
for t in &tests {
let expected = t["testPassed"].as_bool().unwrap();
assert_eq!(ek_from(&field(t, "ek")).is_ok(), expected, "tcId {} ({})", t["tcId"], t["reason"]);
// Arcanum's own parser must agree: a hybrid key built on a bad ML-KEM key is refused.
let mut hybrid = field(t, "ek");
hybrid.extend([9u8; 32]);
assert_eq!(arcanum::xwing::PublicKey::from_bytes(&hybrid).is_ok(), expected, "tcId {}", t["tcId"]);
rejected += usize::from(!expected);
}
assert!(rejected > 0, "the set must contain keys that fail the check");
}
/// FIPS 203 §7.3 decapsulation key check (hash of ek inside dk).
#[test]
fn acvp_decapsulation_key_check_768() {
let tests = tests_of(&groups(ENCDEC, "decapsulationKeyCheck"));
assert_eq!(tests.len(), 10);
for t in &tests {
let expected = t["testPassed"].as_bool().unwrap();
assert_eq!(dk_from_expanded(&field(t, "dk")).is_ok(), expected, "tcId {} ({})", t["tcId"], t["reason"]);
}
}
+66
View File
@@ -0,0 +1,66 @@
//! Mandatory test 1b: X25519 known-answer tests from RFC 7748 (§5.2 and §6.1).
//!
//! Runs the vetted `x25519-dalek` crate, exactly as Arcanum uses it. The bytes are the RFC's; the
//! same values are in x25519-dalek 3.0.0's own tests (tests/vectors/SOURCES.md).
mod common;
use common::arr;
use x25519_dalek::{PublicKey, StaticSecret, X25519_BASEPOINT_BYTES, x25519};
#[test]
fn rfc7748_5_2_vector_1() {
let k = arr("a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4");
let u = arr("e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c");
let out: [u8; 32] = arr("c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552");
assert_eq!(x25519(k, u), out);
}
#[test]
fn rfc7748_5_2_vector_2() {
let k = arr("4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d");
let u = arr("e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493");
let out: [u8; 32] = arr("95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957");
assert_eq!(x25519(k, u), out);
}
/// RFC 7748 §5.2 iteration: k = u = 9; each step u <- k, k <- X25519(k, u).
fn iterate(n: usize) -> [u8; 32] {
let mut k = X25519_BASEPOINT_BYTES;
let mut u = X25519_BASEPOINT_BYTES;
for _ in 0..n {
let next = x25519(k, u);
u = k;
k = next;
}
k
}
#[test]
fn rfc7748_5_2_iterated_once() {
let expected: [u8; 32] = arr("422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079");
assert_eq!(iterate(1), expected);
}
#[test]
fn rfc7748_5_2_iterated_1000() {
let expected: [u8; 32] = arr("684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51");
assert_eq!(iterate(1000), expected);
}
/// RFC 7748 §6.1, through the same `StaticSecret` / `PublicKey` types Arcanum uses.
#[test]
fn rfc7748_6_1_diffie_hellman() {
let alice_sk: [u8; 32] = arr("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");
let alice_pk: [u8; 32] = arr("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a");
let bob_sk: [u8; 32] = arr("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb");
let bob_pk: [u8; 32] = arr("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f");
let shared: [u8; 32] = arr("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742");
let a = StaticSecret::from(alice_sk);
let b = StaticSecret::from(bob_sk);
assert_eq!(PublicKey::from(&a).as_bytes(), &alice_pk);
assert_eq!(PublicKey::from(&b).as_bytes(), &bob_pk);
assert_eq!(a.diffie_hellman(&PublicKey::from(bob_pk)).as_bytes(), &shared);
assert_eq!(b.diffie_hellman(&PublicKey::from(alice_pk)).as_bytes(), &shared);
}
+82
View File
@@ -0,0 +1,82 @@
//! Mandatory test 1c: X-Wing known-answer tests (draft-connolly-cfrg-xwing-kem-11, Appendix C)
//! through Arcanum's own composition, plus a differential test against RustCrypto `x-wing` 0.1.1.
mod common;
use arcanum::xwing::{Ciphertext, PublicKey, SecretKey};
use common::{assert_sha256, hex, rng};
use rand_core::Rng;
use serde::Deserialize;
use x_wing::{Decapsulate, Decapsulator, KeyExport};
const VECTORS: &[u8] = include_bytes!("vectors/xwing-test-vectors.json");
const VECTORS_SHA256: &str = "409efe197550b22985b4a0419418a0c5f2c2b193426c55bd998399ec8d3e614d";
#[derive(Deserialize)]
struct Vector {
seed: String,
sk: String,
pk: String,
eseed: String,
ct: String,
ss: String,
}
fn vectors() -> Vec<Vector> {
assert_sha256(VECTORS, VECTORS_SHA256, "X-Wing vectors");
serde_json::from_slice(VECTORS).expect("X-Wing json")
}
#[test]
fn draft_11_vectors() {
let vs = vectors();
assert_eq!(vs.len(), 3, "draft -11 Appendix C has three vectors");
for (i, v) in vs.iter().enumerate() {
let seed: [u8; 32] = hex(&v.seed).try_into().unwrap();
let sk = SecretKey::from_seed(seed);
assert_eq!(sk.to_seed().as_slice(), hex(&v.sk).as_slice(), "vector {i}: sk");
assert_eq!(sk.public_key().as_bytes().as_slice(), hex(&v.pk).as_slice(), "vector {i}: pk");
let pk = PublicKey::from_bytes(&hex(&v.pk)).expect("vector pk parses");
let eseed: [u8; 64] = hex(&v.eseed).try_into().unwrap();
let (ct, ss) = pk.encapsulate_derand(&eseed).expect("vector encapsulates");
assert_eq!(ct.as_bytes().as_slice(), hex(&v.ct).as_slice(), "vector {i}: ct");
assert_eq!(ss.as_bytes().as_slice(), hex(&v.ss).as_slice(), "vector {i}: ss (encaps)");
let ct = Ciphertext::from_bytes(&hex(&v.ct)).expect("vector ct parses");
let ss = sk.decapsulate(&ct).expect("vector decapsulates");
assert_eq!(ss.as_bytes().as_slice(), hex(&v.ss).as_slice(), "vector {i}: ss (decaps)");
}
}
/// Arcanum and the RustCrypto reference must agree on keys, ciphertexts and secrets for random
/// inputs, and on the implicit-rejection output for random (garbage) ML-KEM ciphertexts.
#[test]
fn differential_against_rustcrypto_x_wing() {
let mut r = rng(7);
for round in 0..64 {
let mut seed = [0u8; 32];
r.fill_bytes(&mut seed);
let mut eseed = [0u8; 64];
r.fill_bytes(&mut eseed);
let ours = SecretKey::from_seed(seed);
let theirs = x_wing::DecapsulationKey::from(seed);
let their_pk = theirs.encapsulation_key().to_bytes();
assert_eq!(ours.public_key().as_bytes().as_slice(), their_pk.as_slice(), "round {round}: pk");
let (our_ct, our_ss) = ours.public_key().encapsulate_derand(&eseed).unwrap();
let their_ek = x_wing::EncapsulationKey::try_from(their_pk.as_slice()).unwrap();
let (their_ct, their_ss) = their_ek.encapsulate_deterministic(&eseed.into());
assert_eq!(our_ct.as_bytes().as_slice(), their_ct.as_slice(), "round {round}: ct");
assert_eq!(our_ss.as_bytes().as_slice(), their_ss.as_slice(), "round {round}: ss");
// A ciphertext whose ML-KEM part is random bytes, with an honest X25519 part.
let mut garbage = *our_ct.as_bytes();
r.fill_bytes(&mut garbage[..1088]);
let ours_ss = ours.decapsulate(&Ciphertext::from_bytes(&garbage).unwrap()).unwrap();
let theirs_ss = theirs.decapsulate(&garbage.into());
assert_eq!(ours_ss.as_bytes().as_slice(), theirs_ss.as_slice(), "round {round}: implicit rejection");
assert_ne!(ours_ss.as_bytes(), our_ss.as_bytes(), "round {round}: garbage must not decapsulate");
}
}
+131
View File
@@ -0,0 +1,131 @@
//! Mandatory test 5: malformed ciphertexts and keys of the wrong length are rejected with typed
//! errors, never a panic. The same entry points are fuzzed by fuzz/fuzz_targets/untrusted_input.rs.
mod common;
use arcanum::xwing::{CIPHERTEXT_LEN, Ciphertext, PUBLIC_KEY_LEN, PublicKey, SECRET_KEY_LEN, SecretKey};
use arcanum::{Error, Input, exchange, seal};
use common::rng;
use rand_core::Rng;
const LENGTHS: [usize; 12] = [0, 1, 31, 32, 33, 64, 1087, 1088, 1119, 1121, 1215, 1217];
#[test]
fn public_key_of_the_wrong_length_is_a_typed_error() {
for len in LENGTHS.into_iter().chain([PUBLIC_KEY_LEN * 2]) {
let err = PublicKey::from_bytes(&vec![0u8; len]).unwrap_err();
assert_eq!(err, Error::InvalidLength { input: Input::PublicKey, expected: PUBLIC_KEY_LEN, actual: len });
}
}
#[test]
fn ciphertext_of_the_wrong_length_is_a_typed_error() {
for len in LENGTHS.into_iter().filter(|&l| l != CIPHERTEXT_LEN).chain([CIPHERTEXT_LEN * 2]) {
let err = Ciphertext::from_bytes(&vec![0u8; len]).unwrap_err();
assert_eq!(err, Error::InvalidLength { input: Input::Ciphertext, expected: CIPHERTEXT_LEN, actual: len });
}
}
#[test]
fn secret_key_of_the_wrong_length_is_a_typed_error() {
for len in LENGTHS.into_iter().filter(|&l| l != SECRET_KEY_LEN) {
let err = SecretKey::from_bytes(&vec![0u8; len]).unwrap_err();
assert_eq!(err, Error::InvalidLength { input: Input::SecretKey, expected: SECRET_KEY_LEN, actual: len });
}
assert!(SecretKey::from_bytes(&[7u8; SECRET_KEY_LEN]).is_ok(), "any 32 bytes are a valid seed");
}
/// An ML-KEM key whose coefficients are not reduced mod q fails FIPS 203 §7.2: all-0xff bytes
/// encode 12-bit values of 4095 > q = 3329.
#[test]
fn ml_kem_key_failing_the_modulus_check_is_a_typed_error() {
let mut bad = [0xffu8; PUBLIC_KEY_LEN];
bad[1184..].copy_from_slice(&[9u8; 32]);
assert_eq!(PublicKey::from_bytes(&bad).unwrap_err(), Error::InvalidPublicKey);
}
#[test]
fn random_bytes_never_panic() {
let mut r = rng(9);
let sk = SecretKey::from_seed([0x01; 32]);
for round in 0..512 {
let len = [PUBLIC_KEY_LEN, CIPHERTEXT_LEN, seal::OVERHEAD, seal::OVERHEAD + 40, 0, 17][round % 6];
let mut buf = vec![0u8; len];
r.fill_bytes(&mut buf);
if let Ok(pk) = PublicKey::from_bytes(&buf) {
let _ = exchange::initiate(&pk, b"ctx", &mut r);
}
if let Ok(ct) = Ciphertext::from_bytes(&buf) {
// Random ML-KEM ciphertexts decapsulate (implicit rejection) to some unrelated secret.
let _ = exchange::respond(&sk, &ct, b"ctx");
}
assert!(seal::open(&sk, &buf, b"aad").is_err(), "random bytes must never open");
}
}
#[test]
fn sealed_box_round_trips() {
let mut r = rng(10);
let sk = SecretKey::generate(&mut r);
for len in [0usize, 1, 15, 16, 17, 1000, 70_000] {
let msg: Vec<u8> = (0..len).map(|i| (i * 31 % 251) as u8).collect();
let sealed = seal::seal(sk.public_key(), &msg, b"custos/v1 item 42", &mut r).unwrap();
assert_eq!(sealed.len(), msg.len() + seal::OVERHEAD);
let opened = seal::open(&sk, &sealed, b"custos/v1 item 42").unwrap();
assert_eq!(opened.as_slice(), msg.as_slice());
}
}
#[test]
fn sealed_box_too_short_is_a_typed_error() {
let sk = SecretKey::from_seed([0x02; 32]);
for len in [0, 1, seal::OVERHEAD - 1] {
let err = seal::open(&sk, &vec![1u8; len], b"").unwrap_err();
assert_eq!(err, Error::TooShort { input: Input::SealedBox, minimum: seal::OVERHEAD, actual: len });
}
}
#[test]
fn sealed_box_with_an_unknown_version_is_a_typed_error() {
let mut r = rng(11);
let sk = SecretKey::generate(&mut r);
let mut sealed = seal::seal(sk.public_key(), b"hello", b"", &mut r).unwrap();
for v in [0u8, 2, 0xff] {
sealed[0] = v;
assert_eq!(seal::open(&sk, &sealed, b"").unwrap_err(), Error::UnsupportedVersion(v));
}
}
#[test]
fn every_tampered_or_truncated_sealed_box_is_refused() {
let mut r = rng(12);
let sk = SecretKey::generate(&mut r);
let sealed = seal::seal(sk.public_key(), b"the household photo key", b"aad", &mut r).unwrap();
for i in 1..sealed.len() {
let mut bad = sealed.clone();
bad[i] ^= 0x80;
let err = seal::open(&sk, &bad, b"aad").unwrap_err();
assert!(matches!(err, Error::DecryptionFailed | Error::NonContributory), "byte {i}: {err:?}");
}
for len in seal::OVERHEAD..sealed.len() {
assert_eq!(seal::open(&sk, &sealed[..len], b"aad").unwrap_err(), Error::DecryptionFailed, "length {len}");
}
}
#[test]
fn sealed_box_needs_the_right_key_and_aad() {
let mut r = rng(13);
let sk = SecretKey::generate(&mut r);
let other = SecretKey::generate(&mut r);
let sealed = seal::seal(sk.public_key(), b"secret", b"aad", &mut r).unwrap();
assert_eq!(seal::open(&other, &sealed, b"aad").unwrap_err(), Error::DecryptionFailed);
assert_eq!(seal::open(&sk, &sealed, b"aaD").unwrap_err(), Error::DecryptionFailed);
assert_eq!(seal::open(&sk, &sealed, b"").unwrap_err(), Error::DecryptionFailed);
}
#[test]
fn errors_display_without_secrets() {
let e = Error::InvalidLength { input: Input::Ciphertext, expected: 1120, actual: 3 };
assert_eq!(e.to_string(), "ciphertext has the wrong length: expected 1120 bytes, got 3");
let _: &dyn std::error::Error = &e;
}
+37
View File
@@ -0,0 +1,37 @@
//! Mandatory test 6 (the part a test can check; `cargo deny` and `cargo audit` are run separately,
//! see docs/01_arcanum.md). The compiler enforces `#![forbid(unsafe_code)]`; this guardrail makes
//! sure the attribute itself is never removed and no source file opts back in.
use std::fs;
use std::path::Path;
fn rust_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
rust_files(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
#[test]
fn the_crate_forbids_unsafe_code() {
let lib = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lib.rs")).unwrap();
assert!(lib.lines().any(|l| l.trim() == "#![forbid(unsafe_code)]"), "src/lib.rs must forbid unsafe code");
}
#[test]
fn no_source_file_contains_unsafe() {
let mut files = Vec::new();
rust_files(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
assert!(!files.is_empty());
for f in files {
let text = fs::read_to_string(&f).unwrap();
for (n, line) in text.lines().enumerate() {
let code = line.split("//").next().unwrap_or("");
assert!(!code.contains("unsafe"), "{}:{}: {line}", f.display(), n + 1);
}
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Mandatory test 4: WireGuard PSK epochs. Successive epochs differ, the same epoch is reproducible
//! from the same inputs, and the epoch helper follows the 120-second Rosenpass-style interval.
use arcanum::exchange;
use arcanum::xwing::SecretKey;
use arcanum::{RECOMMENDED_EPOCH_SECONDS, WIREGUARD_PSK_LEN, epoch_at};
use std::collections::HashSet;
const CONTEXT: &[u8] = b"via/test: epochs";
fn sessions() -> (exchange::Session, exchange::Session) {
let sk = SecretKey::from_seed([0x01; 32]);
let (ct, a) = exchange::initiate_derand(sk.public_key(), CONTEXT, &[0x02; 64]).unwrap();
let b = exchange::respond(&sk, &ct, CONTEXT).unwrap();
(a, b)
}
#[test]
fn successive_epochs_differ() {
let (a, _) = sessions();
let mut seen = HashSet::new();
for epoch in 0..2048u64 {
assert!(seen.insert(*a.wireguard_psk(epoch).as_bytes()), "epoch {epoch} repeats an earlier PSK");
}
// The ends of the range and neighbours that differ only in the high bytes.
for epoch in [u64::MAX, u64::MAX - 1, 1 << 32, (1 << 32) + 1, 1 << 63] {
assert!(seen.insert(*a.wireguard_psk(epoch).as_bytes()), "epoch {epoch} repeats");
}
}
#[test]
fn the_same_epoch_is_reproducible_from_the_same_inputs() {
let (a1, b1) = sessions();
let (a2, b2) = sessions();
for epoch in [0, 1, 719, 720, u64::MAX] {
let p = *a1.wireguard_psk(epoch).as_bytes();
assert_eq!(&p, a1.wireguard_psk(epoch).as_bytes(), "same session, asked twice");
assert_eq!(&p, a2.wireguard_psk(epoch).as_bytes(), "rebuilt from the same inputs");
assert_eq!(&p, b1.wireguard_psk(epoch).as_bytes(), "the other peer");
assert_eq!(&p, b2.wireguard_psk(epoch).as_bytes(), "the other peer, rebuilt");
}
}
#[test]
fn a_different_exchange_gives_different_psks_for_the_same_epoch() {
let sk = SecretKey::from_seed([0x01; 32]);
let (_, a) = exchange::initiate_derand(sk.public_key(), CONTEXT, &[0x02; 64]).unwrap();
let (_, c) = exchange::initiate_derand(sk.public_key(), CONTEXT, &[0x03; 64]).unwrap();
for epoch in 0..16 {
assert_ne!(a.wireguard_psk(epoch).as_bytes(), c.wireguard_psk(epoch).as_bytes());
}
}
#[test]
fn a_psk_is_32_bytes_and_not_trivial() {
let (a, _) = sessions();
let p = a.wireguard_psk(0);
assert_eq!(WIREGUARD_PSK_LEN, 32);
assert_eq!(p.as_bytes().len(), 32);
assert_ne!(p.as_bytes(), &[0u8; 32]);
}
#[test]
fn the_psk_never_prints() {
let (a, _) = sessions();
let p = a.wireguard_psk(0);
let shown = format!("{p:?} {a:?}");
assert!(shown.contains("redacted"), "{shown}");
let k = p.as_bytes();
// Neither a hex dump nor a derived `[1, 2, 3, ...]` array may appear.
assert!(!shown.contains(&hex::encode(&k[..4])), "{shown}");
assert!(!shown.contains(&format!("{}, {}, {}", k[0], k[1], k[2])), "{shown}");
}
#[test]
fn epoch_helper_uses_two_minute_epochs() {
assert_eq!(RECOMMENDED_EPOCH_SECONDS, 120, "Rosenpass REKEY_AFTER_TIME_RESPONDER is 120 s");
assert_eq!(epoch_at(0), 0);
assert_eq!(epoch_at(119), 0);
assert_eq!(epoch_at(120), 1);
assert_eq!(epoch_at(239), 1);
assert_eq!(epoch_at(240), 2);
assert_eq!(epoch_at(1_764_000_000), 1_764_000_000 / 120);
assert_eq!(epoch_at(u64::MAX), u64::MAX / 120);
}
+29
View File
@@ -0,0 +1,29 @@
# Known-answer vector sources
Every file here is kept byte-for-byte as published (`.gitattributes` marks the folder `-text`).
The tests check each file's sha256 before using it, so a changed file fails the test instead of
silently changing what is verified. Fetched 2026-11-25.
| File | sha256 | Source |
|:--|:--|:--|
| `acvp-ml-kem-keyGen-FIPS203-internalProjection.json` | `d7a62a2c3476957f56dd8d24f9004ea6776ccfe995ffe71a65bb9506dc9c7b1b` | NIST ACVP-Server, `gen-val/json-files/ML-KEM-keyGen-FIPS203/internalProjection.json` at commit `975de31eb83d87039ec88934fdc47d8c312b892d` (2026-08-12). Git blob `99973426c8dd03f227ace6d7ac917ba4443e2f27` matches the GitHub API listing. |
| `acvp-ml-kem-encapDecap-FIPS203-internalProjection.json` | `a556952ce869bb89c3a3196a701dad89647c193a34c86eafb61a9d710d5b810f` | NIST ACVP-Server, `gen-val/json-files/ML-KEM-encapDecap-FIPS203/internalProjection.json` at the same commit. Git blob `73692fe52abe2f937b7884baa46475c77c68a1d3` matches. |
| `xwing-test-vectors.json` | `409efe197550b22985b4a0419418a0c5f2c2b193426c55bd998399ec8d3e614d` | The X-Wing draft authors' repository, `dconnolly/draft-connolly-cfrg-xwing-kem`, `spec/test-vectors.json` at commit `984c2f7a93b8f8d8f8073ebb53f9f4ce50b5babd` (2026-09-23, the day draft -11 was posted). The same three vectors are in Appendix C of draft -11 (spot-checked: seed and ss of vectors 1–2, ss of vector 3), and, pretty-printed, in RustCrypto `x-wing` 0.1.1 `tests/test-vectors.json` (identical after removing whitespace). |
URLs:
- <https://github.com/usnistgov/ACVP-Server/tree/975de31eb83d87039ec88934fdc47d8c312b892d/gen-val/json-files>
- <https://github.com/dconnolly/draft-connolly-cfrg-xwing-kem/blob/984c2f7a93b8f8d8f8073ebb53f9f4ce50b5babd/spec/test-vectors.json>
- <https://www.ietf.org/archive/id/draft-connolly-cfrg-xwing-kem-11.txt>, Appendix C
Only the ML-KEM-768 groups of the ACVP files are used (the files also hold 512 and 1024).
## Vectors kept in test source
| Test | Source |
|:--|:--|
| X25519 scalar multiplication, two vectors (RFC 7748 §5.2) | RFC 7748, <https://www.rfc-editor.org/rfc/rfc7748.txt>; the same bytes are in `x25519-dalek` 3.0.0 `tests/x25519_tests.rs` |
| X25519 iterated, 1 and 1,000 iterations (RFC 7748 §5.2) | RFC 7748 §5.2 |
| X25519 Diffie–Hellman, Alice and Bob (RFC 7748 §6.1) | RFC 7748 §6.1; also in `x25519-dalek` 3.0.0 `tests/x25519_tests.rs` |
Not run: the RFC 7748 1,000,000-iteration vector (minutes in a debug build).
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long