Skip to main content

ratify_protocol/v2/
crypto.rs

1//! Typed v2 signing transcripts for every registered object code
2//! (mirrors Go `crypto_v2.go`).
3
4use ed25519_dalek::{Signature as EdSignature, Signer as _, SigningKey, VerifyingKey};
5use fips204::ml_dsa_65;
6use fips204::traits::{SerDes, Signer, Verifier};
7use sha2::{Digest, Sha256, Sha384};
8
9use super::errors::{err, plain, Classify, V2Error, V2ErrorClass, V2Result};
10use crate::crypto_v2::{validate_ed_public_key, validate_ed_signature};
11use crate::types::{HybridPrivateKey, HybridPublicKey, HybridSignature};
12use zeroize::Zeroizing;
13
14/// The closed v2 signed-object registry (SPEC-v2 §4).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[repr(u16)]
17pub enum V2ObjectType {
18    DelegationCertificate = 0x0001,
19    ChallengePresentation = 0x0002,
20    RevocationList = 0x0003,
21    KeyRotationAuthorization = 0x0004,
22    RevocationPush = 0x0005,
23    WitnessEntry = 0x0006,
24    TransactionPartyStatement = 0x0007,
25    VerificationReceipt = 0x0008,
26    KeyRotationProofOfPossession = 0x0009,
27}
28
29impl V2ObjectType {
30    pub fn code(self) -> u16 {
31        self as u16
32    }
33
34    pub fn from_code(code: u16) -> Option<Self> {
35        use V2ObjectType::*;
36        Some(match code {
37            0x0001 => DelegationCertificate,
38            0x0002 => ChallengePresentation,
39            0x0003 => RevocationList,
40            0x0004 => KeyRotationAuthorization,
41            0x0005 => RevocationPush,
42            0x0006 => WitnessEntry,
43            0x0007 => TransactionPartyStatement,
44            0x0008 => VerificationReceipt,
45            0x0009 => KeyRotationProofOfPossession,
46            _ => return None,
47        })
48    }
49}
50
51/// Full 256-bit v2 key ID: hex(SHA-256("ratify-key-id-v2\0" || ed25519 || ml_dsa_65)).
52pub fn key_id_v2(key: &HybridPublicKey) -> V2Result<String> {
53    if key.ed25519.len() != 32 {
54        return err(
55            V2ErrorClass::Malformed,
56            format!("Ed25519 public key wrong length: {}", key.ed25519.len()),
57        );
58    }
59    if key.ml_dsa_65.len() != ml_dsa_65::PK_LEN {
60        return err(
61            V2ErrorClass::Malformed,
62            format!("ML-DSA-65 public key wrong length: {}", key.ml_dsa_65.len()),
63        );
64    }
65    let mut h = Sha256::new();
66    h.update(b"ratify-key-id-v2\0");
67    h.update(&key.ed25519);
68    h.update(&key.ml_dsa_65);
69    Ok(hex::encode(h.finalize()))
70}
71
72/// M = "ratify-protocol-signature\0\x02" || code_be16 || SHA-384(signable).
73pub fn v2_signing_message(object_type: V2ObjectType, signable: &[u8]) -> Vec<u8> {
74    let digest = Sha384::digest(signable);
75    let mut m = Vec::with_capacity(77);
76    m.extend_from_slice(b"ratify-protocol-signature\0\x02");
77    m.extend_from_slice(&object_type.code().to_be_bytes());
78    m.extend_from_slice(&digest);
79    m
80}
81
82/// ML-DSA-65 context string "ratify-protocol/2/XXXX".
83pub fn v2_mldsa_context(object_type: V2ObjectType) -> Vec<u8> {
84    format!("ratify-protocol/2/{:04x}", object_type.code()).into_bytes()
85}
86
87pub(crate) fn ed_seed(private_key: &HybridPrivateKey) -> V2Result<Zeroizing<[u8; 32]>> {
88    // The Rust SDK stores the 32-byte seed; a 64-byte seed||public form is
89    // also accepted when its public half matches the seed (Go layout).
90    let ed = private_key.ed25519();
91    let seed = match ed.get(..32).map(<[u8; 32]>::try_from) {
92        Some(Ok(seed)) if matches!(ed.len(), 32 | 64) => Zeroizing::new(seed),
93        _ => return plain("incomplete hybrid private key"),
94    };
95    if ed.len() == 64
96        && SigningKey::from_bytes(&seed).verifying_key().to_bytes()[..] != ed[32..]
97    {
98        return plain("Ed25519 private key seed and public component do not match");
99    }
100    Ok(seed)
101}
102
103pub(crate) fn ml_secret(private_key: &HybridPrivateKey) -> V2Result<ml_dsa_65::PrivateKey> {
104    let bytes: Zeroizing<[u8; ml_dsa_65::SK_LEN]> = Zeroizing::new(
105        private_key
106            .ml_dsa_65()
107            .try_into()
108            .map_err(|_| V2Error::plain("incomplete hybrid private key"))?,
109    );
110    ml_dsa_65::PrivateKey::try_from_bytes(*bytes)
111        .map_err(|_| V2Error::plain("ML-DSA-65 secret key malformed"))
112}
113
114/// Derive the hybrid public key of a private key (both components validated).
115pub fn public_key_v2(private_key: &HybridPrivateKey) -> V2Result<HybridPublicKey> {
116    let seed = ed_seed(private_key).classify(V2ErrorClass::Malformed)?;
117    let ml = ml_secret(private_key).classify(V2ErrorClass::Malformed)?;
118    Ok(HybridPublicKey {
119        ed25519: SigningKey::from_bytes(&seed)
120            .verifying_key()
121            .to_bytes()
122            .to_vec(),
123        ml_dsa_65: ml.get_public_key().into_bytes().to_vec(),
124    })
125}
126
127/// Sign the SDK-computed `M` under the registry context. `hedged` selects
128/// randomized ML-DSA-65 signing; deterministic signing (an all-zero `rnd`,
129/// FIPS 204 §3.4) is used only by fixed test fixtures.
130pub(crate) fn sign_v2_message(
131    seed: &[u8; 32],
132    ml: &ml_dsa_65::PrivateKey,
133    message: &[u8],
134    context: &[u8],
135    hedged: bool,
136) -> V2Result<HybridSignature> {
137    let ed = SigningKey::from_bytes(seed).sign(message);
138    let ml_sig = if hedged {
139        ml.try_sign(message, context)
140    } else {
141        ml.try_sign_with_seed(&[0u8; 32], message, context)
142    }
143    .map_err(|e| V2Error::plain(format!("ML-DSA-65 v2 sign: {e}")))?;
144    Ok(HybridSignature {
145        ed25519: ed.to_bytes().to_vec(),
146        ml_dsa_65: ml_sig.to_vec(),
147    })
148}
149
150/// Deterministic signing for fixed test fixtures only (never exported).
151#[cfg(test)]
152pub(crate) fn sign_v2_statement_deterministic(
153    object_type: V2ObjectType,
154    signable: &[u8],
155    private_key: &HybridPrivateKey,
156) -> V2Result<HybridSignature> {
157    let seed = ed_seed(private_key)?;
158    let ml = ml_secret(private_key)?;
159    sign_v2_message(
160        &seed,
161        &ml,
162        &v2_signing_message(object_type, signable),
163        &v2_mldsa_context(object_type),
164        false,
165    )
166}
167
168/// Strict AND verification of both components. An unregistered code is
169/// `unsupported_object_type`; every other failure is `invalid_signature`.
170pub fn verify_v2_statement_code(
171    object_type_code: u16,
172    signable: &[u8],
173    signature: &HybridSignature,
174    public_key: &HybridPublicKey,
175) -> V2Result<()> {
176    let Some(object_type) = V2ObjectType::from_code(object_type_code) else {
177        return err(
178            V2ErrorClass::UnsupportedObjectType,
179            format!("unsupported v2 object type: {object_type_code:04x}"),
180        );
181    };
182    verify_v2_statement(object_type, signable, signature, public_key)
183}
184
185/// Strict AND verification of both components under a registered code.
186pub fn verify_v2_statement(
187    object_type: V2ObjectType,
188    signable: &[u8],
189    signature: &HybridSignature,
190    public_key: &HybridPublicKey,
191) -> V2Result<()> {
192    verify_unclassified(object_type, signable, signature, public_key)
193        .map_err(|m| V2Error::new(V2ErrorClass::InvalidSignature, m))
194}
195
196/// Strict AND verification of both components over an already-computed
197/// transcript `message`, which must be exactly the 77-byte v2 signing message
198/// for `object_type` (`v2_signing_message`); the ML-DSA-65 context is derived
199/// from `object_type`. For bindings that compute `M` themselves. Every
200/// failure, including a message that is not a transcript for `object_type`,
201/// is `invalid_signature`.
202pub fn verify_v2_message(
203    object_type: V2ObjectType,
204    message: &[u8],
205    signature: &HybridSignature,
206    public_key: &HybridPublicKey,
207) -> V2Result<()> {
208    verify_message_unclassified(object_type, message, signature, public_key)
209        .map_err(|m| V2Error::new(V2ErrorClass::InvalidSignature, m))
210}
211
212fn verify_unclassified(
213    object_type: V2ObjectType,
214    signable: &[u8],
215    signature: &HybridSignature,
216    public_key: &HybridPublicKey,
217) -> Result<(), String> {
218    let message = v2_signing_message(object_type, signable);
219    verify_message_unclassified(object_type, &message, signature, public_key)
220}
221
222fn verify_message_unclassified(
223    object_type: V2ObjectType,
224    message: &[u8],
225    signature: &HybridSignature,
226    public_key: &HybridPublicKey,
227) -> Result<(), String> {
228    const PREFIX: &[u8] = b"ratify-protocol-signature\0\x02";
229    if message.len() != 77
230        || !message.starts_with(PREFIX)
231        || message[PREFIX.len()..PREFIX.len() + 2] != object_type.code().to_be_bytes()
232    {
233        return Err("message is not the v2 signing transcript for this object type".into());
234    }
235    if public_key.ed25519.len() != 32 || public_key.ml_dsa_65.len() != ml_dsa_65::PK_LEN {
236        return Err("hybrid public key has invalid component length".into());
237    }
238    if signature.ed25519.len() != 64 || signature.ml_dsa_65.len() != ml_dsa_65::SIG_LEN {
239        return Err("hybrid signature has invalid component length".into());
240    }
241    validate_ed_public_key(&public_key.ed25519)?;
242    validate_ed_signature(&signature.ed25519)?;
243    let ed_bytes: [u8; 32] = public_key.ed25519[..]
244        .try_into()
245        .map_err(|_| "hybrid public key has invalid component length".to_string())?;
246    let ed_key = VerifyingKey::from_bytes(&ed_bytes)
247        .map_err(|_| "Ed25519 v2 public key malformed".to_string())?;
248    let ed_sig = EdSignature::from_slice(&signature.ed25519)
249        .map_err(|_| "Ed25519 v2 signature malformed".to_string())?;
250    ed_key
251        .verify_strict(message, &ed_sig)
252        .map_err(|_| "Ed25519 v2 signature invalid".to_string())?;
253    let ml_pk_bytes: [u8; ml_dsa_65::PK_LEN] = public_key.ml_dsa_65[..]
254        .try_into()
255        .map_err(|_| "hybrid public key has invalid component length".to_string())?;
256    let ml_pk = ml_dsa_65::PublicKey::try_from_bytes(ml_pk_bytes)
257        .map_err(|_| "ML-DSA-65 public key malformed".to_string())?;
258    let ml_sig: [u8; ml_dsa_65::SIG_LEN] = signature.ml_dsa_65[..]
259        .try_into()
260        .map_err(|_| "hybrid signature has invalid component length".to_string())?;
261    if !ml_pk.verify(message, &ml_sig, &v2_mldsa_context(object_type)) {
262        return Err("ML-DSA-65 v2 signature invalid".into());
263    }
264    Ok(())
265}
266
267pub(crate) fn equal_keys(a: &HybridPublicKey, b: &HybridPublicKey) -> bool {
268    a.ed25519 == b.ed25519 && a.ml_dsa_65 == b.ml_dsa_65
269}
270
271/// 64 lowercase hexadecimal characters (a full v2 key ID).
272pub fn valid_v2_id(id: &str) -> bool {
273    id.len() == 64 && lower_hex(id)
274}
275
276pub(crate) fn lower_hex(value: &str) -> bool {
277    value
278        .bytes()
279        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
280}
281
282/// "sha384:" followed by 96 lowercase hexadecimal characters.
283pub(crate) fn valid_prefixed_digest(value: &str) -> bool {
284    value
285        .strip_prefix("sha384:")
286        .is_some_and(|h| h.len() == 96 && lower_hex(h))
287}
288
289pub(crate) fn sha384(parts: &[&[u8]]) -> Vec<u8> {
290    let mut h = Sha384::new();
291    for p in parts {
292        h.update(p);
293    }
294    h.finalize().to_vec()
295}
296
297pub(crate) fn sha256(parts: &[&[u8]]) -> Vec<u8> {
298    let mut h = Sha256::new();
299    for p in parts {
300        h.update(p);
301    }
302    h.finalize().to_vec()
303}
304
305/// Big-endian u64 length prefix followed by the bytes.
306pub(crate) fn lp(value: &[u8]) -> Vec<u8> {
307    let mut out = (value.len() as u64).to_be_bytes().to_vec();
308    out.extend_from_slice(value);
309    out
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use crate::crypto::generate_hybrid_keypair;
316
317    // Fixed fixtures depend on deterministic signing reproducing the same
318    // bytes, and the registry code must domain-separate every object type.
319    #[test]
320    fn deterministic_signing_is_reproducible_and_bound_to_the_object_type() {
321        let (public, private) = generate_hybrid_keypair();
322        let signable = b"fixture signable bytes";
323        let a = sign_v2_statement_deterministic(V2ObjectType::WitnessEntry, signable, &private)
324            .unwrap();
325        let b = sign_v2_statement_deterministic(V2ObjectType::WitnessEntry, signable, &private)
326            .unwrap();
327        assert_eq!(a, b);
328        verify_v2_statement(V2ObjectType::WitnessEntry, signable, &a, &public).unwrap();
329        let wrong =
330            verify_v2_statement(V2ObjectType::RevocationPush, signable, &a, &public).unwrap_err();
331        assert_eq!(wrong.class, V2ErrorClass::InvalidSignature);
332    }
333
334    // A binding that computes M itself must get the same verdict as the
335    // signable-bytes entry point, and M must be the transcript for the code.
336    #[test]
337    fn verify_v2_message_matches_statement_verification() {
338        let (public, private) = generate_hybrid_keypair();
339        let signable = b"fixture signable bytes";
340        let ty = V2ObjectType::VerificationReceipt;
341        let sig = sign_v2_statement_deterministic(ty, signable, &private).unwrap();
342        let message = v2_signing_message(ty, signable);
343        verify_v2_message(ty, &message, &sig, &public).unwrap();
344
345        let other =
346            verify_v2_message(V2ObjectType::WitnessEntry, &message, &sig, &public).unwrap_err();
347        assert_eq!(other.class, V2ErrorClass::InvalidSignature);
348        let short = verify_v2_message(ty, &message[..76], &sig, &public).unwrap_err();
349        assert_eq!(short.class, V2ErrorClass::InvalidSignature);
350        let mut tampered = message.clone();
351        tampered[76] ^= 1;
352        let bad = verify_v2_message(ty, &tampered, &sig, &public).unwrap_err();
353        assert_eq!(bad.class, V2ErrorClass::InvalidSignature);
354        let mut ml_bad = sig.clone();
355        ml_bad.ml_dsa_65[0] ^= 1;
356        let ml = verify_v2_message(ty, &message, &ml_bad, &public).unwrap_err();
357        assert_eq!(ml.class, V2ErrorClass::InvalidSignature);
358    }
359}