vouch-core 4.2.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Post-quantum SLH-DSA-SHA2-128s (FIPS 205) keygen, sign, and verify.
//!
//! SLH-DSA is the stateless hash-based signature standard. Its security rests
//! on SHA-256 alone, so it does not share a failure mode with the lattice
//! problem behind ML-DSA. It is the signature behind the `slhdsa128-jcs-2024`
//! cryptosuite of the W3C Quantum-Resistant Cryptosuites draft, which names
//! the SLH-DSA-SHA2-128s parameter set: a 32-byte public key, a 64-byte
//! secret key and a 7856-byte signature.
//!
//! Signing is "pure" SLH-DSA with an empty context string (FIPS 205,
//! Algorithm 22). [`SlhDsa128KeyPair::sign`] is the hedged variant (fresh
//! randomness per signature), so two signatures over one message differ;
//! interop is asserted by cross-verification, never by signature equality.
//! [`SlhDsa128KeyPair::sign_deterministic`] is the deterministic variant, for
//! reproducible test vectors.

#[allow(unused_imports)]
use crate::prelude::*;

use slh_dsa::signature::{Keypair, RandomizedSigner, Signer, Verifier};
use slh_dsa::{Sha2_128s, Signature, SigningKey, VerifyingKey};

use crate::error::{CoreError, Result};

pub const SLHDSA128_PUBLIC_LEN: usize = 32;
pub const SLHDSA128_SECRET_LEN: usize = 64;
pub const SLHDSA128_SIG_LEN: usize = 7856;

/// The length of each of the four parts of a secret key (SK.seed, SK.prf,
/// PK.seed, PK.root); the last two are the public key.
const N: usize = 16;

/// An SLH-DSA-SHA2-128s key pair, stored as raw key bytes so both the secret
/// and the public material can be exported (the bindings need the secret to
/// sign).
pub struct SlhDsa128KeyPair {
    secret_bytes: [u8; SLHDSA128_SECRET_LEN],
    public_bytes: [u8; SLHDSA128_PUBLIC_LEN],
}

impl SlhDsa128KeyPair {
    /// Generate a fresh key pair using the platform CSPRNG.
    pub fn generate() -> Result<Self> {
        let sk = SigningKey::<Sha2_128s>::new(&mut crate::random::rng()?);
        Self::from_signing_key(&sk)
    }

    fn from_signing_key(sk: &SigningKey<Sha2_128s>) -> Result<Self> {
        let mut secret = sk.to_bytes();
        let public = sk.verifying_key().to_bytes();
        let pair = Self {
            secret_bytes: secret.as_slice().try_into().map_err(|_| {
                CoreError::Crypto("unexpected SLH-DSA-SHA2-128s secret key size".into())
            })?,
            public_bytes: public.as_slice().try_into().map_err(|_| {
                CoreError::Crypto("unexpected SLH-DSA-SHA2-128s public key size".into())
            })?,
        };
        zeroize::Zeroize::zeroize(secret.as_mut_slice());
        Ok(pair)
    }

    /// Import a key pair from a raw 64-byte secret key. The secret key holds
    /// its public key (its last 32 bytes); the pair is accepted only when that
    /// public key is the one key generation makes from the secret parts, so a
    /// spliced or damaged secret key is refused.
    pub fn from_secret(secret: &[u8]) -> Result<Self> {
        if secret.len() != SLHDSA128_SECRET_LEN {
            return Err(CoreError::InvalidKeyLength {
                expected: SLHDSA128_SECRET_LEN,
                got: secret.len(),
            });
        }
        // Rebuild the key from SK.seed, SK.prf and PK.seed: this derives
        // PK.root again, which must be the one the secret key carries.
        let rebuilt = SigningKey::<Sha2_128s>::slh_keygen_internal(
            &secret[..N],
            &secret[N..2 * N],
            &secret[2 * N..3 * N],
        );
        let pair = Self::from_signing_key(&rebuilt)?;
        if !constant_time_eq(&pair.secret_bytes, secret) {
            return Err(CoreError::Crypto(
                "the SLH-DSA-SHA2-128s secret key does not hold its own public key".into(),
            ));
        }
        Ok(pair)
    }

