Files
mnovak 5a52854ccc feat: hybrid signatures ML-DSA-65 + Ed25519, RFC 10073 id-MLDSA65-Ed25519-SHA512
arcanum::sign, as docs/02_signatures.md sets out. M' = Prefix || Label ||
u8(len ctx) || ctx || SHA-512(M), built on the stack. The ML-DSA-65 half is
ExpandedSigningKey::sign_randomized(M', ctx = Label, rng), hedged; the
Ed25519 half is pure Ed25519 over M' (try_sign), checked with verify_strict.
Verification computes both halves before answering, and returns one
InvalidSignature whichever failed. ml-dsa's Signer/Verifier traits,
sign_deterministic and sign_mu_deterministic are never called.

- SigningKey: two 32-byte seeds (RFC 10073's private key format), the
  expanded ML-DSA key boxed; ZeroizeOnDrop, not Clone, Debug redacted.
- VerifyingKey: 1984 bytes; refuses an Ed25519 half that is not a point,
  not its canonical encoding, or of small order (InvalidVerifyingKey).
- AppContext: only "domi/arcanum/v2/sig/app/" + a 1..=231-byte label.
- bind_kem_key / verify_binding: an X-Wing public key bound to a key id and
  an inclusive validity window under "domi/arcanum/v2/sig/kem-key"; the
  message is hashed field by field; window and id are checked first, then
  the signature, then now (InvalidValidity, TooLong, InvalidSignature,
  OutsideValidity).
- sign_composite_raw / verify_composite_raw: the bare RFC ctx, hazmat only.
  They still take an RNG (the ML-DSA half stays hedged), not the
  deterministic variant the doc mentions.
- Error gains TooLong, InvalidVerifyingKey, InvalidSignature,
  SigningFailed, InvalidValidity, OutsideValidity; Input gains SigningKey,
  VerifyingKey, Signature, Context, KeyId.

Also fixes tests/kat_mldsa65.rs, which passed a &[&Vec<u8>] to
sign_internal and did not compile.

cargo test (debug): 121 passed, 0 failed (82 from v0.1.0, golden_v1
unchanged). clippy --all-targets --all-features -D warnings: clean.
2026-11-25 13:12:22 +01:00

235 lines
11 KiB
Rust

//! Mandatory test 1 (v0.2.0): ML-DSA-65 known-answer tests (FIPS 204).
//!
//! Runs the vetted `ml-dsa` crate against NIST ACVP (keyGen and sigGen at `2972def2`, sigVer at
//! `a7f283cd`, after the ModifyZ correction) and Wycheproof (`20b25694`). Provenance, sha256 and
//! how the subsets were made: tests/vectors/SOURCES.md.
//!
//! The hedged cases go through `ExpandedSigningKey::sign_randomized` (external interface) and
//! `sign_mu_randomized` (external mu), the paths Arcanum's composite uses, fed the vector's `rnd`
//! by a `FixedRng`; deterministic cases use the same calls with an all-zero `rnd`, which FIPS 204
//! Algorithm 2 defines as the deterministic variant. `sign_mu_deterministic` is never called.
//! HashML-DSA (`preHash`) groups are not used: Arcanum signs pure ML-DSA only.
mod common;
use common::{FixedRng, assert_sha256, hex};
use ml_dsa::common::array::Array;
use ml_dsa::{ExpandedSigningKey, MlDsa65, Seed, Signature, VerifyingKey};
use serde_json::Value;
const KEYGEN: &[u8] = include_bytes!("vectors/acvp-ml-dsa-keyGen-FIPS204-internalProjection.json");
const KEYGEN_SHA256: &str = "e67ee6540d40e11506c3c4e3b1f79fc1cefcd49820db99fc61f87cc8ba463baf";
const SIGGEN: &[u8] = include_bytes!("vectors/acvp-ml-dsa-sigGen-FIPS204-internalProjection.subset.json");
const SIGGEN_SHA256: &str = "ca1f1697d78b2280d854bbe0f8e86d3601695013f14e7bb4ce0604bc80ed2b4e";
const SIGVER: &[u8] = include_bytes!("vectors/acvp-ml-dsa-sigVer-FIPS204-internalProjection.subset.json");
const SIGVER_SHA256: &str = "d005dfeee9039f751299a6430fdac509b97ad9ab7d25b0b502dc9a2b59b7fb0c";
const WP_SIGN: &[u8] = include_bytes!("vectors/wycheproof-mldsa_65_sign_seed_test.json");
const WP_SIGN_SHA256: &str = "e26b2bb9ab8d45ed570ba6828c7e40b6fa3e1545bb8bc2c449c77531760133e0";
const WP_VERIFY: &[u8] = include_bytes!("vectors/wycheproof-mldsa_65_verify_test.subset.json");
const WP_VERIFY_SHA256: &str = "47fc788c0913dc41cfd0ef5bc9ed44c779a6bdeeb8b3700077fd572527c33870";
const ZERO_RND: [u8; 32] = [0; 32];
fn json(file: &[u8]) -> Value {
serde_json::from_slice(file).expect("vector json")
}
/// The ML-DSA-65 groups, without HashML-DSA.
fn groups(file: &[u8]) -> Vec<Value> {
json(file)["testGroups"]
.as_array()
.expect("testGroups")
.iter()
.filter(|g| g["parameterSet"] == "ML-DSA-65" && g["preHash"].as_str().unwrap_or("none") != "preHash")
.cloned()
.collect()
}
fn field(t: &Value, name: &str) -> Vec<u8> {
hex(t[name].as_str().unwrap_or_else(|| panic!("field {name}")))
}
fn opt_field(t: &Value, name: &str) -> Option<Vec<u8>> {
t.get(name).and_then(Value::as_str).map(hex)
}
fn vk_from(bytes: &[u8]) -> Option<VerifyingKey<MlDsa65>> {
Array::try_from(bytes).ok().map(|a| VerifyingKey::<MlDsa65>::decode(&a))
}
fn sig_from(bytes: &[u8]) -> Option<Signature<MlDsa65>> {
Signature::<MlDsa65>::try_from(bytes).ok()
}
#[allow(deprecated)]
fn sk_from_expanded(bytes: &[u8]) -> ExpandedSigningKey<MlDsa65> {
// ACVP's sigGen gives the FIPS 204 expanded key, not the seed. `from_expanded` is deprecated
// (it does not validate), which is fine for official vectors; Arcanum itself uses seeds.
ExpandedSigningKey::<MlDsa65>::from_expanded(&Array::try_from(bytes).expect("sk length"))
}
#[test]
fn vector_files_are_the_pinned_ones() {
assert_sha256(KEYGEN, KEYGEN_SHA256, "ACVP ML-DSA keyGen");
assert_sha256(SIGGEN, SIGGEN_SHA256, "ACVP ML-DSA sigGen subset");
assert_sha256(SIGVER, SIGVER_SHA256, "ACVP ML-DSA sigVer subset");
assert_sha256(WP_SIGN, WP_SIGN_SHA256, "Wycheproof mldsa_65_sign_seed");
assert_sha256(WP_VERIFY, WP_VERIFY_SHA256, "Wycheproof mldsa_65_verify subset");
}
#[test]
#[allow(deprecated)]
fn acvp_keygen_65() {
let groups = groups(KEYGEN);
assert_eq!(groups.len(), 1, "one ML-DSA-65 keyGen group");
let mut n = 0;
for t in groups[0]["tests"].as_array().unwrap() {
let seed = Seed::try_from(field(t, "seed").as_slice()).expect("seed length");
let sk = ExpandedSigningKey::<MlDsa65>::from_seed(&seed);
assert_eq!(sk.verifying_key().encode().as_slice(), field(t, "pk").as_slice(), "pk, tcId {}", t["tcId"]);
assert_eq!(sk.to_expanded().as_slice(), field(t, "sk").as_slice(), "sk, tcId {}", t["tcId"]);
n += 1;
}
assert_eq!(n, 25);
}
/// sigGen, byte for byte: deterministic groups (tgId 3, 9, 10) and hedged groups (15, 21, 22).
#[test]
fn acvp_siggen_65() {
let groups = groups(SIGGEN);
assert_eq!(groups.len(), 6);
let mut n = 0;
for g in &groups {
let interface = g["signatureInterface"].as_str().unwrap();
let external_mu = g["externalMu"].as_bool().unwrap();
let deterministic = g["deterministic"].as_bool().unwrap();
for t in g["tests"].as_array().unwrap() {
let id = &t["tcId"];
let sk = sk_from_expanded(&field(t, "sk"));
let rnd = if deterministic { ZERO_RND.to_vec() } else { field(t, "rnd") };
let mut rng = FixedRng::new(&rnd);
let sig = match (interface, external_mu) {
("external", false) => {
let ctx = field(t, "context");
sk.sign_randomized(&field(t, "message"), &ctx, &mut rng).expect("sign")
}
("internal", true) => {
let mu = Array::try_from(field(t, "mu").as_slice()).expect("mu length");
sk.sign_mu_randomized(&mu, &mut rng).expect("sign")
}
("internal", false) => {
// ML-DSA.Sign_internal (FIPS 204 Algorithm 7) on M' = the message as given.
// `sign_internal` takes rnd directly (and is never called by Arcanum).
let rnd: ml_dsa::B32 = Array::try_from(rnd.as_slice()).unwrap();
sk.sign_internal(&[field(t, "message").as_slice()], &rnd)
}
other => panic!("unexpected group {other:?}"),
};
assert_eq!(
sig.encode().as_slice(),
field(t, "signature").as_slice(),
"signature, tgId {} tcId {id}",
g["tgId"]
);
if interface == "external" || external_mu {
// The hedged path must consume the vector's rnd: no more, no less.
assert_eq!(rng.used(), 32, "the hedged path draws exactly 32 bytes of rnd, tcId {id}");
}
n += 1;
}
}
assert_eq!(n, 18);
}
/// sigVer: accept and reject, on the corrected (a7f283cd) file.
#[test]
fn acvp_sigver_65() {
let groups = groups(SIGVER);
assert_eq!(groups.len(), 3);
let (mut accepted, mut rejected) = (0, 0);
for g in &groups {
let interface = g["signatureInterface"].as_str().unwrap();
let external_mu = g["externalMu"].as_bool().unwrap();
for t in g["tests"].as_array().unwrap() {
let vk = vk_from(&field(t, "pk")).expect("pk length");
let ok = sig_from(&field(t, "signature")).is_some_and(|sig| match (interface, external_mu) {
("external", false) => vk.verify_with_context(&field(t, "message"), &field(t, "context"), &sig),
("internal", true) => vk.verify_mu(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &sig),
("internal", false) => vk.verify_internal(&field(t, "message"), &sig),
other => panic!("unexpected group {other:?}"),
});
let want = t["testPassed"].as_bool().unwrap();
assert_eq!(ok, want, "tgId {} tcId {} ({})", g["tgId"], t["tcId"], t["reason"]);
if want { accepted += 1 } else { rejected += 1 }
}
}
assert_eq!((accepted, rejected), (3, 12));
}
/// Wycheproof signing from a seed: deterministic unless the case gives `rnd`, byte for byte; an
/// over-long context and a seed of the wrong length are refused.
#[test]
fn wycheproof_sign_seed_65() {
let (mut valid, mut invalid) = (0, 0);
for g in json(WP_SIGN)["testGroups"].as_array().unwrap() {
let seed_bytes = field(g, "privateSeed");
for t in g["tests"].as_array().unwrap() {
let id = &t["tcId"];
let want_valid = t["result"] == "valid";
let Ok(seed) = Seed::try_from(seed_bytes.as_slice()) else {
assert!(!want_valid, "tcId {id}: a seed of {} bytes must be refused", seed_bytes.len());
invalid += 1;
continue;
};
let sk = ExpandedSigningKey::<MlDsa65>::from_seed(&seed);
if let Some(pk) = opt_field(g, "publicKey") {
assert_eq!(sk.verifying_key().encode().as_slice(), pk.as_slice(), "public key, tcId {id}");
}
let rnd = opt_field(t, "rnd").unwrap_or_else(|| ZERO_RND.to_vec());
let mut rng = FixedRng::new(&rnd);
let ctx = opt_field(t, "ctx").unwrap_or_default();
let result = match opt_field(t, "msg") {
Some(msg) => sk.sign_randomized(&msg, &ctx, &mut rng),
None => sk.sign_mu_randomized(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &mut rng),
};
if want_valid {
let sig = result.unwrap_or_else(|e| panic!("tcId {id}: {e}"));
assert_eq!(sig.encode().as_slice(), field(t, "sig").as_slice(), "signature, tcId {id}");
let vk = sk.verifying_key();
let verified = match opt_field(t, "msg") {
Some(msg) => vk.verify_with_context(&msg, &ctx, &sig),
None => vk.verify_mu(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &sig),
};
assert!(verified, "tcId {id}: own signature does not verify");
valid += 1;
} else {
assert!(result.is_err(), "tcId {id} ({}) must be refused", t["comment"]);
invalid += 1;
}
}
}
assert_eq!((valid, invalid), (101, 4));
}
/// Wycheproof verification, including bad hint encodings, infinity-norm violations, wrong lengths
/// and an over-long context.
#[test]
fn wycheproof_verify_65() {
let (mut valid, mut invalid) = (0, 0);
for g in json(WP_VERIFY)["testGroups"].as_array().unwrap() {
let vk = vk_from(&field(g, "publicKey"));
for t in g["tests"].as_array().unwrap() {
let ctx = opt_field(t, "ctx").unwrap_or_default();
let ok = match (&vk, sig_from(&field(t, "sig"))) {
(Some(vk), Some(sig)) => vk.verify_with_context(&field(t, "msg"), &ctx, &sig),
_ => false,
};
let want = t["result"] == "valid";
assert_eq!(ok, want, "tcId {} ({}) {:?}", t["tcId"], t["comment"], t["flags"]);
if want { valid += 1 } else { invalid += 1 }
}
}
assert_eq!(valid + invalid, 70);
assert!(valid > 0 && invalid > 0);
}