Skip to main content

capsule_core/crypto/keys/
hybrid_sig.rs

1//! Hybrid classical + ML-DSA-65 signatures — the long-lived identity signature used for
2//! the user IK, device keys (DSK), asset manifests, write-tier keys, sidecars, the device
3//! directory, and backup manifests (SSoT: [Cryptography — Primitives § Signature Scheme]).
4//!
5//! **Both halves must verify** for a signature to be accepted. Neither algorithm being
6//! broken alone compromises authentication, and because both halves cover the same bytes
7//! (including `crypto_suite_id`), the construction is downgrade-resistant even if one
8//! algorithm is later broken.
9//!
10//! The classical half is **algorithm-tagged** over [`ClassicalAlgorithm`]: software keys use
11//! **Ed25519** (the end-to-end default), while the hardware-backed device key pairs the
12//! ML-DSA-65 half with a **hardware ECDSA-P256** classical half — because shipping secure
13//! elements (Secure Enclave, StrongBox, TPM 2.0) expose P-256, not Ed25519 (see
14//! [`crypto::keys::p256`](super::p256)). The tag is carried by the key/signature themselves
15//! (recovered from the classical-half length on the wire), so the Ed25519 serialization is
16//! **byte-for-byte identical** to before the P-256 variant existed.
17//!
18//! Ed25519 keys are deterministic from 32-byte seeds (Ed25519 secret scalar / ML-DSA `ξ`), so
19//! a software signing key serializes as 64 seed bytes and can be wrapped and restored verbatim.
20//!
21//! [Cryptography — Primitives § Signature Scheme]: https://docs/design/cryptography/primitives/#signature-scheme
22
23use ed25519_dalek::{
24    Signature as EdSignature, Signer as _, SigningKey as EdSigningKey, Verifier as _,
25    VerifyingKey as EdVerifyingKey,
26};
27use ml_dsa::{
28    B32, EncodedSignature, EncodedVerifyingKey, Keypair as _, MlDsa65, Signature as MlSignature,
29    Signer as _, SigningKey as MlSigningKey, Verifier as _, VerifyingKey as MlVerifyingKey,
30};
31use p256::ecdsa::{Signature as P256Signature, VerifyingKey as P256VerifyingKey};
32use serde::{Deserialize, Serialize};
33
34use crate::crypto::{CryptoError, rng};
35
36/// Ed25519 secret/seed length and ML-DSA `ξ` seed length (both 32 bytes).
37const SEED_LEN: usize = 32;
38/// Ed25519 public key length.
39const ED_PK_LEN: usize = 32;
40/// Ed25519 signature length.
41const ED_SIG_LEN: usize = 64;
42/// ML-DSA-65 public key length (FIPS-204 level-3).
43const ML_PK_LEN: usize = 1952;
44/// Compressed SEC1 NIST P-256 public key length (`0x02|0x03` prefix + 32-byte x).
45const P256_PK_LEN: usize = 33;
46
47/// The classical half of a hybrid device-key composition. Ed25519 is the software default;
48/// ECDSA-P256 is what shipping secure elements provide (Secure Enclave / StrongBox / TPM 2.0).
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum ClassicalAlgorithm {
51    /// Software (or future hardware) Ed25519 — today's end-to-end software composition.
52    Ed25519,
53    /// Hardware ECDSA-P256 with DER-encoded signatures over `SHA-256(msg)`.
54    EcdsaP256,
55}
56
57/// The classical half of a [`HybridVerifyingKey`], tagged by algorithm.
58#[derive(Clone)]
59enum ClassicalVerifyingKey {
60    Ed25519(EdVerifyingKey),
61    EcdsaP256(P256VerifyingKey),
62}
63
64/// The classical half of a [`HybridSignature`], tagged by algorithm. The Ed25519 half is a
65/// fixed 64-byte signature; the P-256 half is a DER-encoded ECDSA signature.
66#[derive(Clone, Debug, PartialEq, Eq)]
67enum ClassicalSignature {
68    Ed25519([u8; ED_SIG_LEN]),
69    EcdsaP256(Vec<u8>),
70}
71
72/// A hybrid signing keypair (private) — the **software** composition, both halves in memory.
73/// The hardware-backed composition lives in [`HardwareBackedSigner`](super::HardwareBackedSigner)
74/// (Ed25519 hardware half) and [`P256HybridSigningKey`](super::p256::P256HybridSigningKey)
75/// (P-256 hardware half); both drive the same [`HybridSignature`]/[`HybridVerifyingKey`] types.
76#[derive(Clone)]
77pub struct HybridSigningKey {
78    ed: EdSigningKey,
79    ml: MlSigningKey<MlDsa65>,
80}
81
82/// A hybrid public verifying key. Published in the device directory.
83#[derive(Clone)]
84pub struct HybridVerifyingKey {
85    classical: ClassicalVerifyingKey,
86    ml: MlVerifyingKey<MlDsa65>,
87}
88
89/// A hybrid signature: a classical half (Ed25519 or ECDSA-P256) and an ML-DSA-65 half over the
90/// same message.
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub struct HybridSignature {
93    classical: ClassicalSignature,
94    ml: Vec<u8>,
95}
96
97impl HybridSignature {
98    /// Assemble an **Ed25519** hybrid signature from its two halves. Used by the hardware-backed
99    /// signer, which produces the Ed25519 half inside a secure element and the ML-DSA-65 half in
100    /// software. The halves are not validated here — verification happens in
101    /// [`HybridVerifyingKey::verify`].
102    pub(crate) fn from_halves(ed: [u8; ED_SIG_LEN], ml: Vec<u8>) -> Self {
103        Self {
104            classical: ClassicalSignature::Ed25519(ed),
105            ml,
106        }
107    }
108
109    /// Assemble an **ECDSA-P256** hybrid signature from a DER-encoded classical half and the
110    /// software ML-DSA-65 half. Used by [`P256HybridSigningKey`](super::p256::P256HybridSigningKey),
111    /// whose hardware element emits DER ECDSA over `SHA-256(msg)`.
112    pub(crate) fn from_p256_halves(der: Vec<u8>, ml: Vec<u8>) -> Self {
113        Self {
114            classical: ClassicalSignature::EcdsaP256(der),
115            ml,
116        }
117    }
118
119    /// The classical algorithm this signature's classical half is encoded for.
120    pub fn classical_algorithm(&self) -> ClassicalAlgorithm {
121        match self.classical {
122            ClassicalSignature::Ed25519(_) => ClassicalAlgorithm::Ed25519,
123            ClassicalSignature::EcdsaP256(_) => ClassicalAlgorithm::EcdsaP256,
124        }
125    }
126}
127
128fn to_ml_seed(bytes: &[u8; SEED_LEN]) -> B32 {
129    B32::try_from(&bytes[..]).expect("32-byte ML-DSA seed")
130}
131
132/// Verify a DER-encoded ECDSA-P256 signature over `msg`. RustCrypto's `p256` verifier hashes
133/// `msg` with SHA-256 internally (matching what a secure element signs) and accepts both
134/// low-S and high-S DER encodings, so a signature is never rejected for S-normalization alone.
135fn p256_verify(vk: &P256VerifyingKey, msg: &[u8], der: &[u8]) -> bool {
136    match P256Signature::from_der(der) {
137        Ok(sig) => vk.verify(msg, &sig).is_ok(),
138        Err(_) => false,
139    }
140}
141
142impl HybridSigningKey {
143    /// Generate a fresh hybrid keypair from the OS CSPRNG.
144    pub fn generate() -> Self {
145        let seeds = rng::random_array::<{ 2 * SEED_LEN }>();
146        let mut ed_seed = [0u8; SEED_LEN];
147        let mut ml = [0u8; SEED_LEN];
148        ed_seed.copy_from_slice(&seeds[..SEED_LEN]);
149        ml.copy_from_slice(&seeds[SEED_LEN..]);
150        Self::from_seed_bytes(&ed_seed, &ml)
151    }
152
153    /// Reconstruct a keypair deterministically from its two 32-byte seeds.
154    pub fn from_seed_bytes(ed_seed: &[u8; SEED_LEN], ml_seed: &[u8; SEED_LEN]) -> Self {
155        Self {
156            ed: EdSigningKey::from_bytes(ed_seed),
157            ml: MlSigningKey::<MlDsa65>::from_seed(&to_ml_seed(ml_seed)),
158        }
159    }
160
161    /// Export the two 32-byte seeds (Ed25519 secret ‖ ML-DSA ξ) for sealed storage.
162    pub fn to_seed_bytes(&self) -> [u8; 2 * SEED_LEN] {
163        let mut out = [0u8; 2 * SEED_LEN];
164        out[..SEED_LEN].copy_from_slice(&self.ed.to_bytes());
165        out[SEED_LEN..].copy_from_slice(self.ml.to_seed().as_slice());
166        out
167    }
168
169    /// Reconstruct from a 64-byte concatenation of the two seeds.
170    pub fn from_seed64(bytes: &[u8; 2 * SEED_LEN]) -> Self {
171        let mut ed_seed = [0u8; SEED_LEN];
172        let mut ml = [0u8; SEED_LEN];
173        ed_seed.copy_from_slice(&bytes[..SEED_LEN]);
174        ml.copy_from_slice(&bytes[SEED_LEN..]);
175        Self::from_seed_bytes(&ed_seed, &ml)
176    }
177
178    /// The public verifying key.
179    pub fn verifying_key(&self) -> HybridVerifyingKey {
180        HybridVerifyingKey {
181            classical: ClassicalVerifyingKey::Ed25519(self.ed.verifying_key()),
182            ml: self.ml.verifying_key(),
183        }
184    }
185
186    /// Sign `msg`, producing both halves. ML-DSA uses the deterministic variant.
187    pub fn sign(&self, msg: &[u8]) -> HybridSignature {
188        let ed = self.ed.sign(msg).to_bytes();
189        let ml = self.ml.sign(msg).encode().to_vec();
190        HybridSignature {
191            classical: ClassicalSignature::Ed25519(ed),
192            ml,
193        }
194    }
195}
196
197impl HybridVerifyingKey {
198    /// Assemble an **ECDSA-P256** hybrid verifying key from a hardware P-256 public key and the
199    /// software ML-DSA-65 public half. Used by
200    /// [`P256HybridSigningKey`](super::p256::P256HybridSigningKey) at enrollment.
201    pub(crate) fn from_p256_parts(vk: P256VerifyingKey, ml: MlVerifyingKey<MlDsa65>) -> Self {
202        Self {
203            classical: ClassicalVerifyingKey::EcdsaP256(vk),
204            ml,
205        }
206    }
207
208    /// The classical algorithm this key's classical half is encoded for.
209    pub fn classical_algorithm(&self) -> ClassicalAlgorithm {
210        match self.classical {
211            ClassicalVerifyingKey::Ed25519(_) => ClassicalAlgorithm::Ed25519,
212            ClassicalVerifyingKey::EcdsaP256(_) => ClassicalAlgorithm::EcdsaP256,
213        }
214    }
215
216    /// Verify `sig` over `msg`. Returns `true` only if **both** halves verify. The classical
217    /// half dispatches on this key's declared algorithm: a signature whose classical half is a
218    /// *different* algorithm than the key (an Ed25519 sig against a P-256 key, or vice versa)
219    /// never verifies.
220    pub fn verify(&self, msg: &[u8], sig: &HybridSignature) -> bool {
221        let classical_ok = match (&self.classical, &sig.classical) {
222            (ClassicalVerifyingKey::Ed25519(vk), ClassicalSignature::Ed25519(s)) => {
223                vk.verify(msg, &EdSignature::from_bytes(s)).is_ok()
224            }
225            (ClassicalVerifyingKey::EcdsaP256(vk), ClassicalSignature::EcdsaP256(der)) => {
226                p256_verify(vk, msg, der)
227            }
228            // Algorithm mismatch between key and signature — never accept.
229            _ => false,
230        };
231        // Short-circuit only matters for cost; correctness requires both.
232        let ml_ok = match EncodedSignature::<MlDsa65>::try_from(sig.ml.as_slice()) {
233            Ok(enc) => match MlSignature::<MlDsa65>::decode(&enc) {
234                Some(s) => self.ml.verify(msg, &s).is_ok(),
235                None => false,
236            },
237            Err(_) => false,
238        };
239        classical_ok && ml_ok
240    }
241
242    /// The classical half's raw bytes: Ed25519 public key (32) or compressed SEC1 P-256 public
243    /// key (33).
244    fn classical_bytes(&self) -> Vec<u8> {
245        match &self.classical {
246            ClassicalVerifyingKey::Ed25519(vk) => vk.to_bytes().to_vec(),
247            ClassicalVerifyingKey::EcdsaP256(vk) => vk.to_encoded_point(true).as_bytes().to_vec(),
248        }
249    }
250
251    /// Raw bytes: the classical public key (Ed25519 = 32, P-256 = 33) followed by the ML-DSA-65
252    /// public key (1952). The classical-half length is what distinguishes the two algorithms on
253    /// decode, so an Ed25519 key round-trips to the exact same bytes it always has.
254    pub fn to_bytes(&self) -> Vec<u8> {
255        let classical = self.classical_bytes();
256        let mut out = Vec::with_capacity(classical.len() + ML_PK_LEN);
257        out.extend_from_slice(&classical);
258        out.extend_from_slice(self.ml.encode().as_slice());
259        out
260    }
261
262    /// Reconstruct from the `classical ‖ ml` byte layout produced by [`to_bytes`](Self::to_bytes).
263    /// The ML-DSA-65 half is the fixed-length 1952-byte suffix; the classical prefix is 32 bytes
264    /// (Ed25519) or 33 bytes (compressed SEC1 P-256), which selects the algorithm.
265    pub fn from_bytes(bytes: &[u8]) -> Result<Self, CryptoError> {
266        if bytes.len() <= ML_PK_LEN {
267            return Err(CryptoError::Malformed("hybrid verifying key too short"));
268        }
269        let (classical_b, ml_b) = bytes.split_at(bytes.len() - ML_PK_LEN);
270        let classical = match classical_b.len() {
271            ED_PK_LEN => {
272                let arr: [u8; ED_PK_LEN] = classical_b
273                    .try_into()
274                    .map_err(|_| CryptoError::Malformed("bad Ed25519 public key length"))?;
275                let ed = EdVerifyingKey::from_bytes(&arr)
276                    .map_err(|_| CryptoError::Key("invalid Ed25519 public key"))?;
277                ClassicalVerifyingKey::Ed25519(ed)
278            }
279            P256_PK_LEN => {
280                let vk = P256VerifyingKey::from_sec1_bytes(classical_b)
281                    .map_err(|_| CryptoError::Key("invalid P-256 public key"))?;
282                ClassicalVerifyingKey::EcdsaP256(vk)
283            }
284            _ => return Err(CryptoError::Malformed("bad classical public key length")),
285        };
286        let enc = EncodedVerifyingKey::<MlDsa65>::try_from(ml_b)
287            .map_err(|_| CryptoError::Malformed("bad ML-DSA public key length"))?;
288        let ml = MlVerifyingKey::<MlDsa65>::decode(&enc);
289        Ok(Self { classical, ml })
290    }
291}
292
293impl PartialEq for HybridVerifyingKey {
294    fn eq(&self, other: &Self) -> bool {
295        self.to_bytes() == other.to_bytes()
296    }
297}
298impl Eq for HybridVerifyingKey {}
299
300impl std::fmt::Debug for HybridVerifyingKey {
301    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302        match &self.classical {
303            ClassicalVerifyingKey::Ed25519(vk) => {
304                write!(
305                    f,
306                    "HybridVerifyingKey(ed25519={})",
307                    hex::encode(vk.to_bytes())
308                )
309            }
310            ClassicalVerifyingKey::EcdsaP256(vk) => write!(
311                f,
312                "HybridVerifyingKey(p256={})",
313                hex::encode(vk.to_encoded_point(true).as_bytes())
314            ),
315        }
316    }
317}
318
319// ── serde: signatures and verifying keys serialize as CBOR byte strings ─────────
320
321#[derive(Serialize, Deserialize)]
322struct SigWire {
323    #[serde(with = "serde_bytes")]
324    ed: Vec<u8>,
325    #[serde(with = "serde_bytes")]
326    ml: Vec<u8>,
327}
328
329impl Serialize for HybridSignature {
330    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
331        let classical = match &self.classical {
332            ClassicalSignature::Ed25519(sig) => sig.to_vec(),
333            ClassicalSignature::EcdsaP256(der) => der.clone(),
334        };
335        SigWire {
336            ed: classical,
337            ml: self.ml.clone(),
338        }
339        .serialize(s)
340    }
341}
342
343impl<'de> Deserialize<'de> for HybridSignature {
344    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
345        let w = SigWire::deserialize(d)?;
346        // The classical half is either a 64-byte Ed25519 signature or a variable-length DER
347        // ECDSA-P256 signature (never 64 bytes for a real P-256 signature). Verification is
348        // key-driven, so a misclassified half can only fail verification, never falsely accept.
349        let classical = if w.ed.len() == ED_SIG_LEN {
350            let ed: [u8; ED_SIG_LEN] =
351                w.ed.as_slice()
352                    .try_into()
353                    .expect("length checked to equal ED_SIG_LEN");
354            ClassicalSignature::Ed25519(ed)
355        } else {
356            ClassicalSignature::EcdsaP256(w.ed)
357        };
358        Ok(HybridSignature {
359            classical,
360            ml: w.ml,
361        })
362    }
363}
364
365impl Serialize for HybridVerifyingKey {
366    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
367        SigWire {
368            ed: self.classical_bytes(),
369            ml: self.ml.encode().to_vec(),
370        }
371        .serialize(s)
372    }
373}
374
375impl<'de> Deserialize<'de> for HybridVerifyingKey {
376    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
377        use serde::de::Error;
378        let w = SigWire::deserialize(d)?;
379        let mut bytes = w.ed;
380        bytes.extend_from_slice(&w.ml);
381        HybridVerifyingKey::from_bytes(&bytes).map_err(D::Error::custom)
382    }
383}
384
385#[cfg(test)]
386mod tests;