    /// Import a key pair from raw secret + public key bytes. The public key
    /// must be the one the secret key makes ([`Self::from_secret`]); a pair
    /// whose halves do not belong together is refused.
    pub fn from_bytes(secret: &[u8], public: &[u8]) -> Result<Self> {
        if public.len() != SLHDSA128_PUBLIC_LEN {
            return Err(CoreError::InvalidKeyLength {
                expected: SLHDSA128_PUBLIC_LEN,
                got: public.len(),
            });
        }
        let pair = Self::from_secret(secret)?;
        if pair.public_bytes != public {
            return Err(CoreError::Crypto(
                "the SLH-DSA-SHA2-128s public key does not match its private key".into(),
            ));
        }
        Ok(pair)
    }

    /// The 32-byte public key.
    pub fn public_key(&self) -> [u8; SLHDSA128_PUBLIC_LEN] {
        self.public_bytes
    }

    /// The 64-byte secret key.
    pub fn secret_key(&self) -> [u8; SLHDSA128_SECRET_LEN] {
        self.secret_bytes
    }

    fn signing_key(&self) -> Result<SigningKey<Sha2_128s>> {
        SigningKey::<Sha2_128s>::try_from(&self.secret_bytes[..])
            .map_err(|_| CoreError::Crypto("bad SLH-DSA-SHA2-128s secret key".into()))
    }

    /// Sign a message (pure SLH-DSA, empty context, hedged), returning the
    /// 7856-byte signature.
    pub fn sign(&self, message: &[u8]) -> Result<Vec<u8>> {
        let mut rng = crate::random::rng()?;
        let sig = self
            .signing_key()?
            .try_sign_with_rng(&mut rng, message)
            .map_err(|e| CoreError::Crypto(format!("slh-dsa sign: {e}")))?;
        Ok(sig.to_bytes().to_vec())
    }

    /// Sign a message with the deterministic variant (pure SLH-DSA, empty
    /// context): the same key and message always give the same signature.
    /// For reproducible test vectors; [`Self::sign`] is the one to use.
    pub fn sign_deterministic(&self, message: &[u8]) -> Result<Vec<u8>> {
        let sig = self
            .signing_key()?
            .try_sign(message)
            .map_err(|e| CoreError::Crypto(format!("slh-dsa sign: {e}")))?;
        Ok(sig.to_bytes().to_vec())
    }
}

impl Drop for SlhDsa128KeyPair {
    /// Wipe the secret key from memory when the pair goes away.
    fn drop(&mut self) {
        zeroize::Zeroize::zeroize(&mut self.secret_bytes);
    }
}

/// Compare two byte strings without stopping at the first difference.
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

/// Verify a 7856-byte SLH-DSA-SHA2-128s signature over a message against a
/// 32-byte public key (pure SLH-DSA, empty context). A key or a signature of
/// another length is an error; a signature that does not verify is `false`.
pub fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool> {
    if public_key.len() != SLHDSA128_PUBLIC_LEN {
        return Err(CoreError::InvalidKeyLength {
            expected: SLHDSA128_PUBLIC_LEN,
            got: public_key.len(),
        });
    }
    if signature.len() != SLHDSA128_SIG_LEN {
        return Err(CoreError::InvalidSignatureLength {
            expected: SLHDSA128_SIG_LEN,
            got: signature.len(),
        });
    }
    let vk = VerifyingKey::<Sha2_128s>::try_from(public_key)
        .map_err(|_| CoreError::Crypto("bad SLH-DSA-SHA2-128s public key".into()))?;
    let sig = Signature::<Sha2_128s>::try_from(signature)
        .map_err(|_| CoreError::Crypto("bad SLH-DSA-SHA2-128s signature".into()))?;
    Ok(vk.verify(message, &sig).is_ok())
}

// ---------------------------------------------------------------------------
// JSON in, JSON out (for the bindings)
// ---------------------------------------------------------------------------

use base64::{engine::general_purpose::STANDARD, Engine as _};
use serde_json::{json, Map, Value};
use zeroize::{Zeroize, Zeroizing};

fn refused(msg: impl Into<String>) -> CoreError {
    CoreError::Json(msg.into())
}

fn request_object<'a>(request: &'a Value, members: &[&str]) -> Result<&'a Map<String, Value>> {
    let obj = request
        .as_object()
        .ok_or_else(|| refused("the request must be a JSON object"))?;
    if let Some(name) = obj.keys().find(|k| !members.contains(&k.as_str())) {
        return Err(refused(format!(
            "the request holds an unknown member {:?}",
            name.chars().take(40).collect::<String>()
        )));
    }
    Ok(obj)
}

