Skip to main content

capsule_core/crypto/keys/
p256.rs

1//! P-256 hybrid-DSK variant — the hardware-backed device signing key (design:
2//! <https://docs/design/cryptography/keys/#device-keys>).
3//!
4//! Shipping secure elements (Secure Enclave, StrongBox, TPM 2.0) expose **ECDSA-P256**,
5//! not Ed25519, so the hardware-backed device-key composition pairs a *hardware P-256
6//! classical half* with the software-sealed ML-DSA-65 half. [`P256HybridSigningKey`] composes
7//! the two into the same algorithm-tagged [`HybridSignature`]/[`HybridVerifyingKey`] the
8//! Ed25519 path produces, so every downstream signing site — asset manifests, the device
9//! directory, `verify_asset` — dispatches on the key's declared [`ClassicalAlgorithm`] without
10//! caring which curve produced the classical half.
11//!
12//! The hardware P-256 half is reached through the [`HardwareSigner`] seam: [`enroll`] reads the
13//! element's P-256 public key, and [`sign`] asks the element for a **DER-encoded ECDSA**
14//! signature over `SHA-256(msg)` — exactly what Secure Enclave and StrongBox emit. Only the
15//! ML-DSA-65 half is in software (no shipping element holds PQ keys). The three native backends
16//! (SE/StrongBox/TPM) plug into this same composition via the `HardwareSigner` foreign trait;
17//! the software `p256` crate is the reference/mock element they replace.
18//!
19//! [`ClassicalAlgorithm`]: super::hybrid_sig::ClassicalAlgorithm
20//! [`enroll`]: P256HybridSigningKey::enroll
21//! [`sign`]: P256HybridSigningKey#impl-Signer-for-P256HybridSigningKey
22
23use std::sync::Arc;
24
25use ml_dsa::{B32, Keypair as _, MlDsa65, Signer as _, SigningKey as MlSigningKey};
26use p256::ecdsa::VerifyingKey as P256VerifyingKey;
27
28use super::hardware::{HardwareSigner, HardwareSignerError};
29use super::hybrid_sig::{HybridSignature, HybridVerifyingKey};
30use super::signer::Signer;
31use crate::crypto::CryptoError;
32
33/// Parse a hardware element's P-256 public key into a verifying key. Shipping elements emit the
34/// point in one of three shapes: compressed SEC1 (33 bytes), uncompressed SEC1 (65 bytes,
35/// `0x04‖x‖y`, e.g. Secure Enclave), or the bare `x‖y` coordinate pair (64 bytes, e.g. the TPM
36/// reference in the `tpm` adapter, which is `tpm`-feature-gated and so has no doc page in a
37/// default build). All three normalize to the same key.
38fn parse_p256_public(point: &[u8]) -> Result<P256VerifyingKey, HardwareSignerError> {
39    let vk = match point.len() {
40        33 | 65 => P256VerifyingKey::from_sec1_bytes(point),
41        64 => {
42            let mut sec1 = Vec::with_capacity(65);
43            sec1.push(0x04); // SEC1 uncompressed-point tag
44            sec1.extend_from_slice(point);
45            P256VerifyingKey::from_sec1_bytes(&sec1)
46        }
47        _ => {
48            return Err(HardwareSignerError::Backend(
49                "unexpected P-256 public key length".into(),
50            ));
51        }
52    };
53    vk.map_err(|_| HardwareSignerError::Backend("invalid P-256 public key".into()))
54}
55
56/// A hybrid device signing key whose classical half is a **hardware-held P-256 key** and whose
57/// ML-DSA-65 half is software-sealed. The P-256 analogue of
58/// [`HardwareBackedSigner`](super::hardware::HardwareBackedSigner).
59pub struct P256HybridSigningKey {
60    hardware: Arc<dyn HardwareSigner>,
61    key_alias: String,
62    ml: MlSigningKey<MlDsa65>,
63    verifying_key: HybridVerifyingKey,
64}
65
66impl P256HybridSigningKey {
67    /// Enroll a P-256 hardware key under `key_alias` and compose it with the software ML-DSA-65
68    /// half derived from `ml_seed` (the `ξ` half of the sealed DSK seed). Reads the element's
69    /// P-256 public key and builds the published hybrid verifying key from it plus the software
70    /// ML-DSA-65 public key.
71    pub fn enroll(
72        hardware: Arc<dyn HardwareSigner>,
73        key_alias: String,
74        ml_seed: &[u8; 32],
75    ) -> Result<Self, HardwareSignerError> {
76        let point = hardware.enroll(key_alias.clone())?;
77        let p256_vk = parse_p256_public(&point)?;
78        let seed = B32::try_from(&ml_seed[..])
79            .map_err(|_| HardwareSignerError::Backend("bad ML-DSA seed".into()))?;
80        let ml = MlSigningKey::<MlDsa65>::from_seed(&seed);
81        let verifying_key = HybridVerifyingKey::from_p256_parts(p256_vk, ml.verifying_key());
82        Ok(Self {
83            hardware,
84            key_alias,
85            ml,
86            verifying_key,
87        })
88    }
89}
90
91impl Signer for P256HybridSigningKey {
92    fn sign(&self, msg: &[u8]) -> Result<HybridSignature, CryptoError> {
93        // The element signs SHA-256(msg) and returns a DER-encoded ECDSA signature; the ML-DSA-65
94        // half is produced in software from the sealed ξ seed.
95        let der = self
96            .hardware
97            .sign_classical(self.key_alias.clone(), msg.to_vec())
98            .map_err(|_| CryptoError::Auth("hardware P-256 signature failed"))?;
99        let ml = self.ml.sign(msg).encode().to_vec();
100        Ok(HybridSignature::from_p256_halves(der, ml))
101    }
102
103    fn verifying_key(&self) -> HybridVerifyingKey {
104        self.verifying_key.clone()
105    }
106}
107
108/// An in-memory stand-in for a P-256 secure element (Secure Enclave / StrongBox / TPM). The
109/// software `p256` crate is the reference implementation the real element replaces: it signs
110/// SHA-256(msg) and returns DER-encoded ECDSA, and exposes its public key as uncompressed SEC1
111/// (`0x04‖x‖y`), the format Secure Enclave emits. Test-only; a real element keeps the P-256
112/// private key in hardware. Shared with the `verify_asset` chokepoint tests, so it lives outside
113/// the `tests` module (mirroring `MockHardwareSigner`).
114#[cfg(test)]
115pub(crate) struct MockP256Element {
116    sk: p256::ecdsa::SigningKey,
117    exportable: bool,
118}
119
120#[cfg(test)]
121impl MockP256Element {
122    pub(crate) fn new(scalar: [u8; 32], exportable: bool) -> Self {
123        Self {
124            sk: p256::ecdsa::SigningKey::from_slice(&scalar).expect("valid P-256 scalar"),
125            exportable,
126        }
127    }
128}
129
130#[cfg(test)]
131impl HardwareSigner for MockP256Element {
132    fn enroll(&self, alias: String) -> Result<Vec<u8>, HardwareSignerError> {
133        self.classical_public_key(alias)
134    }
135    fn classical_public_key(&self, _alias: String) -> Result<Vec<u8>, HardwareSignerError> {
136        Ok(self
137            .sk
138            .verifying_key()
139            .to_encoded_point(false)
140            .as_bytes()
141            .to_vec())
142    }
143    fn sign_classical(&self, _alias: String, msg: Vec<u8>) -> Result<Vec<u8>, HardwareSignerError> {
144        use p256::ecdsa::signature::Signer as _;
145        let sig: p256::ecdsa::Signature = self.sk.sign(&msg);
146        Ok(sig.to_der().as_bytes().to_vec())
147    }
148    fn assert_non_exportable(&self, _alias: String) -> Result<(), HardwareSignerError> {
149        if self.exportable {
150            Err(HardwareSignerError::Exportable)
151        } else {
152            Ok(())
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests;