libsoliton 0.1.3

Core cryptographic library for the LO protocol — hybrid post-quantum key exchange, signatures, ratchet, and storage encryption
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! LO composite key and hybrid signatures (§2, §3).
//!
//! LO composite key = X-Wing (X25519 + ML-KEM-768) + Ed25519 + ML-DSA-65.
//! Public key: 1216 + 32 + 1952 = 3200 bytes.
//! Secret key: 2432 + 32 + 32 (ML-DSA seed) = 2496 bytes.
//! Hybrid signature: Ed25519 (64) + ML-DSA-65 (3309) = 3373 bytes.
//!
//! ## Key Separation
//!
//! The X25519 key inside X-Wing is used exclusively for KEM (key agreement).
//! A separate Ed25519 keypair provides classical signing. This clean separation
//! means X25519 never participates in signing — no Montgomery↔Edwards
//! conversion needed, no dual-use security argument required.

use crate::constants;
use crate::error::{Error, Result};
use crate::primitives::{ed25519, mldsa, sha3_256, xwing};
use subtle::Choice;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

/// LO composite public key (3200 bytes): X-Wing_pk || Ed25519_pk || ML-DSA-65_pk.
#[derive(Clone, Eq)]
pub struct IdentityPublicKey(pub(crate) Vec<u8>);

// Constant-time comparison: IdentityPublicKey may be compared against
// untrusted wire data (e.g., in verify_bundle). Variable-time memcmp
// would leak how many leading bytes match.
impl PartialEq for IdentityPublicKey {
    fn eq(&self, other: &Self) -> bool {
        use subtle::ConstantTimeEq;
        self.0.ct_eq(&other.0).into()
    }
}

/// LO composite secret key: X-Wing_sk || Ed25519_sk || ML-DSA-65_sk.
#[derive(Zeroize, ZeroizeOnDrop)]
pub struct IdentitySecretKey(pub(crate) Vec<u8>);

/// Hybrid signature (3373 bytes): Ed25519_sig || ML-DSA-65_sig.
#[derive(Clone, PartialEq, Eq)]
pub struct HybridSignature(pub(crate) Vec<u8>);

impl IdentityPublicKey {
    /// Return the raw byte representation.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Construct from raw bytes with size validation only.
    ///
    /// Accepts any buffer of exactly `LO_PUBLIC_KEY_SIZE` bytes — sub-key
    /// structure (X-Wing, Ed25519, ML-DSA-65 components) is not validated here.
    /// Invalid sub-key bytes will produce errors at point of use (encapsulate,
    /// verify, etc.). This is intentional: eagerly parsing all sub-keys on
    /// construction would add expensive ML-DSA key parsing to every deserialization.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
        if bytes.len() != constants::LO_PUBLIC_KEY_SIZE {
            return Err(Error::InvalidLength {
                expected: constants::LO_PUBLIC_KEY_SIZE,
                got: bytes.len(),
            });
        }
        Ok(Self(bytes))
    }

    /// Extract the X25519 public key (first 32 bytes, inside X-Wing).
    pub fn x25519_pk(&self) -> &[u8] {
        &self.0[..32]
    }

    /// Extract the ML-KEM-768 public key (bytes 32..1216, inside X-Wing).
    pub fn mlkem_pk(&self) -> &[u8] {
        &self.0[32..constants::XWING_PUBLIC_KEY_SIZE]
    }

    /// Extract the Ed25519 public key (bytes 1216..1248).
    pub fn ed25519_pk(&self) -> &[u8] {
        &self.0[constants::XWING_PUBLIC_KEY_SIZE..constants::XWING_PUBLIC_KEY_SIZE + 32]
    }

    /// Extract the ML-DSA-65 public key (bytes 1248..3200).
    pub fn mldsa_pk(&self) -> &[u8] {
        &self.0[constants::XWING_PUBLIC_KEY_SIZE + 32..]
    }

    /// Extract the X-Wing public key (first 1216 bytes).
    pub fn xwing_pk(&self) -> &[u8] {
        &self.0[..constants::XWING_PUBLIC_KEY_SIZE]
    }

    /// Compute the fingerprint (hex-encoded SHA3-256 of the full public key).
    pub fn fingerprint_hex(&self) -> String {
        sha3_256::fingerprint_hex(&self.0)
    }

    /// Compute the raw fingerprint (32-byte SHA3-256 of the full public key).
    pub fn fingerprint_raw(&self) -> [u8; 32] {
        sha3_256::hash(&self.0)
    }
}

