Skip to main content

ratify_protocol/
crypto_v2.rs

1//! Protocol v2 delegation signature primitives.
2//!
3//! This module intentionally implements the v2 signature transcript only; it
4//! does not parse or validate complete v2 protocol objects.
5
6use alloc::{string::{String, ToString}, vec::Vec};
7
8use curve25519_dalek::{edwards::CompressedEdwardsY, traits::IsIdentity};
9use ed25519_dalek::{Signature as EdSignature, VerifyingKey};
10#[cfg(test)]
11use ed25519_dalek::{Signer as _, SigningKey};
12use fips204::ml_dsa_65;
13use fips204::traits::{SerDes, Verifier};
14#[cfg(test)]
15use fips204::traits::Signer;
16use sha2::{Digest, Sha256, Sha384};
17
18#[cfg(test)]
19use crate::types::HybridPrivateKey;
20use crate::types::{HybridPublicKey, HybridSignature};
21
22const SIGNATURE_PREFIX: &[u8] = b"ratify-protocol-signature\0\x02";
23const KEY_ID_PREFIX: &[u8] = b"ratify-key-id-v2\0";
24const DELEGATION_CODE: u16 = 0x0001;
25const ML_DSA_CONTEXT: &[u8] = b"ratify-protocol/2/0001";
26const ED25519_ORDER_LE: [u8; 32] = [
27    0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
28    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
29];
30
31/// Construct the fixed v2 signing message for a delegation certificate.
32pub fn delegation_signature_message_v2(signable_bytes: &[u8]) -> Vec<u8> {
33    signature_message(DELEGATION_CODE, signable_bytes)
34}
35
36fn signature_message(object_type_code: u16, signable_bytes: &[u8]) -> Vec<u8> {
37    let digest = Sha384::digest(signable_bytes);
38    let mut message = Vec::with_capacity(SIGNATURE_PREFIX.len() + 2 + digest.len());
39    message.extend_from_slice(SIGNATURE_PREFIX);
40    message.extend_from_slice(&object_type_code.to_be_bytes());
41    message.extend_from_slice(&digest);
42    message
43}
44
45/// Derive the v2 hybrid key ID from both public key components.
46pub fn derive_key_id_v2(pub_key: &HybridPublicKey) -> Result<String, String> {
47    if pub_key.ed25519.len() != 32 || pub_key.ml_dsa_65.len() != ml_dsa_65::PK_LEN {
48        return Err("v2 hybrid public key has a component with the wrong length".into());
49    }
50    let mut hasher = Sha256::new();
51    hasher.update(KEY_ID_PREFIX);
52    hasher.update(&pub_key.ed25519);
53    hasher.update(&pub_key.ml_dsa_65);
54    Ok(hex::encode(hasher.finalize()))
55}
56
57/// Sign delegation signable bytes with both v2 components and fixed contexts.
58/// Test-only: no exported function signs caller-selected bytes (SPEC-v2 §3.2).
59#[cfg(test)]
60pub(crate) fn sign_delegation_v2(
61    signable_bytes: &[u8],
62    private_key: &HybridPrivateKey,
63) -> Result<HybridSignature, String> {
64    let message = signature_message(DELEGATION_CODE, signable_bytes);
65    let ed_seed: [u8; 32] = private_key
66        .ed25519()
67        .try_into()
68        .map_err(|_| "v2 Ed25519 seed must be 32 bytes".to_string())?;
69    let ed_signature = SigningKey::from_bytes(&ed_seed).sign(&message);
70
71    let ml_sk_bytes: [u8; ml_dsa_65::SK_LEN] = private_key
72        .ml_dsa_65()
73        .try_into()
74        .map_err(|_| "v2 ML-DSA-65 secret key has wrong length".to_string())?;
75    let ml_sk = ml_dsa_65::PrivateKey::try_from_bytes(ml_sk_bytes)
76        .map_err(|_| "v2 ML-DSA-65 secret key malformed".to_string())?;
77    let ml_signature = ml_sk
78        .try_sign(&message, ML_DSA_CONTEXT)
79        .map_err(|_| "v2 ML-DSA-65 signing failed".to_string())?;
80
81    Ok(HybridSignature {
82        ed25519: ed_signature.to_bytes().to_vec(),
83        ml_dsa_65: ml_signature.to_vec(),
84    })
85}
86
87/// Verify both mandatory components using the v2 fixed message and context.
88pub fn verify_delegation_v2(
89    signable_bytes: &[u8],
90    signature: &HybridSignature,
91    public_key: &HybridPublicKey,
92) -> Result<(), String> {
93    if public_key.ed25519.len() != 32 || signature.ed25519.len() != 64 {
94        return Err("v2 Ed25519 key or signature has wrong length".into());
95    }
96    if public_key.ml_dsa_65.len() != ml_dsa_65::PK_LEN
97        || signature.ml_dsa_65.len() != ml_dsa_65::SIG_LEN
98    {
99        return Err("v2 ML-DSA-65 key or signature has wrong length".into());
100    }
101    validate_ed_public_key(&public_key.ed25519)?;
102    validate_ed_signature(&signature.ed25519)?;
103
104    let ed_bytes: [u8; 32] = public_key.ed25519.as_slice().try_into().unwrap();
105    let ed_key = VerifyingKey::from_bytes(&ed_bytes)
106        .map_err(|_| "v2 Ed25519 public key malformed".to_string())?;
107    let ed_signature = EdSignature::from_slice(&signature.ed25519)
108        .map_err(|_| "v2 Ed25519 signature malformed".to_string())?;
109    let message = signature_message(DELEGATION_CODE, signable_bytes);
110    ed_key
111        .verify_strict(&message, &ed_signature)
112        .map_err(|_| "v2 Ed25519 signature invalid".to_string())?;
113
114    let ml_pk_bytes: [u8; ml_dsa_65::PK_LEN] = public_key.ml_dsa_65.as_slice().try_into().unwrap();
115    let ml_pk = ml_dsa_65::PublicKey::try_from_bytes(ml_pk_bytes)
116        .map_err(|_| "v2 ML-DSA-65 public key malformed".to_string())?;
117    let ml_sig: [u8; ml_dsa_65::SIG_LEN] = signature.ml_dsa_65.as_slice().try_into().unwrap();
118    if !ml_pk.verify(&message, &ml_sig, ML_DSA_CONTEXT) {
119        return Err("v2 ML-DSA-65 signature invalid".into());
120    }
121    Ok(())
122}
123
124pub(crate) fn validate_ed_public_key(encoded: &[u8]) -> Result<(), String> {
125    if encoded.len() != 32 {
126        return Err("v2 Ed25519 public key must be 32 bytes".into());
127    }
128    let bytes: [u8; 32] = encoded.try_into().unwrap();
129    let mut y_bytes = bytes;
130    y_bytes[31] &= 0x7f;
131    if little_endian_ge(&y_bytes, &FIELD_MODULUS_LE) {
132        return Err("v2 Ed25519 point encoding is non-canonical".into());
133    }
134    let point = CompressedEdwardsY(bytes)
135        .decompress()
136        .ok_or_else(|| "v2 Ed25519 point is not on curve".to_string())?;
137    if point.compress().to_bytes() != bytes || point.is_identity() || !point.is_torsion_free() {
138        return Err("v2 Ed25519 point must be canonical, non-identity, and prime-order".into());
139    }
140    Ok(())
141}
142
143pub(crate) fn validate_ed_signature(encoded: &[u8]) -> Result<(), String> {
144    if encoded.len() != 64 {
145        return Err("v2 Ed25519 signature must be 64 bytes".into());
146    }
147    validate_ed_public_key(&encoded[..32])
148        .map_err(|_| "v2 Ed25519 R point is invalid".to_string())?;
149    if little_endian_ge(&encoded[32..], &ED25519_ORDER_LE) {
150        return Err("v2 Ed25519 scalar S is non-canonical".into());
151    }
152    Ok(())
153}
154
155const FIELD_MODULUS_LE: [u8; 32] = [
156    0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
157    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
158];
159
160fn little_endian_ge(left: &[u8], right: &[u8; 32]) -> bool {
161    left.iter().rev().cmp(right.iter().rev()).is_ge()
162}
163
164#[cfg(test)]
165mod tests {
166    use super::{
167        sign_delegation_v2, validate_ed_public_key, validate_ed_signature, verify_delegation_v2,
168    };
169    use crate::crypto::generate_hybrid_keypair;
170    use crate::v2::{verify_v2_statement, V2ObjectType};
171    use curve25519_dalek::edwards::CompressedEdwardsY;
172    use ed25519_dalek::{Signer, SigningKey};
173
174    // The delegation helper and the typed registry must produce the same
175    // transcript: a delegation signed one way verifies the other way.
176    #[test]
177    fn delegation_signing_matches_the_typed_registry_transcript() {
178        let (public, private) = generate_hybrid_keypair();
179        let signable = b"delegation signable bytes";
180        let signature = sign_delegation_v2(signable, &private).unwrap();
181        verify_delegation_v2(signable, &signature, &public).unwrap();
182        verify_v2_statement(
183            V2ObjectType::DelegationCertificate,
184            signable,
185            &signature,
186            &public,
187        )
188        .unwrap();
189        assert!(verify_delegation_v2(b"other bytes", &signature, &public).is_err());
190    }
191
192    fn mixed_order_encoding() -> [u8; 32] {
193        let prime = SigningKey::from_bytes(&[7; 32]).verifying_key();
194        let prime = CompressedEdwardsY(prime.to_bytes()).decompress().unwrap();
195        let mut order_two_bytes = [0xff; 32];
196        order_two_bytes[0] = 0xec;
197        order_two_bytes[31] = 0x7f;
198        let order_two = CompressedEdwardsY(order_two_bytes).decompress().unwrap();
199        (prime + order_two).compress().to_bytes()
200    }
201
202    #[test]
203    fn v2_point_validation_rejects_mixed_order_a_and_r_at_the_subgroup_gate() {
204        let mixed = mixed_order_encoding();
205        assert_eq!(
206            validate_ed_public_key(&mixed).unwrap_err(),
207            "v2 Ed25519 point must be canonical, non-identity, and prime-order"
208        );
209
210        let signing_key = SigningKey::from_bytes(&[9; 32]);
211        let mut signature = signing_key.sign(b"test").to_bytes();
212        signature[..32].copy_from_slice(&mixed);
213        assert_eq!(
214            validate_ed_signature(&signature).unwrap_err(),
215            "v2 Ed25519 R point is invalid"
216        );
217    }
218
219    #[test]
220    fn v2_point_validation_rejects_identity_small_order_and_noncanonical_y() {
221        let mut identity = [0; 32];
222        identity[0] = 1;
223        assert!(validate_ed_public_key(&identity).is_err());
224
225        let mut order_two = [0xff; 32];
226        order_two[0] = 0xec;
227        order_two[31] = 0x7f;
228        assert!(validate_ed_public_key(&order_two).is_err());
229
230        let mut y_above_modulus = [0xff; 32];
231        y_above_modulus[0] = 0xee;
232        y_above_modulus[31] = 0x7f;
233        assert_eq!(
234            validate_ed_public_key(&y_above_modulus).unwrap_err(),
235            "v2 Ed25519 point encoding is non-canonical"
236        );
237
238        let mut negative_zero = [0; 32];
239        negative_zero[0] = 1;
240        negative_zero[31] = 0x80;
241        assert!(validate_ed_public_key(&negative_zero).is_err());
242    }
243
244    #[test]
245    fn v2_point_validation_rejects_noncanonical_s() {
246        let signing_key = SigningKey::from_bytes(&[11; 32]);
247        let mut signature = signing_key.sign(b"test").to_bytes();
248        signature[32..].copy_from_slice(&[
249            0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9,
250            0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
251            0x00, 0x00, 0x00, 0x10,
252        ]);
253        assert_eq!(
254            validate_ed_signature(&signature).unwrap_err(),
255            "v2 Ed25519 scalar S is non-canonical"
256        );
257    }
258}