2a432f5d86
The mandatory tests of docs/02_signatures.md, against the API the doc sets out (arcanum::sign). They do not compile yet: the module does not exist. 1 kat_mldsa65: ACVP keyGen, sigGen (deterministic and hedged groups, byte for byte, through sign_randomized/sign_mu_randomized fed the vector's rnd), sigVer on the corrected file; Wycheproof sign_seed and verify. 2 kat_ed25519: RFC 8032 section 7.1 and Wycheproof, with verify_strict. 3 sig_composite: the RFC 10073 vectors s and sWithContext verify, the RFC key derives the RFC public key, own signatures verify under an independent rebuild of M', ML-DSA hedged with ctx = Label. 4 sig_halves: either half swapped in from another signature, zeroed or cut, or the halves swapped, is refused; the ML-DSA half fails an empty-ctx verifier. Not SUF-CMA (RFC 10073 9.2) is pinned. 5 sig_every_byte: any flipped byte of message, ctx, public key or signature fails; contexts are prefix-free; key bindings and app messages never verify as each other; every binding field matters. 6 sig_malformed: wrong lengths, weak and non-canonical Ed25519 keys, 0- and 256-byte contexts, a 65536-byte key id, random bytes. 7 sig_hygiene and feature_hygiene: compile-fail checks against a default-features consumer (hazmat raw interface, ml-dsa internals, non-crypto RNG, Clone), ZeroizeOnDrop, Debug; ml-dsa and ed25519-dalek in the normal graph with zeroize and without hazmat or defaults. The allocator probe covers the signing keys. 8 golden_v1.rs is untouched. Adds ml-dsa =0.1.2 (alloc, rand_core, zeroize) and ed25519-dalek =3.0.0 (zeroize) with default features off, base64 for the tests, and bumps the version to 0.2.0. The fuzz target follows with the code.
235 lines
11 KiB
Rust
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")], &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);
|
|
}
|