impl IdentitySecretKey {
    /// Return the raw byte representation.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Construct from raw bytes with size validation.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
        // Wrap in Zeroizing so the raw Vec is zeroized on the error path
        // (IdentitySecretKey derives ZeroizeOnDrop, but that only fires on success).
        let mut bytes = Zeroizing::new(bytes);
        if bytes.len() != constants::LO_SECRET_KEY_SIZE {
            return Err(Error::InvalidLength {
                expected: constants::LO_SECRET_KEY_SIZE,
                got: bytes.len(),
            });
        }
        // mem::take moves the Vec out of the Zeroizing wrapper (replacing it
        // with an empty Vec). The Zeroizing wrapper then drops the empty Vec
        // harmlessly, while ownership of the key data transfers to Self.
        Ok(Self(std::mem::take(&mut *bytes)))
    }

    /// Extract the X25519 secret key (first 32 bytes, inside X-Wing).
    pub fn x25519_sk(&self) -> &[u8] {
        &self.0[..32]
    }

    /// Extract the X-Wing secret key (first 2432 bytes): X25519_sk (32) || ML-KEM-768_sk (2400).
    ///
    /// The boundary is `XWING_SECRET_KEY_SIZE = 2432`, a compile-time constant
    /// enforced by `assert_eq!` in `generate_identity`.
    pub fn xwing_sk(&self) -> &[u8] {
        &self.0[..constants::XWING_SECRET_KEY_SIZE]
    }

    /// Extract the Ed25519 secret key (bytes 2432..2464).
    pub fn ed25519_sk(&self) -> &[u8] {
        &self.0[constants::XWING_SECRET_KEY_SIZE..constants::XWING_SECRET_KEY_SIZE + 32]
    }

    /// Extract the ML-DSA-65 seed `ξ` (32 bytes at offset 2464..2496, per FIPS 204 §6.1).
    pub fn mldsa_sk(&self) -> &[u8] {
        &self.0[constants::XWING_SECRET_KEY_SIZE + 32..]
    }
}

impl HybridSignature {
    /// Return the raw byte representation.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Construct from raw bytes with size validation.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
        if bytes.len() != constants::HYBRID_SIGNATURE_SIZE {
            return Err(Error::InvalidLength {
                expected: constants::HYBRID_SIGNATURE_SIZE,
                got: bytes.len(),
            });
        }
        Ok(Self(bytes))
    }

    /// Extract the Ed25519 signature (first 64 bytes).
    pub fn ed25519_sig(&self) -> &[u8] {
        &self.0[..constants::ED25519_SIGNATURE_SIZE]
    }

    /// Extract the ML-DSA-65 signature (bytes 64..3373).
    pub fn mldsa_sig(&self) -> &[u8] {
        &self.0[constants::ED25519_SIGNATURE_SIZE..]
    }
}

/// Return value of [`generate_identity`].
pub struct GeneratedIdentity {
    /// LO composite public key (3200 bytes).
    pub public_key: IdentityPublicKey,
    /// LO composite secret key (2496 bytes). Zeroized on drop.
    pub secret_key: IdentitySecretKey,
    /// Lower-case hex SHA3-256 fingerprint of the public key (64 chars).
    pub fingerprint_hex: String,
}