fn b64_member(obj: &Map<String, Value>, name: &str) -> Result<Vec<u8>> {
    let text = obj
        .get(name)
        .and_then(Value::as_str)
        .ok_or_else(|| refused(format!("{name} must be standard base64 text")))?;
    STANDARD
        .decode(text)
        .map_err(|_| refused(format!("{name} must be standard base64 text")))
}

fn public_json(pair: &SlhDsa128KeyPair) -> Result<Value> {
    Ok(json!({
        "publicKey": STANDARD.encode(pair.public_key()),
        "publicKeyMultibase": crate::multikey::encode_slhdsa128_public(&pair.public_key())?,
    }))
}

/// Generate an SLH-DSA-SHA2-128s key pair. The request is `{}`. Returns
/// `{"publicKey", "secretKey"}` (standard base64: 32 and 64 bytes) and
/// `"publicKeyMultibase"` (the Multikey, "u" plus base64url).
pub fn generate_json(request: &Value) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
    request_object(request, &[])?;
    let pair = SlhDsa128KeyPair::generate()?;
    let mut out = public_json(&pair)?;
    let mut secret = pair.secret_key();
    out["secretKey"] = Value::String(STANDARD.encode(secret));
    secret.zeroize();
    Ok(out)
}

/// The public key of a saved secret key: `{"secretKey"}` (base64, 64 bytes)
/// to `{"publicKey", "publicKeyMultibase"}`. A secret key that does not hold
/// its own public key is refused ([`SlhDsa128KeyPair::from_secret`]).
pub fn public_key_json(request: &Value) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
    let obj = request_object(request, &["secretKey"])?;
    let secret = Zeroizing::new(b64_member(obj, "secretKey")?);
    public_json(&SlhDsa128KeyPair::from_secret(&secret)?)
}

/// Sign a message: `{"secretKey"}` (base64, 64 bytes), `{"message"}`
/// (base64) to `{"signature"}` (base64, 7856 bytes). Signing is hedged, so
/// two signatures over one message differ. The secret key must hold its own
/// public key.
pub fn sign_json(request: &Value) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
    let obj = request_object(request, &["secretKey", "message"])?;
    let secret = Zeroizing::new(b64_member(obj, "secretKey")?);
    let message = b64_member(obj, "message")?;
    let pair = SlhDsa128KeyPair::from_secret(&secret)?;
    Ok(json!({ "signature": STANDARD.encode(pair.sign(&message)?) }))
}

/// [`sign_json`] for a request the caller hands over as text: the text and
/// the parsed secret key are wiped once the message is signed.
pub fn sign_json_text(mut request: String) -> Result<Value> {
    if let Err(e) = crate::nesting::check_text(request.as_bytes()) {
        request.zeroize();
        return Err(e);
    }
    let parsed = serde_json::from_str::<Value>(&request);
    request.zeroize();
    let mut parsed = parsed.map_err(|e| refused(format!("the request is not JSON: {e}")))?;
    let out = sign_json(&parsed);
    if let Some(Value::String(text)) = parsed.get_mut("secretKey") {
        text.zeroize();
    }
    out
}

