9f9318664f
ML-DSA-65 keeps large vectors on the stack, and a thread that is too small aborts the process; that is not an Error a caller can handle. Measured here with tests/sig_stack.rs (Windows x86-64, a thread per run): release: 128 KiB overflows, 256/512/1024 KiB pass debug (deps at opt-level 2): 128 and 256 KiB overflow, 512/1024 KiB pass SigningKey's docs now say so and advise at least 512 KiB for threads that sign. generate_and_sign_fit_in_256_kib_of_stack pins the release figure (ignored in debug builds); the four on_a_<n>_kib_stack measurements are ignored and run by hand, one at a time.
471 lines
20 KiB
Rust
471 lines
20 KiB
Rust
//! Hybrid post-quantum signatures: ML-DSA-65 + Ed25519, exactly RFC 10073
|
||
//! `id-MLDSA65-Ed25519-SHA512` (OID 1.3.6.1.5.5.7.6.48). A signature stays unforgeable while
|
||
//! either ML-DSA-65 or Ed25519 does.
|
||
//!
|
||
//! ```text
|
||
//! Prefix = "CompositeAlgorithmSignatures2025" Label = "COMPSIG-MLDSA65-Ed25519-SHA512"
|
||
//! M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) (RFC 10073 §3.2)
|
||
//! sig = ML-DSA-65.Sign(sk_ml, M', ctx = Label) hedged, 3309 bytes
|
||
//! || Ed25519.Sign(sk_ed, M') pure Ed25519, 64 bytes
|
||
//! valid iff ML-DSA-65.Verify(pk_ml, M', sig_ml, ctx = Label) and Ed25519 verify_strict(pk_ed, M', sig_ed)
|
||
//! public key = pk_ml (1952 bytes) || pk_ed (32 bytes)
|
||
//! private key = ML-DSA seed (32 bytes) || Ed25519 seed (32 bytes)
|
||
//! ```
|
||
//!
|
||
//! This module is glue: ML-DSA-65 from `ml-dsa` (FIPS 204), Ed25519 from `ed25519-dalek` (RFC 8032),
|
||
//! SHA-512 from `sha2`. It never uses `ml-dsa`'s `Signer`/`Verifier` traits (deterministic, empty
|
||
//! ctx), only `ExpandedSigningKey::sign_randomized` and `VerifyingKey::verify_with_context`.
|
||
//!
|
||
//! **Contexts.** The RFC's `ctx` is a domain separator. Arcanum fixes it per purpose:
|
||
//! [`KEM_KEY_CONTEXT`] for [`bind_kem_key`], and [`APP_CONTEXT_PREFIX`] + the caller's label for
|
||
//! [`SigningKey::sign`], through [`AppContext`]. A signature made for one context never verifies
|
||
//! under another: `ctx` and its length are inside M'.
|
||
//!
|
||
//! **Stricter than the RFC**, invisible to honest signers: a verifying key whose Ed25519 half is a
|
||
//! small-order point or not the canonical encoding of its point, or whose ML-DSA-65 half has
|
||
//! t1 = 0, is refused when parsed ([`Error::InvalidVerifyingKey`]), and Ed25519 is checked with
|
||
//! `verify_strict`. Both refused shapes are "weak keys": with t1 = 0 an ML-DSA signature needs no
|
||
//! secret at all (QA S-05), as a small-order Ed25519 key lets signatures verify for many messages.
|
||
//!
|
||
//! **Not SUF-CMA** (RFC 10073 §9.2): two signatures of one message under one key can trade their
|
||
//! hedged ML-DSA halves. Never use a signature as an identifier.
|
||
//!
|
||
//! The bare RFC interface (any `ctx`, including empty) is `hazmat` only, for the RFC's vectors.
|
||
|
||
use alloc::boxed::Box;
|
||
use core::{array, fmt};
|
||
|
||
use ed25519_dalek::Signer as _;
|
||
use ml_dsa::{EncodedSignature, EncodedVerifyingKey, ExpandedSigningKey, MlDsa65, Seed};
|
||
use rand_core::CryptoRng;
|
||
use sha2::{Digest, Sha512};
|
||
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
|
||
|
||
use crate::error::{Error, Input, exact};
|
||
use crate::xwing;
|
||
|
||
/// RFC 10073 §2.2: the prefix of every composite M'.
|
||
pub const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
|
||
/// RFC 10073 §6: the label of `id-MLDSA65-Ed25519-SHA512`, also ML-DSA's own `ctx`.
|
||
pub const LABEL: &[u8] = b"COMPSIG-MLDSA65-Ed25519-SHA512";
|
||
|
||
/// The context of a key binding ([`bind_kem_key`]).
|
||
pub const KEM_KEY_CONTEXT: &[u8] = b"domi/arcanum/v2/sig/kem-key";
|
||
/// The prefix of every application context ([`AppContext`]).
|
||
pub const APP_CONTEXT_PREFIX: &[u8] = b"domi/arcanum/v2/sig/app/";
|
||
/// The longest `ctx` RFC 10073 allows (it is encoded as one byte in M').
|
||
pub const MAX_CONTEXT_LEN: usize = 255;
|
||
/// The longest label an [`AppContext`] can take: 255 minus the 24-byte prefix.
|
||
pub const MAX_APP_LABEL_LEN: usize = MAX_CONTEXT_LEN - APP_CONTEXT_PREFIX.len();
|
||
/// The longest key id in a key binding (its length is a big-endian `u16`).
|
||
pub const MAX_KEY_ID_LEN: usize = u16::MAX as usize;
|
||
/// The version byte at the start of every key-binding message.
|
||
pub const KEY_BINDING_VERSION: u8 = 1;
|
||
|
||
/// Length of a composite verifying key: ML-DSA-65 public key (1952) + Ed25519 public key (32).
|
||
pub const VERIFYING_KEY_LEN: usize = 1984;
|
||
/// Length of a stored composite signing key: two 32-byte seeds.
|
||
pub const SIGNING_KEY_LEN: usize = 64;
|
||
/// Length of a composite signature: ML-DSA-65 signature (3309) + Ed25519 signature (64).
|
||
pub const SIGNATURE_LEN: usize = 3373;
|
||
|
||
const ML_DSA_PUBLIC_KEY_LEN: usize = 1952;
|
||
const ML_DSA_SIGNATURE_LEN: usize = 3309;
|
||
const ML_DSA_RHO_LEN: usize = 32;
|
||
const SEED_LEN: usize = 32;
|
||
const M_PRIME_MAX_LEN: usize = 32 + 30 + 1 + MAX_CONTEXT_LEN + 64;
|
||
|
||
// The fixed lengths above are the crates' own; a crate update that changed one fails to compile.
|
||
const _: () = assert!(PREFIX.len() == 32 && LABEL.len() == 30);
|
||
const _: () = assert!(core::mem::size_of::<EncodedVerifyingKey<MlDsa65>>() == ML_DSA_PUBLIC_KEY_LEN);
|
||
const _: () = assert!(core::mem::size_of::<EncodedSignature<MlDsa65>>() == ML_DSA_SIGNATURE_LEN);
|
||
const _: () = assert!(VERIFYING_KEY_LEN == ML_DSA_PUBLIC_KEY_LEN + ed25519_dalek::PUBLIC_KEY_LENGTH);
|
||
const _: () = assert!(SIGNATURE_LEN == ML_DSA_SIGNATURE_LEN + ed25519_dalek::SIGNATURE_LENGTH);
|
||
|
||
/// An application context: [`APP_CONTEXT_PREFIX`] followed by the caller's label, 25 to 255 bytes
|
||
/// in all. It can only be built with that prefix, so a caller cannot pass an empty context, the
|
||
/// key-binding context or a foreign one by accident.
|
||
///
|
||
/// The label is `&'static` (QA S-09): one fixed label per purpose, written in the source, never
|
||
/// derived from a peer name, a file name or a message field (two purposes whose labels came from
|
||
/// data could collide). Build it once, at compile time:
|
||
///
|
||
/// ```
|
||
/// use arcanum::sign::AppContext;
|
||
/// const PLANS: AppContext = match AppContext::new(b"plans") {
|
||
/// Ok(ctx) => ctx,
|
||
/// Err(_) => panic!("label is 1 to 231 bytes"),
|
||
/// };
|
||
/// assert_eq!(PLANS.as_bytes(), b"domi/arcanum/v2/sig/app/plans");
|
||
/// ```
|
||
#[derive(Clone, PartialEq, Eq)]
|
||
pub struct AppContext {
|
||
bytes: [u8; MAX_CONTEXT_LEN],
|
||
len: usize,
|
||
}
|
||
|
||
impl AppContext {
|
||
/// `domi/arcanum/v2/sig/app/` + `label`, for a fixed, compile-time label (Day 3: `plans`).
|
||
/// A `const fn`, so a `const` context is checked when the consumer compiles.
|
||
///
|
||
/// # Errors
|
||
/// [`Error::TooShort`] for an empty label; [`Error::TooLong`] for one over
|
||
/// [`MAX_APP_LABEL_LEN`] (231) bytes.
|
||
pub const fn new(label: &'static [u8]) -> Result<Self, Error> {
|
||
if label.is_empty() {
|
||
return Err(Error::TooShort { input: Input::Context, minimum: 1, actual: 0 });
|
||
}
|
||
if label.len() > MAX_APP_LABEL_LEN {
|
||
return Err(Error::TooLong { input: Input::Context, maximum: MAX_APP_LABEL_LEN, actual: label.len() });
|
||
}
|
||
let mut bytes = [0u8; MAX_CONTEXT_LEN];
|
||
let p = APP_CONTEXT_PREFIX.len();
|
||
let mut i = 0;
|
||
while i < p {
|
||
bytes[i] = APP_CONTEXT_PREFIX[i];
|
||
i += 1;
|
||
}
|
||
let mut j = 0;
|
||
while j < label.len() {
|
||
bytes[p + j] = label[j];
|
||
j += 1;
|
||
}
|
||
Ok(Self { bytes, len: p + label.len() })
|
||
}
|
||
|
||
/// The whole context, prefix included: the RFC's `ctx`.
|
||
#[must_use]
|
||
pub fn as_bytes(&self) -> &[u8] {
|
||
&self.bytes[..self.len]
|
||
}
|
||
}
|
||
|
||
impl fmt::Debug for AppContext {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
f.debug_tuple("AppContext").field(&self.as_bytes().escape_ascii()).finish()
|
||
}
|
||
}
|
||
|
||
/// M' (RFC 10073 §3.2), built on the stack: at most 382 bytes.
|
||
struct MPrime {
|
||
bytes: [u8; M_PRIME_MAX_LEN],
|
||
len: usize,
|
||
}
|
||
|
||
impl MPrime {
|
||
/// M' from the message's SHA-512, which the caller computed (all at once, or field by field).
|
||
fn new(ph: &[u8; 64], ctx: &[u8]) -> Result<Self, Error> {
|
||
let ctx_len = u8::try_from(ctx.len()).map_err(|_| Error::TooLong {
|
||
input: Input::Context,
|
||
maximum: MAX_CONTEXT_LEN,
|
||
actual: ctx.len(),
|
||
})?;
|
||
let mut m = Self { bytes: [0u8; M_PRIME_MAX_LEN], len: 0 };
|
||
for part in [PREFIX, LABEL, &[ctx_len], ctx, ph] {
|
||
m.bytes[m.len..m.len + part.len()].copy_from_slice(part);
|
||
m.len += part.len();
|
||
}
|
||
Ok(m)
|
||
}
|
||
|
||
fn of_message(msg: &[u8], ctx: &[u8]) -> Result<Self, Error> {
|
||
Self::new(&Sha512::digest(msg).into(), ctx)
|
||
}
|
||
|
||
fn as_bytes(&self) -> &[u8] {
|
||
&self.bytes[..self.len]
|
||
}
|
||
}
|
||
|
||
/// A composite verifying key (`pk_ml || pk_ed`), validated on parse.
|
||
#[derive(Clone)]
|
||
pub struct VerifyingKey {
|
||
bytes: [u8; VERIFYING_KEY_LEN],
|
||
ml: ml_dsa::VerifyingKey<MlDsa65>,
|
||
ed: ed25519_dalek::VerifyingKey,
|
||
}
|
||
|
||
impl VerifyingKey {
|
||
/// Parse a composite verifying key received from somewhere else.
|
||
///
|
||
/// # Errors
|
||
/// [`Error::InvalidLength`] if it is not 1984 bytes; [`Error::InvalidVerifyingKey`] if the
|
||
/// Ed25519 half is not a point, is not the canonical encoding of its point, or has small order,
|
||
/// or if the ML-DSA-65 half's t1 (its bytes 32..1952) is all zero. Every other 1952-byte
|
||
/// ML-DSA-65 public key is well formed (FIPS 204 `pkDecode` cannot fail).
|
||
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
|
||
let bytes: &[u8; VERIFYING_KEY_LEN] = exact(Input::VerifyingKey, bytes)?;
|
||
let ed_bytes: [u8; 32] = array::from_fn(|i| bytes[ML_DSA_PUBLIC_KEY_LEN + i]);
|
||
let ed = ed25519_dalek::VerifyingKey::from_bytes(&ed_bytes).map_err(|_| Error::InvalidVerifyingKey)?;
|
||
// `from_bytes` accepts y >= p and a set sign bit on x = 0 (RFC 8032 §5.1.3 says to refuse
|
||
// them); re-encoding the point and comparing refuses every non-canonical encoding.
|
||
if ed.is_weak() || ed.to_edwards().compress().to_bytes() != ed_bytes {
|
||
return Err(Error::InvalidVerifyingKey);
|
||
}
|
||
// t1 = 0 (Wycheproof's `ZeroPublicKey`): ML-DSA verification then checks only
|
||
// c~ = H(mu || w1(A·z)), which anyone can satisfy with s1 = s2 = t0 = 0. An honest key has
|
||
// t1 = 0 with negligible probability.
|
||
if bytes[ML_DSA_RHO_LEN..ML_DSA_PUBLIC_KEY_LEN].iter().all(|&b| b == 0) {
|
||
return Err(Error::InvalidVerifyingKey);
|
||
}
|
||
let enc = EncodedVerifyingKey::<MlDsa65>::try_from(&bytes[..ML_DSA_PUBLIC_KEY_LEN])
|
||
.map_err(|_| Error::InvalidVerifyingKey)?;
|
||
let ml = ml_dsa::VerifyingKey::<MlDsa65>::decode(&enc);
|
||
Ok(Self { bytes: *bytes, ml, ed })
|
||
}
|
||
|
||
/// The 1984-byte encoding.
|
||
#[must_use]
|
||
pub fn as_bytes(&self) -> &[u8; VERIFYING_KEY_LEN] {
|
||
&self.bytes
|
||
}
|
||
|
||
/// Verify a signature over `msg` made with [`SigningKey::sign`] under the same context.
|
||
///
|
||
/// # Errors
|
||
/// [`Error::InvalidSignature`] if either half (or both) fails. The error does not say which
|
||
/// half failed; the time taken may (a malformed ML-DSA half is refused at decode, and
|
||
/// `verify_strict` stops early on a bad R). That is fine: verification handles only public data,
|
||
/// so its timing reveals nothing secret (RFC 10073 §3.3 allows failing early; QA S-06).
|
||
pub fn verify(&self, msg: &[u8], ctx: &AppContext, sig: &Signature) -> Result<(), Error> {
|
||
self.verify_m_prime(&MPrime::of_message(msg, ctx.as_bytes())?, sig)
|
||
}
|
||
|
||
fn verify_m_prime(&self, mp: &MPrime, sig: &Signature) -> Result<(), Error> {
|
||
let mp = mp.as_bytes();
|
||
// A malformed ML-DSA half (bad hint encoding, z out of range) is refused at decode, without
|
||
// the verification step: quicker, and visible in the timing, but everything here is public.
|
||
let ml_ok = ml_dsa::Signature::<MlDsa65>::try_from(&sig.0[..ML_DSA_SIGNATURE_LEN])
|
||
.is_ok_and(|s| self.ml.verify_with_context(mp, LABEL, &s));
|
||
let ed_sig = ed25519_dalek::Signature::from_bytes(&array::from_fn(|i| sig.0[ML_DSA_SIGNATURE_LEN + i]));
|
||
let ed_ok = self.ed.verify_strict(mp, &ed_sig).is_ok();
|
||
if ml_ok && ed_ok { Ok(()) } else { Err(Error::InvalidSignature) }
|
||
}
|
||
}
|
||
|
||
impl PartialEq for VerifyingKey {
|
||
fn eq(&self, other: &Self) -> bool {
|
||
self.bytes == other.bytes
|
||
}
|
||
}
|
||
|
||
impl Eq for VerifyingKey {}
|
||
|
||
impl fmt::Debug for VerifyingKey {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
f.debug_struct("VerifyingKey").field("len", &VERIFYING_KEY_LEN).finish_non_exhaustive()
|
||
}
|
||
}
|
||
|
||
/// A composite signature (`sig_ml || sig_ed`). Any 3373 bytes parse; verification decides.
|
||
#[derive(Clone, PartialEq, Eq)]
|
||
pub struct Signature([u8; SIGNATURE_LEN]);
|
||
|
||
impl Signature {
|
||
/// Parse a signature.
|
||
///
|
||
/// # Errors
|
||
/// [`Error::InvalidLength`] if it is not 3373 bytes.
|
||
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
|
||
exact(Input::Signature, bytes).map(|b| Self(*b))
|
||
}
|
||
|
||
/// The 3373-byte encoding.
|
||
#[must_use]
|
||
pub fn as_bytes(&self) -> &[u8; SIGNATURE_LEN] {
|
||
&self.0
|
||
}
|
||
}
|
||
|
||
impl fmt::Debug for Signature {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
f.debug_struct("Signature").field("len", &SIGNATURE_LEN).finish_non_exhaustive()
|
||
}
|
||
}
|
||
|
||
/// A composite signing key: two independent 32-byte seeds and the keys expanded from them, all
|
||
/// zeroised on drop. Not `Clone`; `Debug` prints nothing secret.
|
||
///
|
||
/// **Stack** (QA S-11): building a key ([`SigningKey::generate`], [`SigningKey::from_bytes`]) and
|
||
/// signing keep ML-DSA-65's polynomial vectors on the stack. Measured on Windows x86-64
|
||
/// (`tests/sig_stack.rs`): a release build needs more than 128 KiB and fits in 256 KiB; a debug
|
||
/// build (with dependencies at `opt-level = 2`, as in Arcanum's own profile) needs more than
|
||
/// 256 KiB and fits in 512 KiB. Too small a thread **aborts the process** with a stack overflow;
|
||
/// it is not an error that can be caught. Default threads (1–2 MiB) are fine; give worker,
|
||
/// blocking-pool or JNI threads that sign at least 512 KiB, and measure unoptimised debug builds.
|
||
pub struct SigningKey {
|
||
seeds: Zeroizing<[u8; SIGNING_KEY_LEN]>,
|
||
// Boxed: the expanded ML-DSA-65 key is about 64 kB.
|
||
ml: Box<ExpandedSigningKey<MlDsa65>>,
|
||
ed: ed25519_dalek::SigningKey,
|
||
public: VerifyingKey,
|
||
}
|
||
|
||
impl SigningKey {
|
||
/// Generate a new key pair from the caller's RNG: 64 fresh bytes, both seeds at once.
|
||
///
|
||
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
|
||
/// once per process; never a fixed, derived or configured seed (QA R2-04).
|
||
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
|
||
let mut seeds = Zeroizing::new([0u8; SIGNING_KEY_LEN]);
|
||
rng.fill_bytes(seeds.as_mut_slice());
|
||
Self::expand(seeds)
|
||
}
|
||
|
||
/// Parse a stored signing key: the ML-DSA-65 seed, then the Ed25519 seed (RFC 10073's
|
||
/// private key format).
|
||
///
|
||
/// # Errors
|
||
/// [`Error::InvalidLength`] if it is not 64 bytes. Every 64-byte value is a valid key.
|
||
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
|
||
let seeds: &[u8; SIGNING_KEY_LEN] = exact(Input::SigningKey, bytes)?;
|
||
Ok(Self::expand(Zeroizing::new(*seeds)))
|
||
}
|
||
|
||
/// The 64 bytes to store in Custos or Tessera. Handle with care.
|
||
#[must_use]
|
||
pub fn to_bytes(&self) -> Zeroizing<[u8; SIGNING_KEY_LEN]> {
|
||
Zeroizing::new(*self.seeds)
|
||
}
|
||
|
||
/// The matching verifying key.
|
||
#[must_use]
|
||
pub fn verifying_key(&self) -> &VerifyingKey {
|
||
&self.public
|
||
}
|
||
|
||
/// Sign `msg` under an application context. The ML-DSA half is hedged: 32 fresh bytes come
|
||
/// from `rng`, which must be the OS RNG or a CSPRNG seeded from it (see [`SigningKey::generate`]).
|
||
///
|
||
/// # Errors
|
||
/// [`Error::SigningFailed`] if the RNG fails or ML-DSA's rejection sampling gives up (it is
|
||
/// bounded; with a working RNG this does not happen in practice). Retry with fresh randomness.
|
||
pub fn sign<R: CryptoRng + ?Sized>(&self, msg: &[u8], ctx: &AppContext, rng: &mut R) -> Result<Signature, Error> {
|
||
self.sign_m_prime(&MPrime::of_message(msg, ctx.as_bytes())?, rng)
|
||
}
|
||
|
||
fn sign_m_prime<R: CryptoRng + ?Sized>(&self, mp: &MPrime, rng: &mut R) -> Result<Signature, Error> {
|
||
let mp = mp.as_bytes();
|
||
let ml = self.ml.sign_randomized(mp, LABEL, rng).map_err(|_| Error::SigningFailed)?;
|
||
let ed = self.ed.try_sign(mp).map_err(|_| Error::SigningFailed)?;
|
||
let mut out = [0u8; SIGNATURE_LEN];
|
||
out[..ML_DSA_SIGNATURE_LEN].copy_from_slice(ml.encode().as_slice());
|
||
out[ML_DSA_SIGNATURE_LEN..].copy_from_slice(&ed.to_bytes());
|
||
Ok(Signature(out))
|
||
}
|
||
|
||
fn expand(seeds: Zeroizing<[u8; SIGNING_KEY_LEN]>) -> Self {
|
||
let mut ml_seed = Seed::default();
|
||
ml_seed.as_mut_slice().copy_from_slice(&seeds[..SEED_LEN]);
|
||
let ml = Box::new(ExpandedSigningKey::<MlDsa65>::from_seed(&ml_seed));
|
||
ml_seed.as_mut_slice().zeroize();
|
||
|
||
let mut ed_seed = Zeroizing::new([0u8; SEED_LEN]);
|
||
ed_seed.copy_from_slice(&seeds[SEED_LEN..]);
|
||
let ed = ed25519_dalek::SigningKey::from_bytes(&ed_seed);
|
||
|
||
let ml_pk = ml.verifying_key();
|
||
let ed_pk = ed.verifying_key();
|
||
let mut bytes = [0u8; VERIFYING_KEY_LEN];
|
||
bytes[..ML_DSA_PUBLIC_KEY_LEN].copy_from_slice(ml_pk.encode().as_slice());
|
||
bytes[ML_DSA_PUBLIC_KEY_LEN..].copy_from_slice(ed_pk.as_bytes());
|
||
Self { seeds, ml, ed, public: VerifyingKey { bytes, ml: ml_pk, ed: ed_pk } }
|
||
}
|
||
}
|
||
|
||
impl fmt::Debug for SigningKey {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
f.write_str("SigningKey([redacted])")
|
||
}
|
||
}
|
||
|
||
// `seeds` is `Zeroizing`; `ml-dsa`'s `ExpandedSigningKey` and `ed25519-dalek`'s `SigningKey` wipe
|
||
// themselves on drop (their `zeroize` features are enabled in Cargo.toml, and
|
||
// tests/sig_hygiene.rs asserts the bounds).
|
||
impl ZeroizeOnDrop for SigningKey {}
|
||
|
||
/// SHA-512 of the key-binding message
|
||
/// `u8(1) || u64be(not_before) || u64be(not_after) || u16be(len(id)) || id || xwing_pk (1216 bytes)`,
|
||
/// fed field by field. Fixed widths and one length prefix: the encoding is injective.
|
||
fn binding_digest(id: &[u8], kem: &xwing::PublicKey, (not_before, not_after): (u64, u64)) -> Result<[u8; 64], Error> {
|
||
if not_before > not_after {
|
||
return Err(Error::InvalidValidity);
|
||
}
|
||
let id_len = u16::try_from(id.len()).map_err(|_| Error::TooLong {
|
||
input: Input::KeyId,
|
||
maximum: MAX_KEY_ID_LEN,
|
||
actual: id.len(),
|
||
})?;
|
||
let mut h = Sha512::new();
|
||
h.update([KEY_BINDING_VERSION]);
|
||
h.update(not_before.to_be_bytes());
|
||
h.update(not_after.to_be_bytes());
|
||
h.update(id_len.to_be_bytes());
|
||
h.update(id);
|
||
h.update(kem.as_bytes());
|
||
Ok(h.finalize().into())
|
||
}
|
||
|
||
/// Sign "this X-Wing public key belongs to `id` from `valid.0` to `valid.1` (inclusive, the
|
||
/// caller's clock, usually Unix seconds)", under [`KEM_KEY_CONTEXT`].
|
||
///
|
||
/// # Errors
|
||
/// [`Error::InvalidValidity`] if `valid.0 > valid.1`; [`Error::TooLong`] for an id over 65,535
|
||
/// bytes; [`Error::SigningFailed`] as for [`SigningKey::sign`].
|
||
pub fn bind_kem_key<R: CryptoRng + ?Sized>(
|
||
sk: &SigningKey,
|
||
id: &[u8],
|
||
kem: &xwing::PublicKey,
|
||
valid: (u64, u64),
|
||
rng: &mut R,
|
||
) -> Result<Signature, Error> {
|
||
sk.sign_m_prime(&MPrime::new(&binding_digest(id, kem, valid)?, KEM_KEY_CONTEXT)?, rng)
|
||
}
|
||
|
||
/// Check a key binding made by [`bind_kem_key`], at time `now` (Arcanum has no clock).
|
||
///
|
||
/// # Errors
|
||
/// In this order: [`Error::InvalidValidity`] or [`Error::TooLong`] for a malformed window or id;
|
||
/// [`Error::InvalidSignature`] if the binding is not authentic; [`Error::OutsideValidity`] if it is
|
||
/// authentic but `now` is before `valid.0` or after `valid.1`.
|
||
pub fn verify_binding(
|
||
vk: &VerifyingKey,
|
||
id: &[u8],
|
||
kem: &xwing::PublicKey,
|
||
valid: (u64, u64),
|
||
now: u64,
|
||
sig: &Signature,
|
||
) -> Result<(), Error> {
|
||
vk.verify_m_prime(&MPrime::new(&binding_digest(id, kem, valid)?, KEM_KEY_CONTEXT)?, sig)?;
|
||
if !(valid.0..=valid.1).contains(&now) {
|
||
return Err(Error::OutsideValidity);
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// RFC 10073 composite signing with the bare `ctx` (0 to 255 bytes, empty allowed), for the RFC's
|
||
/// own vectors. **Hazmat** (feature `hazmat`): release code signs through [`AppContext`] or
|
||
/// [`bind_kem_key`], so its contexts can never collide. The ML-DSA half is still hedged; a test
|
||
/// that needs repeatable bytes passes a seeded RNG.
|
||
///
|
||
/// # Errors
|
||
/// [`Error::TooLong`] for a `ctx` over 255 bytes; [`Error::SigningFailed`].
|
||
#[cfg(feature = "hazmat")]
|
||
pub fn sign_composite_raw<R: CryptoRng + ?Sized>(
|
||
sk: &SigningKey,
|
||
msg: &[u8],
|
||
ctx: &[u8],
|
||
rng: &mut R,
|
||
) -> Result<Signature, Error> {
|
||
sk.sign_m_prime(&MPrime::of_message(msg, ctx)?, rng)
|
||
}
|
||
|
||
/// RFC 10073 composite verification with the bare `ctx`. **Hazmat** (feature `hazmat`).
|
||
///
|
||
/// # Errors
|
||
/// [`Error::TooLong`] for a `ctx` over 255 bytes; [`Error::InvalidSignature`].
|
||
#[cfg(feature = "hazmat")]
|
||
pub fn verify_composite_raw(vk: &VerifyingKey, msg: &[u8], ctx: &[u8], sig: &Signature) -> Result<(), Error> {
|
||
vk.verify_m_prime(&MPrime::of_message(msg, ctx)?, sig)
|
||
}
|