/// Generate a LO composite identity keypair.
///
/// # Security
///
/// The secret key Vec is wrapped in `Zeroizing` during construction and moved
/// into the `IdentitySecretKey` (which derives `ZeroizeOnDrop`). Intermediate
/// component keys are zeroized by their respective types on drop.
#[must_use = "identity key material must not be discarded"]
pub fn generate_identity() -> Result<GeneratedIdentity> {
    // X-Wing first: its public key occupies the first 1216 bytes of the
    // composite key, matching the layout expected by encapsulate/decapsulate.
    let (xwing_pk, xwing_sk) = xwing::keygen()?;

    // Panic (not error return): size mismatch indicates a build-time constant
    // bug or dependency update that changed type-level sizes — not a runtime
    // input error that a caller could recover from.
    assert_eq!(
        xwing_sk.as_bytes().len(),
        constants::XWING_SECRET_KEY_SIZE,
        "X-Wing secret key size mismatch — update XWING_SECRET_KEY_SIZE in constants.rs"
    );

    // Ed25519: separate signing keypair. Not derived from X-Wing's X25519 key.
    let (ed_vk, ed_sk) = ed25519::keygen();
    assert_eq!(ed_vk.as_bytes().len(), 32, "Ed25519 PK must be 32 bytes");

    let (mldsa_pk, mldsa_sk) = mldsa::keygen()?;

    assert_eq!(
        mldsa_sk.as_bytes().len(),
        32,
        "ML-DSA-65 seed size mismatch — expected 32 bytes"
    );

    // PK layout: X-Wing (1216) || Ed25519 (32) || ML-DSA-65 (1952)
    let mut pk = Vec::with_capacity(xwing_pk.as_bytes().len() + 32 + mldsa_pk.as_bytes().len());
    pk.extend_from_slice(xwing_pk.as_bytes());
    pk.extend_from_slice(ed_vk.as_bytes());
    pk.extend_from_slice(mldsa_pk.as_bytes());

    // SK layout: X-Wing (2432) || Ed25519 (32) || ML-DSA seed (32)
    let mut sk = Zeroizing::new(Vec::with_capacity(
        xwing_sk.as_bytes().len() + 32 + mldsa_sk.as_bytes().len(),
    ));
    sk.extend_from_slice(xwing_sk.as_bytes());
    sk.extend_from_slice(ed_sk.as_bytes());
    sk.extend_from_slice(mldsa_sk.as_bytes());
    // ed_sk is ZeroizeOnDrop — drops automatically when this scope ends.

    let fingerprint = sha3_256::fingerprint_hex(&pk);

    // mem::take moves the Vec out of the Zeroizing wrapper (replacing it with
    // an empty Vec). The Zeroizing wrapper drops the empty Vec harmlessly.
    Ok(GeneratedIdentity {
        public_key: IdentityPublicKey(pk),
        secret_key: IdentitySecretKey(std::mem::take(&mut *sk)),
        fingerprint_hex: fingerprint,
    })
}

/// Sign a message with both Ed25519 and ML-DSA-65 (§3.1).
///
/// Both signatures must verify for the hybrid signature to be valid.
///
/// # Security
///
/// The Ed25519 signing key is reconstructed from the composite SK bytes via
/// `SigningKey::from_bytes`, which copies the 32-byte seed. The `SigningKey`
/// implements `ZeroizeOnDrop` and is cleaned up when it goes out of scope.
/// The ML-DSA seed copy is wrapped in `Zeroizing` and zeroized on drop.
pub fn hybrid_sign(sk: &IdentitySecretKey, message: &[u8]) -> Result<HybridSignature> {
    // Ed25519: sign with the dedicated Ed25519 secret key.
    let ed_sk_bytes: &[u8; 32] = sk.ed25519_sk().try_into().map_err(|_| Error::Internal)?;
    let signing_key = ed25519_dalek::SigningKey::from_bytes(ed_sk_bytes);
    let sig_classical = ed25519::sign(&signing_key, message);
    // signing_key is ZeroizeOnDrop — cleaned up when it drops here.

    // ML-DSA-65: sign with the ML-DSA seed.
    // Wrap .to_vec() in Zeroizing so the intermediate heap copy is zeroized
    // regardless of the panic strategy configured in Cargo.toml.
    let mut sk_bytes = Zeroizing::new(sk.mldsa_sk().to_vec());
    let mldsa_sk = mldsa::SecretKey::from_bytes(std::mem::take(&mut *sk_bytes))?;
    let sig_pqc = mldsa::sign(&mldsa_sk, message)?;
    // Debug-only: ML-DSA signature size is a crate-level constant, verified by
    // runtime asserts in mldsa::sign(). This is a defense-in-depth sanity check.
    debug_assert_eq!(sig_pqc.as_bytes().len(), constants::MLDSA_SIGNATURE_SIZE);

    let mut sig = Vec::with_capacity(constants::ED25519_SIGNATURE_SIZE + sig_pqc.as_bytes().len());
    sig.extend_from_slice(&sig_classical);
    sig.extend_from_slice(sig_pqc.as_bytes());

    Ok(HybridSignature(sig))
}

