feat: hybrid signatures ML-DSA-65 + Ed25519, RFC 10073 id-MLDSA65-Ed25519-SHA512
arcanum::sign, as docs/02_signatures.md sets out. M' = Prefix || Label || u8(len ctx) || ctx || SHA-512(M), built on the stack. The ML-DSA-65 half is ExpandedSigningKey::sign_randomized(M', ctx = Label, rng), hedged; the Ed25519 half is pure Ed25519 over M' (try_sign), checked with verify_strict. Verification computes both halves before answering, and returns one InvalidSignature whichever failed. ml-dsa's Signer/Verifier traits, sign_deterministic and sign_mu_deterministic are never called. - SigningKey: two 32-byte seeds (RFC 10073's private key format), the expanded ML-DSA key boxed; ZeroizeOnDrop, not Clone, Debug redacted. - VerifyingKey: 1984 bytes; refuses an Ed25519 half that is not a point, not its canonical encoding, or of small order (InvalidVerifyingKey). - AppContext: only "domi/arcanum/v2/sig/app/" + a 1..=231-byte label. - bind_kem_key / verify_binding: an X-Wing public key bound to a key id and an inclusive validity window under "domi/arcanum/v2/sig/kem-key"; the message is hashed field by field; window and id are checked first, then the signature, then now (InvalidValidity, TooLong, InvalidSignature, OutsideValidity). - sign_composite_raw / verify_composite_raw: the bare RFC ctx, hazmat only. They still take an RNG (the ML-DSA half stays hedged), not the deterministic variant the doc mentions. - Error gains TooLong, InvalidVerifyingKey, InvalidSignature, SigningFailed, InvalidValidity, OutsideValidity; Input gains SigningKey, VerifyingKey, Signature, Context, KeyId. Also fixes tests/kat_mldsa65.rs, which passed a &[&Vec<u8>] to sign_internal and did not compile. cargo test (debug): 121 passed, 0 failed (82 from v0.1.0, golden_v1 unchanged). clippy --all-targets --all-features -D warnings: clean.
This commit is contained in:
@@ -14,6 +14,16 @@ pub enum Input {
|
||||
Ciphertext,
|
||||
/// A sealed box.
|
||||
SealedBox,
|
||||
/// A composite signing key (ML-DSA-65 seed || Ed25519 seed).
|
||||
SigningKey,
|
||||
/// A composite verifying key (ML-DSA-65 public key || Ed25519 public key).
|
||||
VerifyingKey,
|
||||
/// A composite signature (ML-DSA-65 signature || Ed25519 signature).
|
||||
Signature,
|
||||
/// A signature context, or the caller's label inside one.
|
||||
Context,
|
||||
/// The key id in a key binding.
|
||||
KeyId,
|
||||
}
|
||||
|
||||
impl fmt::Display for Input {
|
||||
@@ -23,6 +33,11 @@ impl fmt::Display for Input {
|
||||
Input::SecretKey => "secret key",
|
||||
Input::Ciphertext => "ciphertext",
|
||||
Input::SealedBox => "sealed box",
|
||||
Input::SigningKey => "signing key",
|
||||
Input::VerifyingKey => "verifying key",
|
||||
Input::Signature => "signature",
|
||||
Input::Context => "signature context",
|
||||
Input::KeyId => "key id",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -49,6 +64,15 @@ pub enum Error {
|
||||
/// The length that was given.
|
||||
actual: usize,
|
||||
},
|
||||
/// The input is longer than the largest valid value.
|
||||
TooLong {
|
||||
/// What was being parsed.
|
||||
input: Input,
|
||||
/// The maximum length in bytes.
|
||||
maximum: usize,
|
||||
/// The length that was given.
|
||||
actual: usize,
|
||||
},
|
||||
/// The ML-KEM-768 part of a public key fails the FIPS 203 §7.2 encapsulation key check.
|
||||
InvalidPublicKey,
|
||||
/// An X25519 value is a low-order point, so the classical half would contribute nothing.
|
||||
@@ -59,6 +83,18 @@ pub enum Error {
|
||||
DecryptionFailed,
|
||||
/// The plaintext is longer than ChaCha20-Poly1305 allows (about 256 GiB).
|
||||
MessageTooLong,
|
||||
/// The Ed25519 half of a verifying key is not a canonically encoded point, or is a point of
|
||||
/// small order (a weak key).
|
||||
InvalidVerifyingKey,
|
||||
/// A signature does not verify: one half, the other, or both (deliberately not said which).
|
||||
InvalidSignature,
|
||||
/// ML-DSA signing failed (the randomness source or the rejection-sampling bound). Retry with
|
||||
/// fresh randomness.
|
||||
SigningFailed,
|
||||
/// A key binding's validity window ends before it starts (`not_before > not_after`).
|
||||
InvalidValidity,
|
||||
/// A key binding is authentic, but `now` lies outside its validity window.
|
||||
OutsideValidity,
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
@@ -70,11 +106,19 @@ impl fmt::Display for Error {
|
||||
Error::TooShort { input, minimum, actual } => {
|
||||
write!(f, "{input} is too short: at least {minimum} bytes, got {actual}")
|
||||
}
|
||||
Error::TooLong { input, maximum, actual } => {
|
||||
write!(f, "{input} is too long: at most {maximum} bytes, got {actual}")
|
||||
}
|
||||
Error::InvalidPublicKey => f.write_str("public key fails the ML-KEM-768 encapsulation key check"),
|
||||
Error::NonContributory => f.write_str("X25519 value is a low-order point"),
|
||||
Error::UnsupportedVersion(v) => write!(f, "sealed box version {v} is not supported"),
|
||||
Error::DecryptionFailed => f.write_str("sealed box could not be opened"),
|
||||
Error::MessageTooLong => f.write_str("message is too long to seal"),
|
||||
Error::InvalidVerifyingKey => f.write_str("verifying key has a weak or non-canonical Ed25519 point"),
|
||||
Error::InvalidSignature => f.write_str("signature does not verify"),
|
||||
Error::SigningFailed => f.write_str("signing failed; retry with fresh randomness"),
|
||||
Error::InvalidValidity => f.write_str("key binding validity ends before it starts"),
|
||||
Error::OutsideValidity => f.write_str("key binding is not valid at this time"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-5
@@ -6,13 +6,16 @@
|
||||
//! - [`exchange`]: a mutual exchange between two peers (each encapsulates to the other), bound to
|
||||
//! the full transcript and a context, and the WireGuard pre-shared key it yields per epoch.
|
||||
//! - [`seal`]: a one-shot sealed box to a recipient's hybrid public key.
|
||||
//! - [`sign`] (v0.2.0): hybrid signatures ML-DSA-65 + Ed25519, exactly RFC 10073
|
||||
//! `id-MLDSA65-Ed25519-SHA512`, and a helper that binds an X-Wing public key to its owner.
|
||||
//!
|
||||
//! No primitive is implemented here; they come from `ml-kem`, `x25519-dalek`, `sha3`, `shake`,
|
||||
//! `sha2`, `hkdf` and `chacha20poly1305`. No I/O, no clock: randomness and time are parameters.
|
||||
//! Design, sources and risks: `docs/01_arcanum.md` and `docs/THREAT_MODEL.md`.
|
||||
//! No primitive is implemented here; they come from `ml-kem`, `x25519-dalek`, `ml-dsa`,
|
||||
//! `ed25519-dalek`, `sha3`, `shake`, `sha2`, `hkdf` and `chacha20poly1305`. No I/O, no clock: randomness and time are parameters.
|
||||
//! Design, sources and risks: `docs/01_arcanum.md`, `docs/02_signatures.md` and `docs/THREAT_MODEL.md`.
|
||||
//!
|
||||
//! The `hazmat` feature exposes the deterministic (`_derand`, `from_seed`) entry points used by
|
||||
//! the known-answer tests. It is off by default and must never be enabled in a release build.
|
||||
//! The `hazmat` feature exposes the deterministic (`_derand`, `from_seed`) entry points and the
|
||||
//! bare RFC 10073 signature interface (`sign_composite_raw`, `verify_composite_raw`) used by the
|
||||
//! known-answer tests. It is off by default and must never be enabled in a release build.
|
||||
#![no_std]
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(missing_docs)]
|
||||
@@ -23,6 +26,7 @@ mod error;
|
||||
pub mod exchange;
|
||||
mod schedule;
|
||||
pub mod seal;
|
||||
pub mod sign;
|
||||
pub mod xwing;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+429
@@ -0,0 +1,429 @@
|
||||
//! 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 is refused when parsed
|
||||
//! ([`Error::InvalidVerifyingKey`]), and Ed25519 is checked with `verify_strict`.
|
||||
//!
|
||||
//! **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 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.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct AppContext {
|
||||
bytes: [u8; MAX_CONTEXT_LEN],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl AppContext {
|
||||
/// `domi/arcanum/v2/sig/app/` + `label`. Use one fixed label per purpose (Day 3: `plans`).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::TooShort`] for an empty label; [`Error::TooLong`] for one over
|
||||
/// [`MAX_APP_LABEL_LEN`] (231) bytes.
|
||||
pub fn new(label: &[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();
|
||||
bytes[..p].copy_from_slice(APP_CONTEXT_PREFIX);
|
||||
bytes[p..p + label.len()].copy_from_slice(label);
|
||||
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.
|
||||
/// Every 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);
|
||||
}
|
||||
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. Both halves are always checked
|
||||
/// before answering, and the error does not say which failed (RFC 10073 §3.2).
|
||||
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) cannot verify; that it was
|
||||
// malformed is public, the signature itself says so.
|
||||
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();
|
||||
// `&`, not `&&`: both results are computed whatever the first one says.
|
||||
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.
|
||||
pub struct SigningKey {
|
||||
seeds: Zeroizing<[u8; SIGNING_KEY_LEN]>,
|
||||
// Boxed: the expanded ML-DSA-65 key is about 60 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)
|
||||
}
|
||||
Reference in New Issue
Block a user