/// Verify a signature: `{"publicKey"}` (base64, 32 bytes) or
/// `{"publicKeyMultibase"}`, `{"message"}` and `{"signature"}` (base64) to
/// `{"valid"}`. A key or a signature of the wrong length is `valid: false`,
/// never an error, so a caller cannot mistake a malformed input for a
/// failure to ask.
pub fn verify_json(request: &Value) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
    let obj = request_object(
        request,
        &["publicKey", "publicKeyMultibase", "message", "signature"],
    )?;
    let public = match (obj.get("publicKey"), obj.get("publicKeyMultibase")) {
        (Some(_), None) => b64_member(obj, "publicKey")?,
        (None, Some(Value::String(mk))) => match crate::multikey::decode(mk) {
            Ok(d) if d.algorithm == crate::multikey::SLHDSA128 => d.raw_key,
            _ => return Ok(json!({ "valid": false })),
        },
        _ => {
            return Err(refused(
                "give the key once, as publicKey or publicKeyMultibase",
            ))
        }
    };
    let message = b64_member(obj, "message")?;
    let signature = b64_member(obj, "signature")?;
    Ok(json!({ "valid": verify(&public, &message, &signature).unwrap_or(false) }))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn sizes_match_fips_205() {
        let kp = SlhDsa128KeyPair::generate().unwrap();
        assert_eq!(kp.public_key().len(), SLHDSA128_PUBLIC_LEN);
        assert_eq!(kp.secret_key().len(), SLHDSA128_SECRET_LEN);
        // The public key is the second half of the secret key.
        assert_eq!(kp.secret_key()[32..], kp.public_key());
        let sig = kp.sign(b"message").unwrap();
        assert_eq!(sig.len(), SLHDSA128_SIG_LEN);
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn sign_verify_tamper_wrong_key_truncated() {
        let kp = SlhDsa128KeyPair::generate().unwrap();
        let other = SlhDsa128KeyPair::generate().unwrap();
        let sig = kp.sign(b"message").unwrap();
        assert!(verify(&kp.public_key(), b"message", &sig).unwrap());
        assert!(!verify(&kp.public_key(), b"messagf", &sig).unwrap());
        assert!(!verify(&other.public_key(), b"message", &sig).unwrap());
        let mut flipped = sig.clone();
        flipped[100] ^= 1;
        assert!(!verify(&kp.public_key(), b"message", &flipped).unwrap());
        assert!(verify(&kp.public_key(), b"message", &sig[..SLHDSA128_SIG_LEN - 1]).is_err());
        assert!(verify(&kp.public_key()[..31], b"message", &sig).is_err());
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn hedged_signatures_differ_and_deterministic_ones_repeat() {
        let kp = SlhDsa128KeyPair::generate().unwrap();
        assert_ne!(kp.sign(b"m").unwrap(), kp.sign(b"m").unwrap());
        let a = kp.sign_deterministic(b"m").unwrap();
        assert_eq!(a, kp.sign_deterministic(b"m").unwrap());
        assert!(verify(&kp.public_key(), b"m", &a).unwrap());
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn json_entry_points_round_trip() {
        let made = generate_json(&json!({})).unwrap();
        let secret = made["secretKey"].as_str().unwrap();
        let again = public_key_json(&json!({ "secretKey": secret })).unwrap();
        assert_eq!(again["publicKey"], made["publicKey"]);
        assert_eq!(again["publicKeyMultibase"], made["publicKeyMultibase"]);
        let message = STANDARD.encode(b"hello");
        let signed =
            sign_json_text(json!({"secretKey": secret, "message": message}).to_string()).unwrap();
        let ok = |request: Value| verify_json(&request).unwrap()["valid"] == true;
        assert!(ok(
            json!({"publicKey": made["publicKey"], "message": message,
            "signature": signed["signature"]})
        ));
        assert!(ok(json!({"publicKeyMultibase": made["publicKeyMultibase"],
            "message": message, "signature": signed["signature"]})));
        assert!(!ok(json!({"publicKey": made["publicKey"],
            "message": STANDARD.encode(b"hellp"), "signature": signed["signature"]})));
        // A short signature and a short key are not valid, and not an error.
        assert!(!ok(
            json!({"publicKey": made["publicKey"], "message": message,
            "signature": STANDARD.encode([0u8; 100])})
        ));
        assert!(!ok(
            json!({"publicKey": STANDARD.encode([0u8; 31]), "message": message,
            "signature": signed["signature"]})
        ));
        assert!(!ok(
            json!({"publicKeyMultibase": "z6Mk", "message": message,
            "signature": signed["signature"]})
        ));
        assert!(generate_json(&json!({"seed": "x"})).is_err());
        assert!(sign_json(&json!({"secretKey": STANDARD.encode([1u8; 64]),
            "message": message}))
        .is_err());
        assert!(verify_json(&json!({"message": message, "signature": message})).is_err());
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn import_refuses_a_pair_that_does_not_belong_together() {
        let kp = SlhDsa128KeyPair::generate().unwrap();
        let other = SlhDsa128KeyPair::generate().unwrap();
        let again = SlhDsa128KeyPair::from_bytes(&kp.secret_key(), &kp.public_key()).unwrap();
        assert_eq!(again.public_key(), kp.public_key());
        assert!(SlhDsa128KeyPair::from_bytes(&kp.secret_key(), &other.public_key()).is_err());
        // A secret key whose public half was swapped for another key's.
        let mut spliced = kp.secret_key();
        spliced[32..].copy_from_slice(&other.public_key());
        assert!(SlhDsa128KeyPair::from_secret(&spliced).is_err());
        // A secret key whose PK.root was damaged.
        let mut damaged = kp.secret_key();
        damaged[63] ^= 1;
        assert!(SlhDsa128KeyPair::from_secret(&damaged).is_err());
        assert!(SlhDsa128KeyPair::from_secret(&kp.secret_key()[..63]).is_err());
    }
}