#[must_use = "signature verification result must be checked"]
/// Verify a hybrid signature (§3.2).
///
/// Both Ed25519 and ML-DSA-65 components must verify.
///
/// # Security
///
/// Both components are computed eagerly into `r1` and `r2`, then combined
/// with a constant-time `Choice` AND — the branch that selects Ok vs Err
/// does not reveal which component failed.
pub fn hybrid_verify(pk: &IdentityPublicKey, message: &[u8], sig: &HybridSignature) -> Result<()> {
    let sig_classical = sig.ed25519_sig();
    let sig_pqc_bytes = sig.mldsa_sig();

    // Ed25519: verify with the dedicated Ed25519 public key.
    let ed_sig: &[u8; 64] = sig_classical.try_into().map_err(|_| Error::Internal)?;
    let ed_pk_bytes: &[u8; 32] = pk.ed25519_pk().try_into().map_err(|_| Error::Internal)?;
    let r1 = ed25519_dalek::VerifyingKey::from_bytes(ed_pk_bytes)
        .map_err(|_| Error::VerificationFailed)
        .and_then(|vk| ed25519::verify(&vk, message, ed_sig));

    let mldsa_pk = mldsa::PublicKey::from_bytes_unchecked(pk.mldsa_pk().to_vec());
    let mldsa_sig = mldsa::Signature::from_bytes_unchecked(sig_pqc_bytes.to_vec());
    let r2 = mldsa::verify(&mldsa_pk, message, &mldsa_sig);

    // Constant-time combination: both results are evaluated eagerly above,
    // and the ok/err decision uses subtle::Choice to avoid leaking which
    // component failed via timing.
    let ok1 = Choice::from(u8::from(r1.is_ok()));
    let ok2 = Choice::from(u8::from(r2.is_ok()));
    if bool::from(ok1 & ok2) {
        Ok(())
    } else {
        Err(Error::VerificationFailed)
    }
}

/// Encapsulate to a LO composite key's X-Wing component (§2.3).
///
/// Extracts the X-Wing public key from the composite key and delegates to
/// `xwing::encapsulate`. Size is guaranteed by `IdentityPublicKey`'s constructor,
/// so `from_bytes_unchecked` is safe.
///
/// # Security
///
/// The returned `SharedSecret` contains raw key material. The caller is
/// responsible for deriving session keys (e.g., via HKDF) and ensuring the
/// shared secret is zeroized when no longer needed.
pub fn encapsulate(pk: &IdentityPublicKey) -> Result<(xwing::Ciphertext, xwing::SharedSecret)> {
    let xwing_pk = xwing::PublicKey::from_bytes_unchecked(pk.xwing_pk().to_vec());
    xwing::encapsulate(&xwing_pk)
}

