test: the v0.2.0 signature tests, written before the code

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.
This commit is contained in:
2026-11-25 12:48:39 +01:00
parent 5b9e3ee8fb
commit 2a432f5d86
13 changed files with 1482 additions and 4 deletions
Generated
+95 -1
View File
@@ -14,14 +14,17 @@ dependencies = [
[[package]]
name = "arcanum"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"arcanum",
"base64",
"chacha20",
"chacha20poly1305",
"ed25519-dalek",
"hex",
"hkdf",
"hmac",
"ml-dsa",
"ml-kem",
"rand_core",
"serde",
@@ -40,6 +43,18 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "block-buffer"
version = "0.12.1"
@@ -142,6 +157,7 @@ dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
@@ -159,6 +175,16 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "der"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
dependencies = [
"const-oid",
"zeroize",
]
[[package]]
name = "digest"
version = "0.11.3"
@@ -172,6 +198,28 @@ dependencies = [
"zeroize",
]
[[package]]
name = "ed25519"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
dependencies = [
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2",
"subtle",
"zeroize",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@@ -260,6 +308,22 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "ml-dsa"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c"
dependencies = [
"crypto-common",
"ctutils",
"hybrid-array",
"module-lattice",
"pkcs8",
"shake",
"signature",
"zeroize",
]
[[package]]
name = "ml-kem"
version = "0.3.4"
@@ -296,6 +360,16 @@ dependencies = [
"autocfg",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "poly1305"
version = "0.9.1"
@@ -421,6 +495,26 @@ dependencies = [
"sponge-cursor",
]
[[package]]
name = "signature"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
dependencies = [
"digest",
"rand_core",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "sponge-cursor"
version = "0.1.0"
+8 -2
View File
@@ -1,10 +1,10 @@
[package]
name = "arcanum"
version = "0.1.0"
version = "0.2.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"
description = "Hybrid post-quantum key exchange (X-Wing: ML-KEM-768 + X25519), key schedule, WireGuard PSK derivation, sealing and hybrid signatures (ML-DSA-65 + Ed25519, RFC 10073) for the Domi ecosystem"
repository = "https://gitea.marek-novak.cz/mnovak/arcanum"
readme = "README.md"
publish = false
@@ -21,6 +21,10 @@ 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"] }
# v0.2.0 signatures (docs/02_signatures.md): ML-DSA-65 (FIPS 204) and Ed25519 (RFC 8032), combined as
# RFC 10073 id-MLDSA65-Ed25519-SHA512. Pinned exactly; `zeroize` is opt-in in ml-dsa and must stay on.
ml-dsa = { version = "=0.1.2", default-features = false, features = ["alloc", "rand_core", "zeroize"] }
ed25519-dalek = { version = "=3.0.0", default-features = false, features = ["zeroize"] }
[features]
# Deterministic entry points (`_derand`, `from_seed`) for the known-answer tests. Off by default;
@@ -37,6 +41,8 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
hex = "0.4"
sha2 = "0.11"
# The RFC 10073 vectors are base64.
base64 = "0.22"
# ML-KEM in a debug build is slow; the byte-flip tests run thousands of exchanges.
[profile.dev.package."*"]
+47
View File
@@ -23,3 +23,50 @@ 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)");
}
/// Standard base64 (RFC 4648 §4, with padding), as the RFC 10073 vectors use.
pub fn b64(s: &str) -> Vec<u8> {
use base64::Engine;
base64::engine::general_purpose::STANDARD.decode(s).expect("vector base64")
}
/// An "RNG" that returns exactly the given bytes, then panics. It lets a known-answer test feed a
/// vector's `rnd` to the hedged signing path that Arcanum uses (`sign_randomized`), and proves
/// that path draws exactly 32 bytes. Claims `TryCryptoRng` only so the signing API accepts it.
pub struct FixedRng {
bytes: Vec<u8>,
pos: usize,
}
impl FixedRng {
pub fn new(bytes: &[u8]) -> Self {
Self { bytes: bytes.to_vec(), pos: 0 }
}
pub fn used(&self) -> usize {
self.pos
}
}
impl rand_core::TryRng for FixedRng {
type Error = core::convert::Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
let mut b = [0u8; 4];
self.try_fill_bytes(&mut b)?;
Ok(u32::from_le_bytes(b))
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
let mut b = [0u8; 8];
self.try_fill_bytes(&mut b)?;
Ok(u64::from_le_bytes(b))
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
let end = self.pos + dst.len();
assert!(end <= self.bytes.len(), "FixedRng: asked for more bytes than the vector gives");
dst.copy_from_slice(&self.bytes[self.pos..end]);
self.pos = end;
Ok(())
}
}
impl rand_core::TryCryptoRng for FixedRng {}
+19
View File
@@ -49,3 +49,22 @@ fn no_os_rng_in_the_normal_graph() {
assert!(t.contains("rand_core"), "the tree must include rand_core:\n{t}");
assert!(!t.contains("getrandom"), "getrandom reached a normal build:\n{t}");
}
/// v0.2.0, mandatory test 7: the signature crates enter the normal graph with `zeroize` on and
/// no `hazmat`. `ed25519-dalek` has a `hazmat` feature of its own (raw `ExpandedSecretKey`
/// signing, `verify_stream`); `ml-dsa`'s `default` would pull `getrandom` and `pkcs8`.
#[test]
fn signature_crates_have_zeroize_and_no_hazmat() {
let t = tree(&["-i", "ml-dsa"]);
assert!(t.contains("ml-dsa feature \"zeroize\""), "ml-dsa must have zeroize:\n{t}");
assert!(t.contains("ml-dsa feature \"rand_core\""), "the tree must list ml-dsa's features:\n{t}");
assert!(!t.contains("ml-dsa feature \"default\""), "ml-dsa's default features reached a normal build:\n{t}");
assert!(!t.contains("ml-dsa feature \"getrandom\""), "ml-dsa's getrandom reached a normal build:\n{t}");
assert_no_hazmat(&t, "ml-dsa");
let t = tree(&["-i", "ed25519-dalek"]);
assert!(t.contains("ed25519-dalek feature \"zeroize\""), "ed25519-dalek must have zeroize:\n{t}");
assert!(!t.contains("ed25519-dalek feature \"default\""), "ed25519-dalek's defaults reached a normal build:\n{t}");
assert_no_hazmat(&t, "ed25519-dalek");
// (That the check can see a `hazmat` feature at all is proved for arcanum's own, above.)
}
+95
View File
@@ -0,0 +1,95 @@
//! Mandatory test 2 (v0.2.0): Ed25519 known answers and edge cases, verified with `verify_strict`,
//! the check Arcanum's composite uses.
//!
//! RFC 8032 §7.1 (all five vectors, signing byte for byte) and Wycheproof `ed25519_test.json`
//! (`20b25694`). Provenance and sha256: tests/vectors/SOURCES.md. Pure Ed25519 signing is
//! deterministic by definition (RFC 8032 §5.1.6); `ed25519_dalek::Signer::sign` is that algorithm.
mod common;
use common::{assert_sha256, hex};
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use serde_json::Value;
const RFC8032: &[u8] = include_bytes!("vectors/rfc8032-7.1-ed25519.json");
const RFC8032_SHA256: &str = "fad8e499cdc3e0324a5b4a93cdbabb33f8aed1df73ecacfdb364f433b0fdf12b";
const WYCHEPROOF: &[u8] = include_bytes!("vectors/wycheproof-ed25519_test.json");
const WYCHEPROOF_SHA256: &str = "752d2ea7d7c6cf4736381b6cbacb61f8182b126ab7cd9b058f00c50084975536";
/// Wycheproof cases where `verify_strict` disagrees with the file's verdict, with the reason.
/// Empty unless a run shows otherwise; each entry must be explained in docs/02_signatures.md.
const KNOWN_DISAGREEMENTS: &[(u64, &str)] = &[];
fn json(file: &[u8]) -> Value {
serde_json::from_slice(file).expect("vector json")
}
fn arr<const N: usize>(v: &Value) -> [u8; N] {
hex(v.as_str().expect("hex field")).try_into().expect("field length")
}
#[test]
fn vector_files_are_the_pinned_ones() {
assert_sha256(RFC8032, RFC8032_SHA256, "RFC 8032 section 7.1 extraction");
assert_sha256(WYCHEPROOF, WYCHEPROOF_SHA256, "Wycheproof ed25519_test");
}
#[test]
fn rfc8032_section_7_1() {
let tests = json(RFC8032)["tests"].as_array().unwrap().clone();
assert_eq!(tests.len(), 5);
for t in &tests {
let name = t["name"].as_str().unwrap();
let sk = SigningKey::from_bytes(&arr(&t["secret_key"]));
let pk: [u8; 32] = arr(&t["public_key"]);
let msg = hex(t["message"].as_str().unwrap());
let want: [u8; 64] = arr(&t["signature"]);
assert_eq!(sk.verifying_key().to_bytes(), pk, "TEST {name}: public key");
let sig = sk.sign(&msg);
assert_eq!(sig.to_bytes(), want, "TEST {name}: signature");
let vk = VerifyingKey::from_bytes(&pk).unwrap();
assert!(vk.verify_strict(&msg, &sig).is_ok(), "TEST {name}: verify_strict");
let mut other = msg.clone();
other.push(0);
assert!(vk.verify_strict(&other, &sig).is_err(), "TEST {name}: an extended message must fail");
let mut bad = want;
bad[0] ^= 1;
assert!(vk.verify_strict(&msg, &Signature::from_bytes(&bad)).is_err(), "TEST {name}: flipped R");
}
}
#[test]
fn wycheproof_ed25519_with_verify_strict() {
let mut disagreements = Vec::new();
let (mut valid, mut invalid) = (0, 0);
for g in json(WYCHEPROOF)["testGroups"].as_array().unwrap() {
let pk = hex(g["publicKey"]["pk"].as_str().unwrap());
let vk = <[u8; 32]>::try_from(pk.as_slice()).ok().and_then(|b| VerifyingKey::from_bytes(&b).ok());
for t in g["tests"].as_array().unwrap() {
let id = t["tcId"].as_u64().unwrap();
let msg = hex(t["msg"].as_str().unwrap());
let sig = Signature::from_slice(&hex(t["sig"].as_str().unwrap())).ok();
let ok = match (&vk, sig) {
(Some(vk), Some(sig)) => vk.verify_strict(&msg, &sig).is_ok(),
_ => false,
};
let want = match t["result"].as_str().unwrap() {
"valid" => true,
"invalid" => false,
other => panic!("tcId {id}: result {other} is not handled"),
};
if want {
valid += 1
} else {
invalid += 1
}
if ok != want {
disagreements.push((id, t["comment"].as_str().unwrap_or("").to_string(), want));
}
}
}
assert_eq!(valid + invalid, 151, "numberOfTests in the file");
let got: Vec<u64> = disagreements.iter().map(|d| d.0).collect();
let known: Vec<u64> = KNOWN_DISAGREEMENTS.iter().map(|k| k.0).collect();
assert_eq!(got, known, "verify_strict disagrees with Wycheproof on: {disagreements:?}");
}
+234
View File
@@ -0,0 +1,234 @@
//! 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);
}
+177
View File
@@ -0,0 +1,177 @@
//! Mandatory test 3 (v0.2.0): the composite is RFC 10073 `id-MLDSA65-Ed25519-SHA512`, byte for byte.
//!
//! - The RFC's own signatures (`s`, empty ctx; `sWithContext`) verify, from Appendix E as
//! published in `lamps-wg/draft-composite-sigs` `testvectors.json` at `f0627ab`, and the RFC's
//! 64-byte private key derives the RFC's 1984-byte public key.
//! - Arcanum's own signatures verify under an **independent rebuild** of M' written here, against
//! the component crates directly: ML-DSA-65 with ctx = Label, and Ed25519 `verify_strict`.
//! - The ML-DSA half is hedged (two signatures of the same message differ) and the Ed25519 half
//! is pure Ed25519 (deterministic, so equal).
//!
//! The RFC vectors are hedged, so there is no byte-exact composite signing KAT (docs gap).
mod common;
use arcanum::Error;
use arcanum::sign::{
self, AppContext, SIGNATURE_LEN, SIGNING_KEY_LEN, Signature, SigningKey, VERIFYING_KEY_LEN, VerifyingKey,
};
use common::{assert_sha256, b64, rng};
use ml_dsa::MlDsa65;
use ml_dsa::common::array::Array;
use serde_json::Value;
use sha2::{Digest, Sha512};
const VECTORS: &[u8] = include_bytes!("vectors/composite-sigs-testvectors-MLDSA65-Ed25519.subset.json");
const VECTORS_SHA256: &str = "33311f63d2c5a21d5dd4b05eb864de38bd7572108b38de713a40312d2b893b34";
/// RFC 10073 §2.2 and §6, written out here independently of `src/sign.rs`.
const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
const LABEL: &[u8] = b"COMPSIG-MLDSA65-Ed25519-SHA512";
const ML_DSA_SIG_LEN: usize = 3309;
const ML_DSA_PK_LEN: usize = 1952;
/// M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) (RFC 10073 §3.2)
fn m_prime(msg: &[u8], ctx: &[u8]) -> Vec<u8> {
assert!(ctx.len() <= 255);
let mut m = Vec::new();
m.extend_from_slice(PREFIX);
m.extend_from_slice(LABEL);
m.push(ctx.len() as u8);
m.extend_from_slice(ctx);
m.extend_from_slice(&Sha512::digest(msg));
m
}
/// Verify a composite signature with the component crates only, not with Arcanum.
fn independent_verify(pk: &[u8], msg: &[u8], ctx: &[u8], sig: &[u8]) -> (bool, bool) {
assert_eq!(pk.len(), ML_DSA_PK_LEN + 32);
assert_eq!(sig.len(), ML_DSA_SIG_LEN + 64);
let mp = m_prime(msg, ctx);
let ml_vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_DSA_PK_LEN]).unwrap());
let ml_ok = ml_dsa::Signature::<MlDsa65>::try_from(&sig[..ML_DSA_SIG_LEN])
.is_ok_and(|s| ml_vk.verify_with_context(&mp, LABEL, &s));
let ed_vk = ed25519_dalek::VerifyingKey::from_bytes(pk[ML_DSA_PK_LEN..].try_into().unwrap()).unwrap();
let ed_sig = ed25519_dalek::Signature::from_slice(&sig[ML_DSA_SIG_LEN..]).unwrap();
let ed_ok = ed_vk.verify_strict(&mp, &ed_sig).is_ok();
(ml_ok, ed_ok)
}
struct Rfc {
m: Vec<u8>,
ctx: Vec<u8>,
pk: Vec<u8>,
sk: Vec<u8>,
s: Vec<u8>,
s_with_context: Vec<u8>,
}
fn rfc() -> Rfc {
assert_sha256(VECTORS, VECTORS_SHA256, "RFC 10073 composite vectors subset");
let v: Value = serde_json::from_slice(VECTORS).unwrap();
let tests = v["tests"].as_array().unwrap();
assert_eq!(tests.len(), 1);
let t = &tests[0];
assert_eq!(t["tcId"], "id-MLDSA65-Ed25519-SHA512");
let f = |name: &str| b64(t[name].as_str().unwrap());
Rfc {
m: b64(v["m"].as_str().unwrap()),
ctx: b64(v["ctx"].as_str().unwrap()),
pk: f("pk"),
sk: f("sk"),
s: f("s"),
s_with_context: f("sWithContext"),
}
}
#[test]
fn sizes_are_the_rfcs() {
let r = rfc();
assert_eq!((VERIFYING_KEY_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN), (1984, 3373, 64));
assert_eq!((r.pk.len(), r.s.len(), r.s_with_context.len(), r.sk.len()), (1984, 3373, 3373, 64));
assert_eq!(sign::PREFIX, PREFIX);
assert_eq!(sign::LABEL, LABEL);
}
#[test]
fn rfc_private_key_derives_the_rfc_public_key() {
let r = rfc();
let sk = SigningKey::from_bytes(&r.sk).unwrap();
assert_eq!(sk.verifying_key().as_bytes().as_slice(), r.pk.as_slice());
assert_eq!(sk.to_bytes().as_slice(), r.sk.as_slice(), "the private key round-trips (mldsaSeed || edSK)");
}
/// The gap in docs/02_signatures.md: does `verify_strict` accept the RFC's vectors? This answers it.
#[test]
fn rfc_signatures_verify() {
let r = rfc();
let vk = VerifyingKey::from_bytes(&r.pk).unwrap();
let s = Signature::from_bytes(&r.s).unwrap();
let swc = Signature::from_bytes(&r.s_with_context).unwrap();
// Arcanum's raw (hazmat) interface, with the RFC's bare ctx.
assert_eq!(sign::verify_composite_raw(&vk, &r.m, b"", &s), Ok(()), "s (empty ctx)");
assert_eq!(sign::verify_composite_raw(&vk, &r.m, &r.ctx, &swc), Ok(()), "sWithContext");
// The contexts are not interchangeable.
assert_eq!(sign::verify_composite_raw(&vk, &r.m, &r.ctx, &s), Err(Error::InvalidSignature));
assert_eq!(sign::verify_composite_raw(&vk, &r.m, b"", &swc), Err(Error::InvalidSignature));
// The independent rebuild agrees, half by half.
assert_eq!(independent_verify(&r.pk, &r.m, b"", &r.s), (true, true));
assert_eq!(independent_verify(&r.pk, &r.m, &r.ctx, &r.s_with_context), (true, true));
}
#[test]
fn own_signatures_verify_under_an_independent_rebuild_of_m_prime() {
let mut rng = rng(30);
let sk = SigningKey::generate(&mut rng);
let pk = sk.verifying_key().as_bytes().to_vec();
let msg = b"a plan, signed by its author";
// Release API: the ctx is Arcanum's app prefix plus the caller's label.
let ctx = AppContext::new(b"plans").unwrap();
assert_eq!(ctx.as_bytes(), b"domi/arcanum/v2/sig/app/plans");
let sig = sk.sign(msg, &ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&pk, msg, ctx.as_bytes(), sig.as_bytes()), (true, true));
assert_eq!(sk.verifying_key().verify(msg, &ctx, &sig), Ok(()));
// Raw interface: an empty ctx and the longest ctx, 255 bytes.
for ctx in [&b""[..], &[0xa5; 255][..]] {
let sig = sign::sign_composite_raw(&sk, msg, ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&pk, msg, ctx, sig.as_bytes()), (true, true), "ctx of {} bytes", ctx.len());
assert_eq!(sign::verify_composite_raw(sk.verifying_key(), msg, ctx, &sig), Ok(()));
}
// The RFC's own private key, signing the RFC's message: verifies under the RFC's public key.
let r = rfc();
let rfc_sk = SigningKey::from_bytes(&r.sk).unwrap();
let sig = sign::sign_composite_raw(&rfc_sk, &r.m, &r.ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&r.pk, &r.m, &r.ctx, sig.as_bytes()), (true, true));
}
#[test]
fn ml_dsa_half_is_hedged_and_ed25519_half_is_pure() {
let sk = SigningKey::generate(&mut rng(31));
let ctx = AppContext::new(b"hedge").unwrap();
let a = sk.sign(b"same message", &ctx, &mut rng(32)).unwrap();
let b = sk.sign(b"same message", &ctx, &mut rng(33)).unwrap();
let (a, b) = (a.as_bytes(), b.as_bytes());
assert_ne!(a[..ML_DSA_SIG_LEN], b[..ML_DSA_SIG_LEN], "ML-DSA must be hedged: fresh rnd per signature");
assert_eq!(a[ML_DSA_SIG_LEN..], b[ML_DSA_SIG_LEN..], "Ed25519 over the same M' is deterministic");
// The same RNG state gives the same signature: the RNG is the only source of randomness.
let c = sk.sign(b"same message", &ctx, &mut rng(32)).unwrap();
assert_eq!(a, c.as_bytes());
}
#[test]
fn ml_dsa_half_uses_the_label_as_its_context() {
let mut rng = rng(34);
let sk = SigningKey::generate(&mut rng);
let pk = sk.verifying_key().as_bytes().to_vec();
let ctx = AppContext::new(b"label").unwrap();
let sig = sk.sign(b"m", &ctx, &mut rng).unwrap();
let mp = m_prime(b"m", ctx.as_bytes());
let ml_vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_DSA_PK_LEN]).unwrap());
let ml_sig = ml_dsa::Signature::<MlDsa65>::try_from(&sig.as_bytes()[..ML_DSA_SIG_LEN]).unwrap();
assert!(ml_vk.verify_with_context(&mp, LABEL, &ml_sig), "ctx = Label");
assert!(!ml_vk.verify_with_context(&mp, b"", &ml_sig), "not the empty ctx");
assert!(!ml_vk.verify_with_context(&mp, ctx.as_bytes(), &ml_sig), "not the application ctx");
}
+196
View File
@@ -0,0 +1,196 @@
//! Mandatory test 5 (v0.2.0): every byte matters. Flipping any byte of the message, the context,
//! the public key or the signature fails verification. Contexts are prefix-free (the length of
//! ctx is inside M'), and a key-binding signature never verifies as an application message, nor
//! the other way round.
mod common;
use arcanum::Error;
use arcanum::sign::{
self, AppContext, KEM_KEY_CONTEXT, SIGNATURE_LEN, Signature, SigningKey, VERIFYING_KEY_LEN, VerifyingKey,
};
use arcanum::xwing;
use common::rng;
const MSG: &[u8] = b"Built on Domi: every byte of this message is signed.";
fn setup(tag: u8) -> (SigningKey, AppContext, Signature) {
let mut r = rng(tag);
let sk = SigningKey::generate(&mut r);
let c = AppContext::new(b"every-byte").unwrap();
let sig = sk.sign(MSG, &c, &mut r).unwrap();
assert_eq!(sk.verifying_key().verify(MSG, &c, &sig), Ok(()), "control");
(sk, c, sig)
}
#[test]
fn flipping_any_byte_of_the_message_fails() {
let (sk, c, sig) = setup(50);
for i in 0..MSG.len() {
for mask in [0x01, 0x80] {
let mut m = MSG.to_vec();
m[i] ^= mask;
assert_eq!(sk.verifying_key().verify(&m, &c, &sig), Err(Error::InvalidSignature), "byte {i}");
}
}
let mut longer = MSG.to_vec();
longer.push(0);
assert_eq!(sk.verifying_key().verify(&longer, &c, &sig), Err(Error::InvalidSignature), "appended byte");
assert_eq!(sk.verifying_key().verify(&MSG[..MSG.len() - 1], &c, &sig), Err(Error::InvalidSignature));
}
#[test]
fn flipping_any_byte_of_the_context_fails() {
let (sk, c, sig) = setup(51);
let vk = sk.verifying_key();
// Through the release API: every byte of the caller's label.
let label = b"every-byte";
for i in 0..label.len() {
let mut l = label.to_vec();
l[i] ^= 0x01;
assert_eq!(vk.verify(MSG, &AppContext::new(&l).unwrap(), &sig), Err(Error::InvalidSignature), "label byte {i}");
}
// Through the raw interface: every byte of the whole ctx, Arcanum's prefix included.
let full = c.as_bytes().to_vec();
assert_eq!(sign::verify_composite_raw(vk, MSG, &full, &sig), Ok(()), "control");
for i in 0..full.len() {
let mut f = full.clone();
f[i] ^= 0x01;
assert_eq!(sign::verify_composite_raw(vk, MSG, &f, &sig), Err(Error::InvalidSignature), "ctx byte {i}");
}
}
#[test]
fn flipping_any_byte_of_the_public_key_fails() {
let (sk, c, sig) = setup(52);
let pk = *sk.verifying_key().as_bytes();
let (mut refused_at_parse, mut refused_at_verify) = (0, 0);
for i in 0..VERIFYING_KEY_LEN {
let mut b = pk;
b[i] ^= 0x01;
match VerifyingKey::from_bytes(&b) {
Err(e) => {
assert_eq!(e, Error::InvalidVerifyingKey, "byte {i}");
assert!(i >= VERIFYING_KEY_LEN - 32, "byte {i}: only the Ed25519 point can fail to parse");
refused_at_parse += 1;
}
Ok(vk) => {
assert_eq!(vk.verify(MSG, &c, &sig), Err(Error::InvalidSignature), "byte {i}");
refused_at_verify += 1;
}
}
}
assert_eq!(refused_at_parse + refused_at_verify, VERIFYING_KEY_LEN);
assert!(refused_at_verify >= 1952, "every ML-DSA byte reaches verification");
}
#[test]
fn flipping_any_byte_of_the_signature_fails() {
let (sk, c, sig) = setup(53);
for i in 0..SIGNATURE_LEN {
let mut b = *sig.as_bytes();
b[i] ^= 0x01;
let bad = Signature::from_bytes(&b).unwrap();
assert_eq!(sk.verifying_key().verify(MSG, &c, &bad), Err(Error::InvalidSignature), "byte {i}");
}
}
#[test]
fn contexts_are_prefix_free() {
let mut r = rng(54);
let sk = SigningKey::generate(&mut r);
let vk = sk.verifying_key();
let a = AppContext::new(b"a").unwrap();
let ab = AppContext::new(b"ab").unwrap();
let sig_a = sk.sign(MSG, &a, &mut r).unwrap();
let sig_ab = sk.sign(MSG, &ab, &mut r).unwrap();
assert_eq!(vk.verify(MSG, &ab, &sig_a), Err(Error::InvalidSignature), "a is a prefix of ab");
assert_eq!(vk.verify(MSG, &a, &sig_ab), Err(Error::InvalidSignature), "ab extends a");
assert_eq!(vk.verify(MSG, &AppContext::new(b"a\0").unwrap(), &sig_a), Err(Error::InvalidSignature));
// Moving a byte between ctx and message: M' holds SHA-512(M), and u8(len ctx) fixes the split.
assert_eq!(vk.verify(b"bBuilt", &a, &sk.sign(b"Built", &ab, &mut r).unwrap()), Err(Error::InvalidSignature));
// The raw interface: the empty ctx, Arcanum's prefixes and the RFC's empty ctx are all distinct.
let raw_empty = sign::sign_composite_raw(&sk, MSG, b"", &mut r).unwrap();
assert_eq!(sign::verify_composite_raw(vk, MSG, b"\0", &raw_empty), Err(Error::InvalidSignature));
assert_eq!(vk.verify(MSG, &a, &raw_empty), Err(Error::InvalidSignature));
let app_prefix_only = sign::sign_composite_raw(&sk, MSG, b"domi/arcanum/v2/sig/app/", &mut r).unwrap();
assert_eq!(vk.verify(MSG, &a, &app_prefix_only), Err(Error::InvalidSignature));
// Arcanum's fixed contexts: neither is a prefix of the other.
let app = b"domi/arcanum/v2/sig/app/";
assert_eq!(KEM_KEY_CONTEXT, b"domi/arcanum/v2/sig/kem-key");
assert!(!app.starts_with(KEM_KEY_CONTEXT) && !KEM_KEY_CONTEXT.starts_with(app));
}
/// The key-binding message, written out here from docs/02_signatures.md, independently of the code:
/// u8(1) || u64be(not_before) || u64be(not_after) || u16be(len id) || id || xwing_pk.
fn binding_message(id: &[u8], kem: &xwing::PublicKey, (nb, na): (u64, u64)) -> Vec<u8> {
let mut m = vec![1u8];
m.extend_from_slice(&nb.to_be_bytes());
m.extend_from_slice(&na.to_be_bytes());
m.extend_from_slice(&(id.len() as u16).to_be_bytes());
m.extend_from_slice(id);
m.extend_from_slice(kem.as_bytes());
m
}
#[test]
fn a_key_binding_never_verifies_as_an_app_message_and_back() {
let mut r = rng(55);
let sk = SigningKey::generate(&mut r);
let vk = sk.verifying_key();
let kem = xwing::SecretKey::generate(&mut r);
let (id, valid, now) = (b"device-7".as_slice(), (1_000, 2_000), 1_500);
let binding = sign::bind_kem_key(&sk, id, kem.public_key(), valid, &mut r).unwrap();
assert_eq!(sign::verify_binding(vk, id, kem.public_key(), valid, now, &binding), Ok(()), "control");
// The binding is exactly the documented message under the kem-key ctx.
let msg = binding_message(id, kem.public_key(), valid);
assert_eq!(sign::verify_composite_raw(vk, &msg, KEM_KEY_CONTEXT, &binding), Ok(()), "documented encoding");
// As an application message, under any application label: refused.
for label in [&b"kem-key"[..], b"", b"domi/arcanum/v2/sig/kem-key", b"x"] {
if let Ok(c) = AppContext::new(label) {
assert_eq!(vk.verify(&msg, &c, &binding), Err(Error::InvalidSignature), "label {label:?}");
}
}
// The other way round: an application signature over the very same bytes is no binding.
let app_sig = sk.sign(&msg, &AppContext::new(b"kem-key").unwrap(), &mut r).unwrap();
assert_eq!(sign::verify_binding(vk, id, kem.public_key(), valid, now, &app_sig), Err(Error::InvalidSignature));
}
#[test]
fn every_field_of_a_key_binding_matters() {
let mut r = rng(56);
let sk = SigningKey::generate(&mut r);
let vk = sk.verifying_key();
let kem = xwing::SecretKey::generate(&mut r);
let other_kem = xwing::SecretKey::generate(&mut r);
let (id, valid) = (b"device-7".as_slice(), (1_000u64, 2_000u64));
let sig = sign::bind_kem_key(&sk, id, kem.public_key(), valid, &mut r).unwrap();
let check =
|id: &[u8], k: &xwing::PublicKey, v: (u64, u64), now: u64| sign::verify_binding(vk, id, k, v, now, &sig);
assert_eq!(check(id, kem.public_key(), valid, 1_000), Ok(()), "not_before is inclusive");
assert_eq!(check(id, kem.public_key(), valid, 2_000), Ok(()), "not_after is inclusive");
assert_eq!(check(id, kem.public_key(), valid, 999), Err(Error::OutsideValidity));
assert_eq!(check(id, kem.public_key(), valid, 2_001), Err(Error::OutsideValidity));
assert_eq!(check(b"device-8", kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "id");
assert_eq!(check(b"device-7\0", kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "id length");
assert_eq!(check(id, other_kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "X-Wing key");
assert_eq!(check(id, kem.public_key(), (1_000, 2_001), 1_500), Err(Error::InvalidSignature), "not_after");
assert_eq!(check(id, kem.public_key(), (999, 2_000), 1_500), Err(Error::InvalidSignature), "not_before");
// A forged window is refused as a bad signature before its dates are looked at.
assert_eq!(check(id, kem.public_key(), (0, u64::MAX), 5_000), Err(Error::InvalidSignature));
// An inverted window is refused when binding and when verifying.
assert_eq!(sign::bind_kem_key(&sk, id, kem.public_key(), (2, 1), &mut r), Err(Error::InvalidValidity));
assert_eq!(check(id, kem.public_key(), (2_000, 1_000), 1_500), Err(Error::InvalidValidity));
// Every byte of the X-Wing key matters (its encoding is fixed-width and signed whole).
let mut flipped = *kem.public_key().as_bytes();
for i in [0, 600, 1183, 1184, 1215] {
flipped[i] ^= 0x01;
if let Ok(k) = xwing::PublicKey::from_bytes(&flipped) {
assert_eq!(check(id, &k, valid, 1_500), Err(Error::InvalidSignature), "X-Wing byte {i}");
}
flipped[i] ^= 0x01;
}
}
+135
View File
@@ -0,0 +1,135 @@
//! Mandatory test 4 (v0.2.0): both halves of a composite signature are bound. A signature is
//! accepted only when **both** the ML-DSA-65 half and the Ed25519 half verify over this M'.
//!
//! Refused: either half replaced by a valid half of another signature (another message, another
//! key or another context), either half zeroed, the halves swapped. And the ML-DSA half alone is
//! no ordinary ML-DSA signature: an empty-ctx ML-DSA verifier refuses it, on M' and on M.
//!
//! Pinned, not a bug: the composite is not SUF-CMA (RFC 10073 §9.2). Two hedged signatures of the
//! same message by the same key under the same context can trade ML-DSA halves and still verify.
mod common;
use arcanum::Error;
use arcanum::sign::{AppContext, SIGNATURE_LEN, Signature, SigningKey};
use common::rng;
use ml_dsa::MlDsa65;
use ml_dsa::common::array::Array;
use sha2::{Digest, Sha512};
const ML: usize = 3309; // the ML-DSA-65 half comes first
const ML_PK: usize = 1952;
fn ctx(label: &[u8]) -> AppContext {
AppContext::new(label).unwrap()
}
fn splice(ml_from: &Signature, ed_from: &Signature) -> Signature {
let mut b = [0u8; SIGNATURE_LEN];
b[..ML].copy_from_slice(&ml_from.as_bytes()[..ML]);
b[ML..].copy_from_slice(&ed_from.as_bytes()[ML..]);
Signature::from_bytes(&b).unwrap()
}
fn refused(sk: &SigningKey, msg: &[u8], c: &AppContext, sig: &Signature, what: &str) {
assert_eq!(sk.verifying_key().verify(msg, c, sig), Err(Error::InvalidSignature), "{what}");
}
#[test]
fn a_half_from_another_signature_is_refused() {
let mut r = rng(40);
let sk = SigningKey::generate(&mut r);
let other_key = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let msg = b"the message";
let good = sk.sign(msg, &c, &mut r).unwrap();
assert_eq!(sk.verifying_key().verify(msg, &c, &good), Ok(()), "control");
let other_msg = sk.sign(b"another message", &c, &mut r).unwrap();
let other_ctx = sk.sign(msg, &ctx(b"another context"), &mut r).unwrap();
let other_signer = other_key.sign(msg, &c, &mut r).unwrap();
for (donor, what) in
[(&other_msg, "another message"), (&other_ctx, "another context"), (&other_signer, "another key")]
{
refused(&sk, msg, &c, &splice(donor, &good), &format!("ML-DSA half from {what}"));
refused(&sk, msg, &c, &splice(&good, donor), &format!("Ed25519 half from {what}"));
}
}
#[test]
fn a_zeroed_or_missing_half_is_refused() {
let mut r = rng(41);
let sk = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let good = sk.sign(b"m", &c, &mut r).unwrap();
let mut b = *good.as_bytes();
b[..ML].fill(0);
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "ML-DSA half zeroed");
let mut b = *good.as_bytes();
b[ML..].fill(0);
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "Ed25519 half zeroed");
let mut b = *good.as_bytes();
b[ML..].fill(0xff);
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "Ed25519 half all ones");
// A signature with one half cut off is the wrong length, a typed error at parse time.
assert!(Signature::from_bytes(&good.as_bytes()[..ML]).is_err(), "ML-DSA half alone");
assert!(Signature::from_bytes(&good.as_bytes()[ML..]).is_err(), "Ed25519 half alone");
}
#[test]
fn swapped_halves_are_refused() {
let mut r = rng(42);
let sk = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let good = sk.sign(b"m", &c, &mut r).unwrap();
let g = good.as_bytes();
let mut swapped = Vec::with_capacity(SIGNATURE_LEN);
swapped.extend_from_slice(&g[ML..]);
swapped.extend_from_slice(&g[..ML]);
refused(&sk, b"m", &c, &Signature::from_bytes(&swapped).unwrap(), "Ed25519 || ML-DSA");
}
#[test]
fn the_ml_dsa_half_alone_is_not_an_ordinary_ml_dsa_signature() {
let mut r = rng(43);
let sk = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let msg = b"m";
let sig = sk.sign(msg, &c, &mut r).unwrap();
let pk = sk.verifying_key().as_bytes();
let vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_PK]).unwrap());
let half = ml_dsa::Signature::<MlDsa65>::try_from(&sig.as_bytes()[..ML]).unwrap();
let mut mp = Vec::new();
mp.extend_from_slice(b"CompositeAlgorithmSignatures2025COMPSIG-MLDSA65-Ed25519-SHA512");
mp.push(c.as_bytes().len() as u8);
mp.extend_from_slice(c.as_bytes());
mp.extend_from_slice(&Sha512::digest(msg));
// An application that verifies ML-DSA with the empty ctx (as the crate's `Verifier` trait does)
// refuses the half, whether it is shown M' or the message itself.
assert!(!vk.verify_with_context(&mp, b"", &half), "empty ctx over M'");
assert!(!vk.verify_with_context(msg, b"", &half), "empty ctx over M");
assert!(!vk.verify_with_context(msg, b"COMPSIG-MLDSA65-Ed25519-SHA512", &half), "Label ctx over M");
// Control: it is a valid ML-DSA signature over M' under ctx = Label, and nothing else.
assert!(vk.verify_with_context(&mp, b"COMPSIG-MLDSA65-Ed25519-SHA512", &half));
// Likewise the Ed25519 half: it signs M', never the message.
let ed = ed25519_dalek::VerifyingKey::from_bytes(pk[ML_PK..].try_into().unwrap()).unwrap();
let ed_half = ed25519_dalek::Signature::from_slice(&sig.as_bytes()[ML..]).unwrap();
assert!(ed.verify_strict(msg, &ed_half).is_err(), "Ed25519 over M");
assert!(ed.verify_strict(&mp, &ed_half).is_ok(), "control: Ed25519 over M'");
}
/// RFC 10073 §9.2: not SUF-CMA. Pinned so a change in this property is noticed, not hidden.
#[test]
fn halves_of_two_signatures_of_the_same_message_combine_as_the_rfc_says() {
let mut r = rng(44);
let sk = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let a = sk.sign(b"m", &c, &mut r).unwrap();
let b = sk.sign(b"m", &c, &mut r).unwrap();
assert_ne!(a, b, "hedged ML-DSA");
assert_eq!(sk.verifying_key().verify(b"m", &c, &splice(&a, &b)), Ok(()));
assert_eq!(sk.verifying_key().verify(b"m", &c, &splice(&b, &a)), Ok(()));
}
+200
View File
@@ -0,0 +1,200 @@
//! Mandatory test 7 (v0.2.0): hygiene of the signature API.
//!
//! - What a **default-features consumer** can and cannot write, by compiling small programs against
//! Arcanum without `hazmat`, the way `qa_consumer_api.rs` does for v0.1.0 (QA A-33, A-34). The
//! raw RFC interface is `hazmat` only, and none of `ml-dsa`'s own signing internals
//! (`sign_internal` with caller-chosen randomness, `sign_mu_deterministic`, `sign_deterministic`,
//! the `Signer` trait with its empty context) can be reached through Arcanum's types.
//! - The secret types are `ZeroizeOnDrop`, including the component crates' keys (which proves their
//! `zeroize` features are on), and `Debug` never prints key material.
//!
//! The feature graph (no `hazmat` anywhere, `zeroize` on) is checked in `feature_hygiene.rs`, and
//! the heap wiping by the allocator probe in `zeroize-probe/`.
mod common;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use arcanum::sign::{AppContext, SigningKey};
use common::rng;
use zeroize::ZeroizeOnDrop;
/// The cases share one crate (its dependencies are checked once), so they must not run at once.
static LOCK: Mutex<()> = Mutex::new(());
const PRELUDE: &str = r#"
#![allow(unused)]
use core::convert::Infallible;
use rand_core::{TryCryptoRng, TryRng};
/// A counter: deterministic, and therefore NOT a cryptographic RNG.
pub struct Counter(pub u64);
impl TryRng for Counter {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0 += 1; Ok(self.0 as u32) }
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0 += 1; Ok(self.0) }
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> {
for b in d { self.0 += 1; *b = self.0 as u8; }
Ok(())
}
}
/// The same counter, *claiming* to be cryptographic (a stand-in for a real CSPRNG in the control).
pub struct Claimed(pub Counter);
impl TryRng for Claimed {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0.try_next_u32() }
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0.try_next_u64() }
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> { self.0.try_fill_bytes(d) }
}
impl TryCryptoRng for Claimed {}
fn key() -> arcanum::sign::SigningKey { arcanum::sign::SigningKey::generate(&mut Claimed(Counter(0))) }
fn ctx() -> arcanum::sign::AppContext { arcanum::sign::AppContext::new(b"consumer").unwrap() }
"#;
fn consumer_dir() -> PathBuf {
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("sig-consumer-api");
std::fs::create_dir_all(dir.join("src")).unwrap();
let arcanum = env!("CARGO_MANIFEST_DIR").replace('\\', "/");
let manifest = format!(
"[package]\nname = \"sig-consumer-api\"\nversion = \"0.0.0\"\nedition = \"2024\"\npublish = false\n\n\
[dependencies]\narcanum = {{ path = \"{arcanum}\" }}\n\
rand_core = {{ version = \"0.10\", default-features = false }}\n\n[workspace]\n"
);
std::fs::write(dir.join("Cargo.toml"), manifest).unwrap();
if !dir.join("Cargo.lock").exists() {
std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock"), dir.join("Cargo.lock")).unwrap();
}
dir
}
/// `cargo check` a consumer whose `main` body is `body`. Returns (compiled, compiler output).
fn check(body: &str) -> (bool, String) {
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = consumer_dir();
std::fs::write(dir.join("src/main.rs"), format!("{PRELUDE}\nfn main() {{\n{body}\n}}\n")).unwrap();
let out = Command::new(env!("CARGO"))
.current_dir(&dir)
.args(["check", "--offline", "--quiet", "--message-format", "short"])
.env_remove("CARGO_TARGET_DIR")
.output()
.expect("run cargo check");
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned())
}
fn assert_refused(what: &str, body: &str, needles: &[&str]) {
let (ok, err) = check(body);
assert!(!ok, "{what}: compiled against Arcanum with default features, and must not");
assert!(
needles.iter().any(|n| err.contains(n)),
"{what}: refused, but not for the expected reason ({needles:?}):\n{err}"
);
}
#[test]
fn control_the_release_signature_api_compiles_without_hazmat() {
let (ok, err) = check(
r#"
let mut rng = Claimed(Counter(0));
let sk = key();
let sig = sk.sign(b"plan", &ctx(), &mut rng).unwrap();
sk.verifying_key().verify(b"plan", &ctx(), &sig).unwrap();
let vk = arcanum::sign::VerifyingKey::from_bytes(sk.verifying_key().as_bytes()).unwrap();
let sig = arcanum::sign::Signature::from_bytes(sig.as_bytes()).unwrap();
vk.verify(b"plan", &ctx(), &sig).unwrap();
let stored = sk.to_bytes();
let _again = arcanum::sign::SigningKey::from_bytes(stored.as_slice()).unwrap();
let kem = arcanum::xwing::SecretKey::generate(&mut rng);
let b = arcanum::sign::bind_kem_key(&sk, b"id", kem.public_key(), (1, 2), &mut rng).unwrap();
arcanum::sign::verify_binding(&vk, b"id", kem.public_key(), (1, 2), 1, &b).unwrap();
"#,
);
assert!(ok, "the control program must compile, or the harness is blind:\n{err}");
}
/// Like QA A-33: randomness must be `CryptoRng`; a counter is refused everywhere it enters.
#[test]
fn a_non_crypto_rng_does_not_compile() {
let calls = [
("SigningKey::generate", "let _ = arcanum::sign::SigningKey::generate(&mut Counter(0));"),
("SigningKey::sign", "let _ = key().sign(b\"m\", &ctx(), &mut Counter(0));"),
(
"bind_kem_key",
"let kem = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
let _ = arcanum::sign::bind_kem_key(&key(), b\"id\", kem.public_key(), (1, 2), &mut Counter(0));",
),
];
for (what, body) in calls {
assert_refused(what, body, &["CryptoRng"]);
}
}
/// Like QA A-34: the raw RFC 10073 interface (any ctx, including empty) is `hazmat` only.
#[test]
fn the_raw_interface_is_not_reachable_without_hazmat() {
let calls = [
(
"sign_composite_raw",
"let _ = arcanum::sign::sign_composite_raw(&key(), b\"m\", b\"\", &mut Claimed(Counter(0)));",
),
(
"verify_composite_raw",
"let k = key(); let s = k.sign(b\"m\", &ctx(), &mut Claimed(Counter(0))).unwrap(); \
let _ = arcanum::sign::verify_composite_raw(k.verifying_key(), b\"m\", b\"\", &s);",
),
];
for (what, body) in calls {
assert_refused(what, body, &["E0425"]);
}
}
/// `ml-dsa` 0.1.2 makes `ExpandedSigningKey::sign_internal` (caller-chosen randomness) and
/// `sign_mu_deterministic` (panics on failure) public, and its `Signer` trait signs with an
/// empty context. None may be reachable through Arcanum: no re-export, no public field, no
/// `Deref`/`AsRef` to the component keys, and an `AppContext` only from the Arcanum prefix.
#[test]
fn ml_dsa_internals_are_not_reachable() {
let calls: [(&str, &str, &[&str]); 8] = [
("re-export of ml_dsa", "use arcanum::ml_dsa;", &["E0432"]),
("re-export in sign", "use arcanum::sign::ml_dsa;", &["E0432"]),
("sign_internal through the key", "let _ = key().sign_internal(&[b\"m\"], &Default::default());", &["E0599"]),
(
"sign_mu_deterministic through the key",
"let _ = key().sign_mu_deterministic(&Default::default());",
&["E0599"],
),
("sign_deterministic through the key", "let _ = key().sign_deterministic(b\"m\", b\"\");", &["E0599"]),
("a component key field", "let k = key(); let _ = &k.ml;", &["E0609", "E0616"]),
("a foreign or empty context", "let _ = arcanum::sign::AppContext::from_raw(b\"\");", &["E0599"]),
("cloning a signing key", "let k = key(); let _ = k.clone();", &["E0599"]),
];
for (what, body, needles) in calls {
assert_refused(what, body, needles);
}
}
fn assert_zeroize_on_drop<T: ZeroizeOnDrop + ?Sized>() {}
#[test]
fn secret_types_are_zeroize_on_drop() {
assert_zeroize_on_drop::<SigningKey>();
// The component keys Arcanum holds: these bounds hold only with each crate's `zeroize` feature.
assert_zeroize_on_drop::<ml_dsa::ExpandedSigningKey<ml_dsa::MlDsa65>>();
assert_zeroize_on_drop::<ml_dsa::SigningKey<ml_dsa::MlDsa65>>();
assert_zeroize_on_drop::<ed25519_dalek::SigningKey>();
}
#[test]
fn debug_never_prints_key_material() {
let sk = SigningKey::from_bytes(&[0xab; 64]).unwrap();
let dbg = format!("{sk:?}");
assert!(!dbg.contains("ab, ab") && !dbg.contains("abab") && !dbg.contains("171"), "{dbg}");
let seeds = sk.to_bytes();
assert_eq!(seeds.as_slice(), [0xab; 64].as_slice());
let ctx = AppContext::new(b"debug").unwrap();
let sig = sk.sign(b"m", &ctx, &mut rng(70)).unwrap();
let _ = format!("{sig:?} {:?} {ctx:?}", sk.verifying_key());
}
+155
View File
@@ -0,0 +1,155 @@
//! Mandatory test 6 (v0.2.0): malformed signature input gives typed errors, never a panic.
//! Wrong lengths, weak and non-canonical Ed25519 keys, contexts of 0 and 256 bytes, an over-long
//! key id, random bytes. The same entry points are fuzzed by fuzz/fuzz_targets/signatures.rs.
mod common;
use arcanum::sign::{
self, AppContext, MAX_APP_LABEL_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN, Signature, SigningKey, VERIFYING_KEY_LEN,
VerifyingKey,
};
use arcanum::{Error, Input, xwing};
use common::{hex, rng};
use rand_core::Rng;
const LENGTHS: [usize; 14] = [0, 1, 31, 32, 33, 63, 64, 65, 1952, 1983, 1985, 3309, 3372, 3374];
#[test]
fn wrong_lengths_are_typed_errors() {
for len in LENGTHS {
let b = vec![0u8; len];
if len != VERIFYING_KEY_LEN {
assert_eq!(
VerifyingKey::from_bytes(&b).unwrap_err(),
Error::InvalidLength { input: Input::VerifyingKey, expected: VERIFYING_KEY_LEN, actual: len }
);
}
if len != SIGNATURE_LEN {
assert_eq!(
Signature::from_bytes(&b).unwrap_err(),
Error::InvalidLength { input: Input::Signature, expected: SIGNATURE_LEN, actual: len }
);
}
if len != SIGNING_KEY_LEN {
assert_eq!(
SigningKey::from_bytes(&b).unwrap_err(),
Error::InvalidLength { input: Input::SigningKey, expected: SIGNING_KEY_LEN, actual: len }
);
}
}
assert!(SigningKey::from_bytes(&[7u8; SIGNING_KEY_LEN]).is_ok(), "any two 32-byte seeds are a key");
assert!(Signature::from_bytes(&[0u8; SIGNATURE_LEN]).is_ok(), "any 3373 bytes parse; verify decides");
}
/// The small-order points of edwards25519 (the 8-torsion), canonical and non-canonical
/// encodings, and encodings of y >= p. All must be refused as an Ed25519 half.
const WEAK_OR_NON_CANONICAL: [&str; 10] = [
"0100000000000000000000000000000000000000000000000000000000000000", // identity
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // order 2
"0000000000000000000000000000000000000000000000000000000000000000", // order 4
"0000000000000000000000000000000000000000000000000000000000000080", // order 4
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05", // order 8
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85", // order 8
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a", // order 8
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", // order 8
"0100000000000000000000000000000000000000000000000000000000000080", // identity, sign bit set
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // y = p + 1 (non-canonical 1)
];
fn with_ed_half(base: &[u8; VERIFYING_KEY_LEN], ed: &[u8]) -> [u8; VERIFYING_KEY_LEN] {
let mut b = *base;
b[VERIFYING_KEY_LEN - 32..].copy_from_slice(ed);
b
}
#[test]
fn weak_and_non_canonical_ed25519_keys_are_refused() {
let base = *SigningKey::generate(&mut rng(60)).verifying_key().as_bytes();
for h in WEAK_OR_NON_CANONICAL {
let b = with_ed_half(&base, &hex(h));
assert_eq!(VerifyingKey::from_bytes(&b).unwrap_err(), Error::InvalidVerifyingKey, "{h}");
}
// Every y >= p (19 values, sign bit clear and set) is a non-canonical encoding.
for low in 0xedu8..=0xff {
for top in [0x7f, 0xff] {
let mut e = [0xffu8; 32];
e[0] = low;
e[31] = top;
assert_eq!(VerifyingKey::from_bytes(&with_ed_half(&base, &e)).unwrap_err(), Error::InvalidVerifyingKey);
}
}
// An honest key with its sign bit flipped is another valid point: it parses, but cannot verify.
let sk = SigningKey::generate(&mut rng(61));
let c = AppContext::new(b"t").unwrap();
let sig = sk.sign(b"m", &c, &mut rng(62)).unwrap();
let mut b = *sk.verifying_key().as_bytes();
b[VERIFYING_KEY_LEN - 1] ^= 0x80;
if let Ok(vk) = VerifyingKey::from_bytes(&b) {
assert_eq!(vk.verify(b"m", &c, &sig), Err(Error::InvalidSignature));
}
}
#[test]
fn contexts_of_the_wrong_length_are_typed_errors() {
let sk = SigningKey::generate(&mut rng(63));
let vk = sk.verifying_key();
assert_eq!(MAX_APP_LABEL_LEN, 255 - b"domi/arcanum/v2/sig/app/".len());
assert!(AppContext::new(&[b'x'; MAX_APP_LABEL_LEN]).is_ok());
assert_eq!(AppContext::new(&[b'x'; MAX_APP_LABEL_LEN]).unwrap().as_bytes().len(), 255);
assert_eq!(
AppContext::new(&[b'x'; MAX_APP_LABEL_LEN + 1]).unwrap_err(),
Error::TooLong { input: Input::Context, maximum: MAX_APP_LABEL_LEN, actual: MAX_APP_LABEL_LEN + 1 }
);
assert_eq!(AppContext::new(b"").unwrap_err(), Error::TooShort { input: Input::Context, minimum: 1, actual: 0 });
// The raw RFC interface: 255 bytes is the most, 256 is a typed error (sign and verify).
let sig = sign::sign_composite_raw(&sk, b"m", &[1; 255], &mut rng(64)).unwrap();
assert_eq!(sign::verify_composite_raw(vk, b"m", &[1; 255], &sig), Ok(()));
let too_long = Error::TooLong { input: Input::Context, maximum: 255, actual: 256 };
assert_eq!(sign::sign_composite_raw(&sk, b"m", &[1; 256], &mut rng(65)).unwrap_err(), too_long);
assert_eq!(sign::verify_composite_raw(vk, b"m", &[1; 256], &sig), Err(too_long));
}
#[test]
fn an_over_long_key_id_is_a_typed_error() {
let mut r = rng(66);
let sk = SigningKey::generate(&mut r);
let kem = xwing::SecretKey::generate(&mut r);
let id = vec![0u8; 65_536];
let err = Error::TooLong { input: Input::KeyId, maximum: 65_535, actual: 65_536 };
assert_eq!(sign::bind_kem_key(&sk, &id, kem.public_key(), (0, 1), &mut r), Err(err.clone()));
let sig = sign::bind_kem_key(&sk, &id[..65_535], kem.public_key(), (0, 1), &mut r).unwrap();
assert_eq!(sign::verify_binding(sk.verifying_key(), &id[..65_535], kem.public_key(), (0, 1), 0, &sig), Ok(()));
assert_eq!(sign::verify_binding(sk.verifying_key(), &id, kem.public_key(), (0, 1), 0, &sig), Err(err));
// The empty id is allowed (a key bound to "no name" is still bound to this signer).
let sig = sign::bind_kem_key(&sk, b"", kem.public_key(), (0, 1), &mut r).unwrap();
assert_eq!(sign::verify_binding(sk.verifying_key(), b"", kem.public_key(), (0, 1), 1, &sig), Ok(()));
}
#[test]
fn random_bytes_never_panic() {
let mut r = rng(67);
let sk = SigningKey::generate(&mut r);
let c = AppContext::new(b"random").unwrap();
let good = sk.sign(b"m", &c, &mut r).unwrap();
let kem = xwing::SecretKey::generate(&mut r);
for round in 0..256 {
let len = [VERIFYING_KEY_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN, 0, 17][round % 5];
let mut buf = vec![0u8; len];
r.fill_bytes(&mut buf);
if let Ok(vk) = VerifyingKey::from_bytes(&buf) {
assert!(vk.verify(b"m", &c, &good).is_err());
assert!(sign::verify_binding(&vk, b"id", kem.public_key(), (0, 9), 1, &good).is_err());
}
if let Ok(sig) = Signature::from_bytes(&buf) {
assert_eq!(sk.verifying_key().verify(b"m", &c, &sig), Err(Error::InvalidSignature));
let _ = sign::verify_composite_raw(sk.verifying_key(), &buf, &buf[..len.min(255)], &sig);
}
if let Ok(k) = SigningKey::from_bytes(&buf) {
let sig = k.sign(&buf, &c, &mut r).unwrap();
assert_eq!(k.verifying_key().verify(&buf, &c, &sig), Ok(()));
}
// Random labels: typed errors or a context, never a panic.
let _ = AppContext::new(&buf[..len.min(300)]);
}
}
+94 -1
View File
@@ -14,11 +14,13 @@ dependencies = [
[[package]]
name = "arcanum"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"chacha20poly1305",
"ed25519-dalek",
"hkdf",
"hmac",
"ml-dsa",
"ml-kem",
"rand_core",
"sha2",
@@ -44,6 +46,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "block-buffer"
version = "0.12.1"
@@ -103,6 +111,12 @@ 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"
@@ -140,6 +154,7 @@ dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
@@ -157,6 +172,16 @@ dependencies = [
"syn",
]
[[package]]
name = "der"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
dependencies = [
"const-oid",
"zeroize",
]
[[package]]
name = "digest"
version = "0.11.3"
@@ -169,6 +194,28 @@ dependencies = [
"zeroize",
]
[[package]]
name = "ed25519"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
dependencies = [
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2",
"subtle",
"zeroize",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@@ -239,6 +286,22 @@ version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "ml-dsa"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c"
dependencies = [
"crypto-common",
"ctutils",
"hybrid-array",
"module-lattice",
"pkcs8",
"shake",
"signature",
"zeroize",
]
[[package]]
name = "ml-kem"
version = "0.3.4"
@@ -275,6 +338,16 @@ dependencies = [
"autocfg",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "poly1305"
version = "0.9.1"
@@ -357,6 +430,26 @@ dependencies = [
"sponge-cursor",
]
[[package]]
name = "signature"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
dependencies = [
"digest",
"rand_core",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "sponge-cursor"
version = "0.1.0"
+27
View File
@@ -8,6 +8,7 @@
use arcanum::exchange;
use arcanum::seal;
use arcanum::sign::{self, AppContext, SigningKey};
use arcanum::xwing::SecretKey;
use arcanum_zeroize_probe::{CANARY, arm, disarm};
use chacha20::ChaCha20Rng;
@@ -88,4 +89,30 @@ fn secrets_are_wiped_before_their_heap_memory_is_freed() {
let psk = Box::new(is.wireguard_psk(1));
drop((psk, is, rs));
assert!(!disarm(), "an exchange freed its context unwiped");
// --- v0.2.0: signatures ---
// Both seeds are the canary. Building the key runs `ml-dsa`'s `SigningKey::from_seed`, which
// keeps a copy of the ML-DSA seed in a heap box (`alloc`) and wipes it on drop (`zeroize`).
let seeds: Zeroizing<Vec<u8>> = Zeroizing::new([CANARY, CANARY].concat());
arm();
drop(std::hint::black_box(Box::new(SigningKey::from_bytes(&seeds).unwrap())));
assert!(!disarm(), "a boxed signing key (or ml-dsa's seed box) was freed with a seed in memory");
// The exported seeds.
let sk = SigningKey::from_bytes(&seeds).unwrap();
arm();
drop(std::hint::black_box(Box::new(sk.to_bytes())));
assert!(!disarm(), "a boxed to_bytes() copy was freed unwiped");
// Signing, an app message and a key binding, with the canary key; then the key is dropped.
let ctx = AppContext::new(b"probe").unwrap();
let kem = SecretKey::from_bytes(&[9; 32]).unwrap();
arm();
let sk = Box::new(SigningKey::from_bytes(&seeds).unwrap());
let sig = sk.sign(b"message", &ctx, &mut rng(6)).unwrap();
assert_eq!(sk.verifying_key().verify(b"message", &ctx, &sig), Ok(()));
let bound = sign::bind_kem_key(&sk, b"id", kem.public_key(), (0, 1), &mut rng(7)).unwrap();
assert_eq!(sign::verify_binding(sk.verifying_key(), b"id", kem.public_key(), (0, 1), 0, &bound), Ok(()));
drop((sig, bound, sk));
assert!(!disarm(), "signing freed a buffer that held a seed");
}