Skip to main content

hide_sign/
lib.rs

1//! Hybrid Ed25519 + ML-DSA-65 signatures for HIDE.
2//!
3//! A signature is the concatenation of both halves and verifies **only if both
4//! halves verify**. Accepting either alone would silently reduce the scheme to
5//! the weaker of the two, which is the whole reason for pairing them: Ed25519
6//! falls to a quantum adversary, and ML-DSA is young enough that a classical
7//! break cannot be ruled out.
8//!
9//! Both halves are derived from one 32-byte seed through domain-separated
10//! HKDF, so an identity is a single thing to back up. The seed is also
11//! separate from the encryption key: compromise of one must not imply the
12//! other.
13//!
14//! No primitive is implemented here. This crate composes reviewed crates and
15//! owns only the combination.
16
17use ed25519_dalek::{
18    Signer as _, SigningKey as EdSigningKey, Verifier as _, VerifyingKey as EdVerifyingKey,
19};
20use hkdf::Hkdf;
21use ml_dsa::{
22    KeyInit as _, MlDsa65, Signature as MlSignature, SigningKey as MlSigningKey,
23    VerifyingKey as MlVerifyingKey, signature::Keypair as _,
24};
25use sha2::Sha256;
26use thiserror::Error;
27use zeroize::Zeroizing;
28
29mod challenge;
30pub use challenge::{Challenge, ChallengeError, NONCE_LENGTH, SpentNonces};
31
32/// The seed an identity is stored and backed up as.
33pub const SEED_LENGTH: usize = 32;
34
35const ED25519_PUBLIC_LEN: usize = 32;
36const ED25519_SIGNATURE_LEN: usize = 64;
37const ML_DSA_PUBLIC_LEN: usize = 1952;
38const ML_DSA_SIGNATURE_LEN: usize = 3309;
39
40/// A hybrid verifying key: the Ed25519 half followed by the ML-DSA-65 half.
41pub const VERIFYING_KEY_LENGTH: usize = ED25519_PUBLIC_LEN + ML_DSA_PUBLIC_LEN;
42/// A hybrid signature: the Ed25519 half followed by the ML-DSA-65 half.
43pub const SIGNATURE_LENGTH: usize = ED25519_SIGNATURE_LEN + ML_DSA_SIGNATURE_LEN;
44
45/// Separates the two halves so neither key can stand in for the other, and
46/// separates a signing seed from the encryption seed of the same identity.
47const ED25519_INFO: &[u8] = b"HIDE/0.5 identity ed25519";
48const ML_DSA_INFO: &[u8] = b"HIDE/0.5 identity ml-dsa-65";
49
50/// Contexts starting with these bytes belong to the specification (§8.5):
51/// identity-log entries, MLS bindings, container signatures and the rest.
52/// A general-purpose signing API that let a caller choose one would sign
53/// protocol objects on that caller's behalf.
54pub const RESERVED_CONTEXT_PREFIX: &[u8] = b"HIDE/";
55
56/// Whether `context` is reserved for the specification and must be refused
57/// by any API through which a third party chooses what gets signed.
58pub fn is_reserved_context(context: &[u8]) -> bool {
59    context.starts_with(RESERVED_CONTEXT_PREFIX)
60}
61
62/// An error that carries no key material and no signed plaintext.
63#[derive(Debug, Error, PartialEq, Eq)]
64pub enum SignError {
65    /// Deliberately does not say which half failed: that distinction is not
66    /// useful to a caller and would tell an attacker which half to attack.
67    #[error("signature verification failed")]
68    Verification,
69    #[error("invalid {name} length: expected {expected}, got {actual}")]
70    InvalidLength {
71        name: &'static str,
72        expected: usize,
73        actual: usize,
74    },
75    #[error("verifying key is malformed")]
76    MalformedKey,
77    #[error("challenge is malformed")]
78    MalformedChallenge,
79    #[error("contexts beginning with \"HIDE/\" are reserved for the protocol")]
80    ReservedContext,
81    #[error("operating-system randomness failed")]
82    Random,
83}
84
85fn require_length(name: &'static str, expected: usize, actual: usize) -> Result<(), SignError> {
86    if expected == actual {
87        Ok(())
88    } else {
89        Err(SignError::InvalidLength {
90            name,
91            expected,
92            actual,
93        })
94    }
95}
96
97fn derive(seed: &[u8; SEED_LENGTH], info: &[u8]) -> Zeroizing<[u8; 32]> {
98    let mut output = Zeroizing::new([0_u8; 32]);
99    // HKDF-Expand cannot fail for a 32-byte output, and a panic here would be a
100    // logic error rather than anything an input can cause.
101    Hkdf::<Sha256>::from_prk(seed)
102        .expect("a 32-byte PRK is long enough for HKDF-SHA256")
103        .expand(info, output.as_mut())
104        .expect("32 bytes is within HKDF's output limit");
105    output
106}
107
108/// A signing identity, intentionally not `Debug`, `Clone` or `Serialize`.
109///
110/// ```compile_fail,E0277
111/// fn requires_debug<T: core::fmt::Debug>() {}
112/// requires_debug::<hide_sign::SigningIdentity>();
113/// ```
114///
115/// ```compile_fail,E0277
116/// fn requires_clone<T: Clone>() {}
117/// requires_clone::<hide_sign::SigningIdentity>();
118/// ```
119pub struct SigningIdentity {
120    seed: Zeroizing<[u8; SEED_LENGTH]>,
121    ed25519: EdSigningKey,
122    ml_dsa: MlSigningKey<MlDsa65>,
123}
124
125impl SigningIdentity {
126    pub fn generate() -> Result<Self, SignError> {
127        let mut seed = Zeroizing::new([0_u8; SEED_LENGTH]);
128        getrandom::fill(seed.as_mut()).map_err(|_| SignError::Random)?;
129        Ok(Self::from_seed(&seed))
130    }
131
132    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SignError> {
133        require_length("signing seed", SEED_LENGTH, bytes.len())?;
134        let mut seed = Zeroizing::new([0_u8; SEED_LENGTH]);
135        seed.copy_from_slice(bytes);
136        Ok(Self::from_seed(&seed))
137    }
138
139    fn from_seed(seed: &Zeroizing<[u8; SEED_LENGTH]>) -> Self {
140        let ed_seed = derive(seed, ED25519_INFO);
141        let ml_seed = derive(seed, ML_DSA_INFO);
142        Self {
143            seed: seed.clone(),
144            ed25519: EdSigningKey::from_bytes(&ed_seed),
145            ml_dsa: MlSigningKey::<MlDsa65>::new((&*ml_seed).into()),
146        }
147    }
148
149    /// The seed to back up. This is key material: never log or transmit it.
150    pub fn to_bytes(&self) -> Zeroizing<[u8; SEED_LENGTH]> {
151        self.seed.clone()
152    }
153
154    pub fn verifying_key(&self) -> VerifyingIdentity {
155        VerifyingIdentity {
156            ed25519: self.ed25519.verifying_key(),
157            ml_dsa: self.ml_dsa.verifying_key().clone(),
158        }
159    }
160
161    /// Signs with both halves. `context` separates uses of one identity, so a
162    /// signature made for one purpose cannot be replayed as another.
163    ///
164    /// This accepts every context, including the reserved `HIDE/` ones, because
165    /// the protocol crates sign through it. Anything that exposes signing to
166    /// application code must use [`Self::sign_application`] instead.
167    pub fn sign(&self, context: &[u8], message: &[u8]) -> [u8; SIGNATURE_LENGTH] {
168        let payload = bind(context, message);
169        let ed = self.ed25519.sign(&payload);
170        let ml = self.ml_dsa.sign(&payload);
171        let mut signature = [0_u8; SIGNATURE_LENGTH];
172        signature[..ED25519_SIGNATURE_LEN].copy_from_slice(&ed.to_bytes());
173        signature[ED25519_SIGNATURE_LEN..].copy_from_slice(&ml.encode());
174        signature
175    }
176
177    /// Signs under an application-chosen context, refusing the reserved
178    /// `HIDE/` prefix. Without this refusal, whoever can ask a key holder to
179    /// sign "context X, message Y" obtains an identity-log entry, an MLS
180    /// binding or a container signature under that key (§15.2).
181    pub fn sign_application(
182        &self,
183        context: &[u8],
184        message: &[u8],
185    ) -> Result<[u8; SIGNATURE_LENGTH], SignError> {
186        if is_reserved_context(context) {
187            return Err(SignError::ReservedContext);
188        }
189        Ok(self.sign(context, message))
190    }
191
192    /// The Ed25519 half alone, for the SSH agent. OpenSSH has no post-quantum
193    /// signature type for user authentication, so this is what an unmodified
194    /// server can actually verify.
195    pub fn ed25519_seed(&self) -> Zeroizing<[u8; 32]> {
196        Zeroizing::new(self.ed25519.to_bytes())
197    }
198}
199
200/// The public half of an identity: shareable, and safe to print.
201#[derive(Clone)]
202pub struct VerifyingIdentity {
203    ed25519: EdVerifyingKey,
204    ml_dsa: MlVerifyingKey<MlDsa65>,
205}
206
207// Hand-written because ml_dsa::VerifyingKey implements PartialEq but not Eq.
208// Equality over the encoded bytes is reflexive, so Eq is sound here.
209impl PartialEq for VerifyingIdentity {
210    fn eq(&self, other: &Self) -> bool {
211        self.to_bytes() == other.to_bytes()
212    }
213}
214
215impl Eq for VerifyingIdentity {}
216
217impl core::fmt::Debug for VerifyingIdentity {
218    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
219        // Public material, but printing 1984 bytes helps nobody.
220        formatter
221            .debug_struct("VerifyingIdentity")
222            .field("ed25519", &hex_prefix(&self.ed25519_bytes()))
223            .finish_non_exhaustive()
224    }
225}
226
227fn hex_prefix(bytes: &[u8]) -> String {
228    bytes[..8]
229        .iter()
230        .map(|byte| format!("{byte:02x}"))
231        .collect()
232}
233
234impl VerifyingIdentity {
235    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SignError> {
236        require_length("verifying key", VERIFYING_KEY_LENGTH, bytes.len())?;
237        let (ed, ml) = bytes.split_at(ED25519_PUBLIC_LEN);
238        let ed: [u8; ED25519_PUBLIC_LEN] = ed.try_into().expect("split at the exact length");
239        let ml: &[u8; ML_DSA_PUBLIC_LEN] = ml.try_into().expect("split at the exact length");
240        Ok(Self {
241            ed25519: EdVerifyingKey::from_bytes(&ed).map_err(|_| SignError::MalformedKey)?,
242            ml_dsa: MlVerifyingKey::<MlDsa65>::new(ml.into()),
243        })
244    }
245
246    pub fn to_bytes(&self) -> [u8; VERIFYING_KEY_LENGTH] {
247        let mut bytes = [0_u8; VERIFYING_KEY_LENGTH];
248        bytes[..ED25519_PUBLIC_LEN].copy_from_slice(self.ed25519.as_bytes());
249        bytes[ED25519_PUBLIC_LEN..].copy_from_slice(&self.ml_dsa.encode());
250        bytes
251    }
252
253    /// The Ed25519 half, in the 32-byte form OpenSSH uses.
254    pub fn ed25519_bytes(&self) -> [u8; ED25519_PUBLIC_LEN] {
255        self.ed25519.to_bytes()
256    }
257
258    /// Verifies both halves. Neither alone is accepted.
259    pub fn verify(
260        &self,
261        context: &[u8],
262        message: &[u8],
263        signature: &[u8],
264    ) -> Result<(), SignError> {
265        require_length("signature", SIGNATURE_LENGTH, signature.len())?;
266        let payload = bind(context, message);
267        let (ed, ml) = signature.split_at(ED25519_SIGNATURE_LEN);
268
269        let ed: [u8; ED25519_SIGNATURE_LEN] = ed.try_into().expect("split at the exact length");
270        // verify_strict rejects keys and signatures of small order, which
271        // plain verify accepts and which break the usual uniqueness guarantee.
272        let classical = self
273            .ed25519
274            .verify_strict(&payload, &ed_signature(&ed))
275            .is_ok();
276
277        let ml: [u8; ML_DSA_SIGNATURE_LEN] = ml.try_into().expect("split at the exact length");
278        let quantum = match MlSignature::<MlDsa65>::decode(&ml.into()) {
279            Some(parsed) => self.ml_dsa.verify(&payload, &parsed).is_ok(),
280            None => false,
281        };
282
283        // Both are evaluated before the decision so the time taken does not
284        // reveal which half failed.
285        if classical && quantum {
286            Ok(())
287        } else {
288            Err(SignError::Verification)
289        }
290    }
291}
292
293fn ed_signature(bytes: &[u8; ED25519_SIGNATURE_LEN]) -> ed25519_dalek::Signature {
294    ed25519_dalek::Signature::from_bytes(bytes)
295}
296
297/// Binds the context to the message length-prefixed, so that no two distinct
298/// (context, message) pairs can produce the same signed bytes. Concatenating
299/// them directly would let a crafted context absorb part of the message.
300fn bind(context: &[u8], message: &[u8]) -> Vec<u8> {
301    let mut payload = Vec::with_capacity(8 + context.len() + message.len());
302    payload.extend_from_slice(&(context.len() as u64).to_be_bytes());
303    payload.extend_from_slice(context);
304    payload.extend_from_slice(message);
305    payload
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    const CONTEXT: &[u8] = b"HIDE/0.5 test";
313
314    fn identity() -> SigningIdentity {
315        SigningIdentity::from_bytes(&[0x42; SEED_LENGTH]).expect("a 32-byte seed is valid")
316    }
317
318    #[test]
319    fn a_signature_round_trips_and_has_the_documented_size() {
320        let signing = identity();
321        let verifying = signing.verifying_key();
322        let signature = signing.sign(CONTEXT, b"attack at dawn");
323
324        assert_eq!(signature.len(), SIGNATURE_LENGTH);
325        assert_eq!(verifying.to_bytes().len(), VERIFYING_KEY_LENGTH);
326        verifying
327            .verify(CONTEXT, b"attack at dawn", &signature)
328            .expect("a fresh signature verifies");
329    }
330
331    #[test]
332    fn the_seed_reproduces_the_same_identity() {
333        let first = identity();
334        let second = SigningIdentity::from_bytes(&first.to_bytes()[..]).expect("round trip");
335        assert_eq!(
336            first.verifying_key().to_bytes(),
337            second.verifying_key().to_bytes()
338        );
339
340        let signature = first.sign(CONTEXT, b"same seed");
341        second
342            .verifying_key()
343            .verify(CONTEXT, b"same seed", &signature)
344            .expect("the derived key is identical");
345    }
346
347    #[test]
348    fn a_verifying_key_survives_encoding() {
349        let verifying = identity().verifying_key();
350        let decoded = VerifyingIdentity::from_bytes(&verifying.to_bytes()).expect("round trip");
351        assert!(decoded == verifying);
352    }
353
354    /// The central invariant: a signature valid in one half only must fail.
355    #[test]
356    fn neither_half_alone_is_accepted() {
357        let alice = identity();
358        let bob = SigningIdentity::from_bytes(&[0x99; SEED_LENGTH]).expect("valid seed");
359        let message = b"transfer 100";
360
361        let from_alice = alice.sign(CONTEXT, message);
362        let from_bob = bob.sign(CONTEXT, message);
363
364        // Alice's Ed25519 half with Bob's ML-DSA half, and the reverse.
365        let mut classical_only = from_alice;
366        classical_only[ED25519_SIGNATURE_LEN..].copy_from_slice(&from_bob[ED25519_SIGNATURE_LEN..]);
367        assert_eq!(
368            alice
369                .verifying_key()
370                .verify(CONTEXT, message, &classical_only),
371            Err(SignError::Verification),
372            "a valid Ed25519 half was accepted despite a foreign ML-DSA half"
373        );
374
375        let mut quantum_only = from_alice;
376        quantum_only[..ED25519_SIGNATURE_LEN].copy_from_slice(&from_bob[..ED25519_SIGNATURE_LEN]);
377        assert_eq!(
378            alice
379                .verifying_key()
380                .verify(CONTEXT, message, &quantum_only),
381            Err(SignError::Verification),
382            "a valid ML-DSA half was accepted despite a foreign Ed25519 half"
383        );
384    }
385
386    #[test]
387    fn a_changed_message_context_or_signer_is_rejected() {
388        let signing = identity();
389        let verifying = signing.verifying_key();
390        let signature = signing.sign(CONTEXT, b"pay Ana");
391
392        assert_eq!(
393            verifying.verify(CONTEXT, b"pay Bob", &signature),
394            Err(SignError::Verification)
395        );
396        assert_eq!(
397            verifying.verify(b"HIDE/0.5 other", b"pay Ana", &signature),
398            Err(SignError::Verification),
399            "a signature was replayed under a different context"
400        );
401
402        let other = SigningIdentity::from_bytes(&[7; SEED_LENGTH]).expect("valid seed");
403        assert_eq!(
404            other
405                .verifying_key()
406                .verify(CONTEXT, b"pay Ana", &signature),
407            Err(SignError::Verification)
408        );
409    }
410
411    #[test]
412    fn every_single_bit_flip_in_a_signature_is_rejected() {
413        let signing = identity();
414        let verifying = signing.verifying_key();
415        let message = b"integrity";
416        let signature = signing.sign(CONTEXT, message);
417
418        // Both halves, at their boundaries and in the middle of each.
419        for offset in [
420            0,
421            1,
422            ED25519_SIGNATURE_LEN - 1,
423            ED25519_SIGNATURE_LEN,
424            ED25519_SIGNATURE_LEN + 1,
425            SIGNATURE_LENGTH / 2,
426            SIGNATURE_LENGTH - 1,
427        ] {
428            let mut damaged = signature;
429            damaged[offset] ^= 1;
430            assert_eq!(
431                verifying.verify(CONTEXT, message, &damaged),
432                Err(SignError::Verification),
433                "a flipped bit at offset {offset} was accepted"
434            );
435        }
436    }
437
438    #[test]
439    fn a_truncated_or_extended_signature_is_refused_before_verifying() {
440        let signing = identity();
441        let verifying = signing.verifying_key();
442        let signature = signing.sign(CONTEXT, b"bounds");
443
444        for length in [0, 1, ED25519_SIGNATURE_LEN, SIGNATURE_LENGTH - 1] {
445            assert!(matches!(
446                verifying.verify(CONTEXT, b"bounds", &signature[..length]),
447                Err(SignError::InvalidLength { .. })
448            ));
449        }
450        let mut extended = signature.to_vec();
451        extended.push(0);
452        assert!(matches!(
453            verifying.verify(CONTEXT, b"bounds", &extended),
454            Err(SignError::InvalidLength { .. })
455        ));
456    }
457
458    #[test]
459    fn a_malformed_key_or_seed_is_refused_rather_than_panicking() {
460        for length in [0, 31, 33, 64] {
461            assert!(SigningIdentity::from_bytes(&vec![0; length]).is_err());
462        }
463        for length in [0, VERIFYING_KEY_LENGTH - 1, VERIFYING_KEY_LENGTH + 1] {
464            assert!(VerifyingIdentity::from_bytes(&vec![0; length]).is_err());
465        }
466        // An all-zero Ed25519 half parses: dalek defers point decompression,
467        // so a degenerate key is caught at verification rather than here.
468        // What matters is that it can never validate anything, which is the
469        // reason this code uses verify_strict.
470        let degenerate =
471            VerifyingIdentity::from_bytes(&[0; VERIFYING_KEY_LENGTH]).expect("parses lazily");
472        let signature = identity().sign(CONTEXT, b"anything");
473        assert_eq!(
474            degenerate.verify(CONTEXT, b"anything", &signature),
475            Err(SignError::Verification),
476            "a small-order key validated a signature"
477        );
478        assert_eq!(
479            degenerate.verify(CONTEXT, b"anything", &[0; SIGNATURE_LENGTH]),
480            Err(SignError::Verification)
481        );
482    }
483
484    #[test]
485    fn the_context_cannot_absorb_part_of_the_message() {
486        let signing = identity();
487        let verifying = signing.verifying_key();
488        // Without a length prefix, ("ab", "c") and ("a", "bc") would sign the
489        // same bytes and a signature would transfer between them.
490        let signature = signing.sign(b"ab", b"c");
491        assert_eq!(
492            verifying.verify(b"a", b"bc", &signature),
493            Err(SignError::Verification)
494        );
495    }
496
497    /// Case 1 of the ed25519-speccheck suite: a small-order public key with a
498    /// matching small-order signature. Plain `verify` accepts it; `verify_strict`
499    /// must not. Without this, swapping verify_strict for verify is undetectable.
500    #[test]
501    fn a_small_order_ed25519_key_is_rejected() {
502        let pubkey = hex("c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa");
503        let sig = hex(
504            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a\
505             0000000000000000000000000000000000000000000000000000000000000000",
506        );
507        let message = hex("8c93255d71dcab10e8f379c26200f3c7bd5f09d9bc3068d3ef4edeb4853022b6");
508
509        let key = EdVerifyingKey::from_bytes(&pubkey.try_into().expect("32 bytes"))
510            .expect("the point decodes");
511        let signature = ed25519_dalek::Signature::from_bytes(&sig.try_into().expect("64 bytes"));
512
513        // The premise: this is exactly the case the two APIs disagree on.
514        assert!(
515            key.verify(&message, &signature).is_ok(),
516            "vector no longer exercises the small-order path"
517        );
518        assert!(
519            key.verify_strict(&message, &signature).is_err(),
520            "verify_strict accepted a small-order key"
521        );
522    }
523
524    /// The vector above cannot be routed through `VerifyingIdentity::verify`,
525    /// because `bind` length-prefixes every payload and the vector's message is
526    /// fixed. Guard the call site directly instead, so downgrading it to plain
527    /// `verify` cannot pass unnoticed.
528    #[test]
529    fn the_classical_half_uses_verify_strict() {
530        let source = include_str!("lib.rs");
531        let after = source
532            .split("fn verify(")
533            .nth(1)
534            .expect("verify is defined here");
535        // Stop at the end of the function, otherwise this test's own source
536        // (which mentions verify_strict) would satisfy the assertion.
537        let body = after.split("\n    }\n").next().expect("the body ends");
538        assert!(
539            body.contains(".verify_strict("),
540            "VerifyingIdentity::verify must use verify_strict"
541        );
542    }
543
544    fn hex(s: &str) -> Vec<u8> {
545        let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
546        s.as_bytes()
547            .chunks(2)
548            .map(|pair| {
549                u8::from_str_radix(std::str::from_utf8(pair).expect("ascii"), 16)
550                    .expect("hex digits")
551            })
552            .collect()
553    }
554
555    /// A wiring mistake that fed the same seed to both halves would leave every
556    /// other test green, so pin the derived material to frozen bytes.
557    #[test]
558    fn the_derived_halves_match_frozen_bytes() {
559        let bytes = identity().verifying_key().to_bytes();
560        assert_eq!(
561            &bytes[..ED25519_PUBLIC_LEN],
562            &hex("d272bef04a4165fcd3fe54571231cc1f7ddb9a0750b5dfb014743007ca39afd6")[..],
563            "derived Ed25519 half changed: this is a protocol change"
564        );
565        // Pin the post-quantum half too. Without this, feeding both halves the
566        // same seed leaves every other test green.
567        assert_eq!(
568            &bytes[ED25519_PUBLIC_LEN..ED25519_PUBLIC_LEN + 32],
569            &hex("f8119f4e0a419adc36f51d2babba246d7e03260d0b904ca695859c9af81d462f")[..],
570            "derived ML-DSA half changed: this is a protocol change"
571        );
572    }
573
574    /// RFC 8032 section 7.1, TEST 3. Proves ed25519-dalek is wired to the
575    /// standard, not merely self-consistent.
576    #[test]
577    fn the_classical_half_matches_rfc_8032() {
578        let secret = hex("c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7");
579        let message = hex("af82");
580        let expected = hex(
581            "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac\
582             18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a",
583        );
584
585        let signing = EdSigningKey::from_bytes(&secret.try_into().expect("32-byte seed"));
586        assert_eq!(
587            signing.sign(&message).to_bytes()[..],
588            expected[..],
589            "Ed25519 does not match RFC 8032"
590        );
591    }
592
593    /// NIST ACVP ML-DSA keyGen, ML-DSA-65, tcId 26. Proves the ml-dsa crate
594    /// implements FIPS-204 with the parameter set this code selects; a silent
595    /// swap to ML-DSA-44 or -87 would change these bytes.
596    #[test]
597    fn the_quantum_half_matches_fips_204() {
598        let seed = hex("A991FD42B071D49C48AE3E75C647459E0DAAD1E1BA356A04801912D3294BCFF8");
599        let seed: [u8; 32] = seed.try_into().expect("32 bytes");
600        let signing = MlSigningKey::<MlDsa65>::new((&seed).into());
601        let public = signing.verifying_key().encode();
602
603        assert_eq!(
604            public.len(),
605            ML_DSA_PUBLIC_LEN,
606            "wrong ML-DSA parameter set"
607        );
608        assert_eq!(
609            &public[..32],
610            &hex("36DB0B5DCE98BD190CB139E80B71B49C7D7040B71C5A1F3412C46BDE939192B1")[..],
611            "ML-DSA-65 does not match the NIST vector"
612        );
613    }
614
615    #[test]
616    fn a_context_change_alone_invalidates() {
617        let signing = identity();
618        let verifying = signing.verifying_key();
619        let signature = signing.sign(b"one", b"m");
620        assert_eq!(
621            verifying.verify(b"two", b"m", &signature),
622            Err(SignError::Verification)
623        );
624    }
625
626    /// §15.2: a general-purpose API must not sign protocol objects.
627    #[test]
628    fn application_signing_refuses_every_reserved_context() {
629        let signing = identity();
630        for context in [
631            &b"HIDE/"[..],
632            b"HIDE/0.6 identity entry",
633            b"HIDE/0.7 mls binding",
634            b"HIDE/1.0 container",
635            b"HIDE/0.5 detached",
636            b"HIDE/0.5 challenge",
637            b"HIDE/1.0 recovery binding",
638            b"HIDE/1.0 epoch binding",
639            b"HIDE/1.0 checkpoint",
640        ] {
641            assert!(
642                matches!(
643                    signing.sign_application(context, b"m"),
644                    Err(SignError::ReservedContext)
645                ),
646                "signed under reserved context {context:?}"
647            );
648        }
649    }
650
651    #[test]
652    fn application_signing_accepts_other_contexts_and_matches_sign() {
653        let signing = identity();
654        for context in [
655            &b""[..],
656            b"myapp/v1 release",
657            b"hide/lowercase",
658            b"HIDE",
659            b" HIDE/",
660        ] {
661            let signature = signing
662                .sign_application(context, b"m")
663                .expect("not reserved");
664            assert_eq!(signature, signing.sign(context, b"m"));
665        }
666    }
667
668    #[test]
669    fn the_two_halves_are_derived_independently() {
670        let signing = identity();
671        let bytes = signing.verifying_key().to_bytes();
672        // A wiring mistake that fed the same seed to both would be invisible in
673        // a round-trip test, so compare the derived material directly.
674        assert_ne!(
675            &bytes[..ED25519_PUBLIC_LEN],
676            &signing.to_bytes()[..],
677            "the Ed25519 key is the raw seed rather than a derived one"
678        );
679        assert_ne!(
680            derive(&signing.to_bytes(), ED25519_INFO).as_ref(),
681            derive(&signing.to_bytes(), ML_DSA_INFO).as_ref()
682        );
683    }
684}