/// Decapsulate using a LO composite key's X-Wing component (§2.3).
///
/// `ct`: X-Wing ciphertext produced by [`encapsulate`].
///
/// # Security
///
/// The returned `SharedSecret` contains raw key material. The caller is
/// responsible for deriving session keys (e.g., via HKDF) and ensuring the
/// shared secret is zeroized when no longer needed.
pub fn decapsulate(sk: &IdentitySecretKey, ct: &xwing::Ciphertext) -> Result<xwing::SharedSecret> {
    // .to_vec() creates a heap copy of the X-Wing secret key slice;
    // xwing::SecretKey takes ownership and zeroizes the copy on drop.
    let xwing_sk = xwing::SecretKey::from_bytes_unchecked(sk.xwing_sk().to_vec());
    xwing::decapsulate(&xwing_sk, ct)
}

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

    #[test]
    fn generate_identity_sizes() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        assert_eq!(pk.as_bytes().len(), constants::LO_PUBLIC_KEY_SIZE);
        assert_eq!(sk.as_bytes().len(), constants::LO_SECRET_KEY_SIZE);
    }

    #[test]
    fn fingerprint_format() {
        let GeneratedIdentity {
            public_key: pk,
            fingerprint_hex: fp,
            ..
        } = generate_identity().unwrap();
        assert_eq!(fp.len(), 64);
        assert!(
            fp.chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
        );
        // Accessor must match returned fingerprint.
        assert_eq!(pk.fingerprint_hex(), fp);
    }

    #[test]
    fn fingerprint_matches_pk() {
        let GeneratedIdentity {
            public_key: pk,
            fingerprint_hex: fp,
            ..
        } = generate_identity().unwrap();
        let expected = sha3_256::fingerprint_hex(pk.as_bytes());
        assert_eq!(fp, expected);
    }

    #[test]
    fn pk_component_extraction() {
        let GeneratedIdentity { public_key: pk, .. } = generate_identity().unwrap();
        let bytes = pk.as_bytes();
        assert_eq!(pk.x25519_pk(), &bytes[..32]);
        assert_eq!(pk.mlkem_pk(), &bytes[32..constants::XWING_PUBLIC_KEY_SIZE]);
        assert_eq!(
            pk.ed25519_pk(),
            &bytes[constants::XWING_PUBLIC_KEY_SIZE..constants::XWING_PUBLIC_KEY_SIZE + 32]
        );
        assert_eq!(
            pk.mldsa_pk(),
            &bytes[constants::XWING_PUBLIC_KEY_SIZE + 32..]
        );
        // Sizes
        assert_eq!(pk.x25519_pk().len(), 32);
        assert_eq!(pk.mlkem_pk().len(), 1184);
        assert_eq!(pk.ed25519_pk().len(), 32);
        assert_eq!(pk.mldsa_pk().len(), 1952);
    }

    #[test]
    fn xwing_pk_accessor() {
        let GeneratedIdentity { public_key: pk, .. } = generate_identity().unwrap();
        assert_eq!(
            pk.xwing_pk(),
            &pk.as_bytes()[..constants::XWING_PUBLIC_KEY_SIZE]
        );
        assert_eq!(pk.xwing_pk().len(), 1216);
    }

    #[test]
    fn fingerprint_raw_accessor() {
        let GeneratedIdentity { public_key: pk, .. } = generate_identity().unwrap();
        let raw = pk.fingerprint_raw();
        assert_eq!(raw.len(), 32);
        assert_eq!(raw, sha3_256::hash(pk.as_bytes()));
    }

    #[test]
    fn hybrid_sign_verify_round_trip() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        let sig = hybrid_sign(&sk, b"test message").unwrap();
        assert!(hybrid_verify(&pk, b"test message", &sig).is_ok());
    }

    #[test]
    fn hybrid_sign_size() {
        let GeneratedIdentity { secret_key: sk, .. } = generate_identity().unwrap();
        let sig = hybrid_sign(&sk, b"test").unwrap();
        assert_eq!(sig.as_bytes().len(), constants::HYBRID_SIGNATURE_SIZE);
        assert_eq!(sig.as_bytes().len(), 3373);
    }

    #[test]
    fn hybrid_verify_wrong_message() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        let sig = hybrid_sign(&sk, b"message one").unwrap();
        assert!(matches!(
            hybrid_verify(&pk, b"message two", &sig),
            Err(Error::VerificationFailed)
        ));
    }

    #[test]
    fn hybrid_verify_wrong_key() {
        let GeneratedIdentity { secret_key: sk, .. } = generate_identity().unwrap();
        let GeneratedIdentity {
            public_key: pk2, ..
        } = generate_identity().unwrap();
        let sig = hybrid_sign(&sk, b"test").unwrap();
        assert!(matches!(
            hybrid_verify(&pk2, b"test", &sig),
            Err(Error::VerificationFailed)
        ));
    }

    #[test]
    fn hybrid_verify_tampered_ed25519() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        let sig = hybrid_sign(&sk, b"test").unwrap();
        let mut bad = sig.as_bytes().to_vec();
        bad[0] ^= 0xFF; // flip byte in Ed25519 portion
        let bad_sig = HybridSignature::from_bytes(bad).unwrap();
        assert!(matches!(
            hybrid_verify(&pk, b"test", &bad_sig),
            Err(Error::VerificationFailed)
        ));
    }

    #[test]
    fn hybrid_verify_tampered_mldsa() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        let sig = hybrid_sign(&sk, b"test").unwrap();
        let mut bad = sig.as_bytes().to_vec();
        bad[64] ^= 0xFF; // flip byte in ML-DSA portion
        let bad_sig = HybridSignature::from_bytes(bad).unwrap();
        assert!(matches!(
            hybrid_verify(&pk, b"test", &bad_sig),
            Err(Error::VerificationFailed)
        ));
    }

    #[test]
    fn hybrid_verify_valid_ed25519_invalid_mldsa() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        let sig = hybrid_sign(&sk, b"test").unwrap();
        // Keep valid Ed25519, replace ML-DSA with zeros.
        let mut franken = sig.as_bytes()[..64].to_vec();
        franken.extend_from_slice(&vec![0u8; constants::MLDSA_SIGNATURE_SIZE]);
        let bad_sig = HybridSignature::from_bytes(franken).unwrap();
        assert!(matches!(
            hybrid_verify(&pk, b"test", &bad_sig),
            Err(Error::VerificationFailed)
        ));
    }

    #[test]
    fn hybrid_verify_invalid_ed25519_valid_mldsa() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        let sig = hybrid_sign(&sk, b"test").unwrap();
        // Replace Ed25519 with zeros, keep valid ML-DSA.
        let mut franken = vec![0u8; 64];
        franken.extend_from_slice(&sig.as_bytes()[64..]);
        let bad_sig = HybridSignature::from_bytes(franken).unwrap();
        assert!(matches!(
            hybrid_verify(&pk, b"test", &bad_sig),
            Err(Error::VerificationFailed)
        ));
    }

    #[test]
    fn encapsulate_decapsulate() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        let (ct, ss_enc) = encapsulate(&pk).unwrap();
        let ss_dec = decapsulate(&sk, &ct).unwrap();
        assert_eq!(ss_enc.as_bytes(), ss_dec.as_bytes());
    }

    // Split into 3 separate tests: under panic="abort" (workspace-wide), a failure
    // in the first assertion terminates the process, making subsequent assertions
    // unreachable and untested.
    #[test]
    fn identity_public_key_from_bytes_wrong_size() {
        assert!(matches!(
            IdentityPublicKey::from_bytes(vec![0u8; 100]),
            Err(Error::InvalidLength {
                expected: 3200,
                got: 100
            })
        ));
    }

    #[test]
    fn identity_secret_key_from_bytes_wrong_size() {
        assert!(matches!(
            IdentitySecretKey::from_bytes(vec![0u8; 100]),
            Err(Error::InvalidLength {
                expected: 2496,
                got: 100
            })
        ));
    }

    #[test]
    fn hybrid_signature_from_bytes_wrong_size() {
        assert!(matches!(
            HybridSignature::from_bytes(vec![0u8; 100]),
            Err(Error::InvalidLength {
                expected: 3373,
                got: 100
            })
        ));
    }

    #[test]
    fn hybrid_verify_cross_spliced_signatures_rejected() {
        let GeneratedIdentity {
            public_key: pk,
            secret_key: sk,
            ..
        } = generate_identity().unwrap();
        let sig_a = hybrid_sign(&sk, b"message A").unwrap();
        let sig_b = hybrid_sign(&sk, b"message B").unwrap();
        // Cross-splice: Ed25519 from sig_a (valid for "message A") with
        // ML-DSA from sig_b (valid for "message B"). A short-circuit bug
        // that checks only one component would accept one of the messages.
        let mut spliced = sig_a.as_bytes()[..constants::ED25519_SIGNATURE_SIZE].to_vec();
        spliced.extend_from_slice(&sig_b.as_bytes()[constants::ED25519_SIGNATURE_SIZE..]);
        let franken_sig = HybridSignature::from_bytes(spliced).unwrap();
        assert!(matches!(
            hybrid_verify(&pk, b"message A", &franken_sig),
            Err(Error::VerificationFailed)
        ));
        assert!(matches!(
            hybrid_verify(&pk, b"message B", &franken_sig),
            Err(Error::VerificationFailed)
        ));
    }

    #[test]
    fn hybrid_sign_nondeterministic() {
        // ML-DSA uses hedged signing — two signatures over the same message
        // must produce different ML-DSA components (different randomness).
        // Ed25519 is deterministic (RFC 8032), so its component is identical.
        let GeneratedIdentity { secret_key: sk, .. } = generate_identity().unwrap();
        let msg = b"same message";
        let sig1 = hybrid_sign(&sk, msg).unwrap();
        let sig2 = hybrid_sign(&sk, msg).unwrap();
        // Ed25519 component (first 64 bytes) is deterministic.
        assert_eq!(&sig1.as_bytes()[..64], &sig2.as_bytes()[..64]);
        // ML-DSA component (bytes 64..) must differ (hedged signing).
        assert_ne!(&sig1.as_bytes()[64..], &sig2.as_bytes()[64..]);
    }
}