bao_crypto 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
use crate::CryptoError;
use bun_boringssl_sys::*;
use core::ffi::c_void;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcCurve {
    P256,
    P384,
    X25519,
}

pub fn parse_curve(name: &str) -> Result<EcCurve, CryptoError> {
    match name.to_lowercase().as_str() {
        "p256" | "prime256v1" | "secp256r1" => Ok(EcCurve::P256),
        "p384" | "secp384r1" => Ok(EcCurve::P384),
        "x25519" => Ok(EcCurve::X25519),
        _ => Err(CryptoError::InvalidCurve(format!(
            "Unsupported curve: {}",
            name
        ))),
    }
}

fn curve_nid(curve: EcCurve) -> core::ffi::c_int {
    match curve {
        EcCurve::P256 => NID_X9_62_prime256v1,
        EcCurve::P384 => NID_secp384r1,
        EcCurve::X25519 => NID_X25519,
    }
}

fn curve_priv_len(curve: EcCurve) -> usize {
    match curve {
        EcCurve::P256 => 32,
        EcCurve::P384 => 48,
        EcCurve::X25519 => 32,
    }
}

struct EcKeyGuard(*mut EC_KEY);
impl Drop for EcKeyGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { EC_KEY_free(self.0) };
        }
    }
}

struct BnCtxGuard(*mut BN_CTX);
impl Drop for BnCtxGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { BN_CTX_free(self.0) };
        }
    }
}

struct EcPointGuard(*mut EC_POINT);
impl Drop for EcPointGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { EC_POINT_free(self.0) };
        }
    }
}

struct BnGuard(*mut BIGNUM);
impl Drop for BnGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { BN_free(self.0) };
        }
    }
}

struct PkeyGuard(*mut EVP_PKEY);
impl Drop for PkeyGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { EVP_PKEY_free(self.0) };
        }
    }
}

struct PkeyCtxGuard(*mut EVP_PKEY_CTX);
impl Drop for PkeyCtxGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { EVP_PKEY_CTX_free(self.0) };
        }
    }
}

fn ec_extract_private_bytes(key: *mut EC_KEY, priv_len: usize) -> Result<Vec<u8>, CryptoError> {
    let priv_bn = unsafe { EC_KEY_get0_private_key(key) };
    if priv_bn.is_null() {
        return Err(CryptoError::KeyGenerationFailed(
            "EC_KEY private key null".into(),
        ));
    }
    let num_bits = unsafe { BN_num_bits(priv_bn) } as usize;
    let bn_len = (num_bits + 7) / 8;
    let mut priv_buf = vec![0u8; priv_len];
    let mut bn_raw = vec![0u8; bn_len];
    unsafe { BN_bn2bin(priv_bn, bn_raw.as_mut_ptr()) };
    let offset = priv_len.saturating_sub(bn_len);
    priv_buf[offset..].copy_from_slice(&bn_raw);
    Ok(priv_buf)
}

fn ec_extract_public_bytes(key: *mut EC_KEY, ctx: *mut BN_CTX) -> Result<Vec<u8>, CryptoError> {
    let pub_point = unsafe { EC_KEY_get0_public_key(key) };
    let group = unsafe { EC_KEY_get0_group(key) };
    if pub_point.is_null() || group.is_null() {
        return Err(CryptoError::KeyGenerationFailed(
            "EC_KEY public key/group null".into(),
        ));
    }
    let pub_len = unsafe {
        EC_POINT_point2oct(
            group,
            pub_point,
            POINT_CONVERSION_UNCOMPRESSED,
            std::ptr::null_mut(),
            0,
            ctx,
        )
    };
    if pub_len == 0 {
        return Err(CryptoError::KeyGenerationFailed(
            "EC_POINT_point2oct size query failed".into(),
        ));
    }
    let mut pub_buf = vec![0u8; pub_len];
    let written = unsafe {
        EC_POINT_point2oct(
            group,
            pub_point,
            POINT_CONVERSION_UNCOMPRESSED,
            pub_buf.as_mut_ptr(),
            pub_len,
            ctx,
        )
    };
    if written == 0 {
        return Err(CryptoError::KeyGenerationFailed(
            "EC_POINT_point2oct failed".into(),
        ));
    }
    Ok(pub_buf)
}

fn boringssl_ec_generate(curve: EcCurve) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
    let nid = curve_nid(curve);
    let priv_len = curve_priv_len(curve);

    let key = EcKeyGuard(unsafe { EC_KEY_new_by_curve_name(nid) });
    if key.0.is_null() {
        return Err(CryptoError::KeyGenerationFailed(
            "EC_KEY_new_by_curve_name failed".into(),
        ));
    }
    if unsafe { EC_KEY_generate_key(key.0) } != 1 {
        return Err(CryptoError::KeyGenerationFailed(
            "EC_KEY_generate_key failed".into(),
        ));
    }

    let ctx = BnCtxGuard(unsafe { BN_CTX_new() });
    if ctx.0.is_null() {
        return Err(CryptoError::KeyGenerationFailed("BN_CTX_new failed".into()));
    }

    let priv_bytes = ec_extract_private_bytes(key.0, priv_len)?;
    let pub_bytes = ec_extract_public_bytes(key.0, ctx.0)?;
    Ok((priv_bytes, pub_bytes))
}

fn boringssl_ec_reconstruct(curve: EcCurve, private_bytes: &[u8]) -> Result<Vec<u8>, CryptoError> {
    let nid = curve_nid(curve);
    let priv_len = curve_priv_len(curve);

    if private_bytes.len() != priv_len {
        return Err(CryptoError::InvalidKeyLength {
            expected: priv_len,
            got: private_bytes.len(),
        });
    }

    let key = EcKeyGuard(unsafe { EC_KEY_new_by_curve_name(nid) });
    if key.0.is_null() {
        return Err(CryptoError::InvalidKey(
            "EC_KEY_new_by_curve_name failed".into(),
        ));
    }

    let priv_bn = BnGuard(unsafe {
        BN_bin2bn(
            private_bytes.as_ptr(),
            private_bytes.len(),
            std::ptr::null_mut(),
        )
    });
    if priv_bn.0.is_null() {
        return Err(CryptoError::InvalidKey("BN_bin2bn failed".into()));
    }

    if unsafe { EC_KEY_set_private_key(key.0, priv_bn.0) } != 1 {
        return Err(CryptoError::InvalidKey(
            "EC_KEY_set_private_key failed".into(),
        ));
    }

    let group = unsafe { EC_KEY_get0_group(key.0) };
    let pub_point = EcPointGuard(unsafe { EC_POINT_new(group) });
    if pub_point.0.is_null() {
        return Err(CryptoError::InvalidKey("EC_POINT_new failed".into()));
    }

    let ctx = BnCtxGuard(unsafe { BN_CTX_new() });
    if ctx.0.is_null() {
        return Err(CryptoError::InvalidKey("BN_CTX_new failed".into()));
    }

    if unsafe {
        EC_POINT_mul(
            group,
            pub_point.0,
            priv_bn.0,
            std::ptr::null(),
            std::ptr::null(),
            ctx.0,
        )
    } != 1
    {
        return Err(CryptoError::InvalidKey("EC_POINT_mul failed".into()));
    }

    if unsafe { EC_KEY_set_public_key(key.0, pub_point.0) } != 1 {
        return Err(CryptoError::InvalidKey(
            "EC_KEY_set_public_key failed".into(),
        ));
    }

    ec_extract_public_bytes(key.0, ctx.0)
}

/// Generate X25519 keypair using BoringSSL EVP_PKEY API.
///
/// BoringSSL does not support X25519 via EVP_PKEY_CTX_new_id keygen; generate a
/// 32-byte seed, lift it into an EVP_PKEY via EVP_PKEY_from_raw_private_key,
/// then extract the raw private/public bytes.
fn x25519_generate() -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
    let mut seed = [0u8; 32];
    crate::random::rand_bytes(&mut seed)?;
    unsafe {
        let pkey = PkeyGuard(EVP_PKEY_from_raw_private_key(
            EVP_pkey_x25519(),
            seed.as_ptr(),
            seed.len(),
        ));
        if pkey.0.is_null() {
            return Err(CryptoError::KeyGenerationFailed(
                "EVP_PKEY_from_raw_private_key (x25519) failed".into(),
            ));
        }

        let mut priv_len: usize = 0;
        if EVP_PKEY_get_raw_private_key(pkey.0, std::ptr::null_mut(), &mut priv_len) != 1 {
            return Err(CryptoError::KeyGenerationFailed(
                "EVP_PKEY_get_raw_private_key size query failed".into(),
            ));
        }
        let mut priv_bytes = vec![0u8; priv_len];
        if EVP_PKEY_get_raw_private_key(pkey.0, priv_bytes.as_mut_ptr(), &mut priv_len) != 1 {
            return Err(CryptoError::KeyGenerationFailed(
                "EVP_PKEY_get_raw_private_key failed".into(),
            ));
        }

        let mut pub_len: usize = 0;
        if EVP_PKEY_get_raw_public_key(pkey.0, std::ptr::null_mut(), &mut pub_len) != 1 {
            return Err(CryptoError::KeyGenerationFailed(
                "EVP_PKEY_get_raw_public_key size query failed".into(),
            ));
        }
        let mut pub_bytes = vec![0u8; pub_len];
        if EVP_PKEY_get_raw_public_key(pkey.0, pub_bytes.as_mut_ptr(), &mut pub_len) != 1 {
            return Err(CryptoError::KeyGenerationFailed(
                "EVP_PKEY_get_raw_public_key failed".into(),
            ));
        }

        Ok((priv_bytes, pub_bytes))
    }
}

/// Reconstruct X25519 public key from private key using BoringSSL EVP_PKEY API.
fn x25519_reconstruct(private_bytes: &[u8]) -> Result<Vec<u8>, CryptoError> {
    if private_bytes.len() != 32 {
        return Err(CryptoError::InvalidKeyLength {
            expected: 32,
            got: private_bytes.len(),
        });
    }
    unsafe {
        let pkey = PkeyGuard(EVP_PKEY_from_raw_private_key(
            EVP_pkey_x25519(),
            private_bytes.as_ptr(),
            private_bytes.len(),
        ));
        if pkey.0.is_null() {
            return Err(CryptoError::InvalidKey(
                "EVP_PKEY_from_raw_private_key failed".into(),
            ));
        }

        let mut pub_len: usize = 0;
        if EVP_PKEY_get_raw_public_key(pkey.0, std::ptr::null_mut(), &mut pub_len) != 1 {
            return Err(CryptoError::InvalidKey(
                "EVP_PKEY_get_raw_public_key size query failed".into(),
            ));
        }
        let mut pub_bytes = vec![0u8; pub_len];
        if EVP_PKEY_get_raw_public_key(pkey.0, pub_bytes.as_mut_ptr(), &mut pub_len) != 1 {
            return Err(CryptoError::InvalidKey(
                "EVP_PKEY_get_raw_public_key failed".into(),
            ));
        }

        Ok(pub_bytes)
    }
}

/// Compute X25519 shared secret using BoringSSL EVP_PKEY_derive API.
fn x25519_derive(private_bytes: &[u8], peer_public: &[u8]) -> Result<Vec<u8>, CryptoError> {
    if private_bytes.len() != 32 {
        return Err(CryptoError::InvalidKeyLength {
            expected: 32,
            got: private_bytes.len(),
        });
    }
    if peer_public.len() != 32 {
        return Err(CryptoError::InvalidKeyLength {
            expected: 32,
            got: peer_public.len(),
        });
    }
    unsafe {
        let our_pkey = PkeyGuard(EVP_PKEY_from_raw_private_key(
            EVP_pkey_x25519(),
            private_bytes.as_ptr(),
            private_bytes.len(),
        ));
        if our_pkey.0.is_null() {
            return Err(CryptoError::SharedSecretFailed(
                "EVP_PKEY_from_raw_private_key failed".into(),
            ));
        }

        let peer_pkey = PkeyGuard(EVP_PKEY_from_raw_public_key(
            EVP_pkey_x25519(),
            peer_public.as_ptr(),
            peer_public.len(),
        ));
        if peer_pkey.0.is_null() {
            return Err(CryptoError::InvalidKey(
                "EVP_PKEY_from_raw_public_key for peer failed".into(),
            ));
        }

        let ctx = PkeyCtxGuard(EVP_PKEY_CTX_new(our_pkey.0, std::ptr::null_mut()));
        if ctx.0.is_null() {
            return Err(CryptoError::SharedSecretFailed(
                "EVP_PKEY_CTX_new failed".into(),
            ));
        }

        if EVP_PKEY_derive_init(ctx.0) != 1 {
            return Err(CryptoError::SharedSecretFailed(
                "EVP_PKEY_derive_init failed".into(),
            ));
        }
        if EVP_PKEY_derive_set_peer(ctx.0, peer_pkey.0) != 1 {
            return Err(CryptoError::SharedSecretFailed(
                "EVP_PKEY_derive_set_peer failed".into(),
            ));
        }

        let mut key_len: usize = 0;
        if EVP_PKEY_derive(ctx.0, std::ptr::null_mut(), &mut key_len) != 1 {
            return Err(CryptoError::SharedSecretFailed(
                "EVP_PKEY_derive size query failed".into(),
            ));
        }

        let mut shared = vec![0u8; key_len];
        if EVP_PKEY_derive(ctx.0, shared.as_mut_ptr(), &mut key_len) != 1 {
            return Err(CryptoError::SharedSecretFailed(
                "EVP_PKEY_derive failed".into(),
            ));
        }

        Ok(shared)
    }
}

pub struct EcdhKeyPair {
    curve: EcCurve,
    private_bytes: Vec<u8>,
    public_bytes: Vec<u8>,
}

impl EcdhKeyPair {
    pub fn generate(curve: EcCurve) -> Result<EcdhKeyPair, CryptoError> {
        let (priv_bytes, pub_bytes) = match curve {
            EcCurve::P256 | EcCurve::P384 => boringssl_ec_generate(curve)?,
            EcCurve::X25519 => x25519_generate()?,
        };
        Ok(EcdhKeyPair {
            curve,
            private_bytes: priv_bytes,
            public_bytes: pub_bytes,
        })
    }

    pub fn reconstruct_keypair(
        curve: EcCurve,
        private_bytes: &[u8],
    ) -> Result<EcdhKeyPair, CryptoError> {
        let pub_bytes = match curve {
            EcCurve::P256 | EcCurve::P384 => boringssl_ec_reconstruct(curve, private_bytes)?,
            EcCurve::X25519 => x25519_reconstruct(private_bytes)?,
        };
        Ok(EcdhKeyPair {
            curve,
            private_bytes: private_bytes.to_vec(),
            public_bytes: pub_bytes,
        })
    }

    pub fn compute_shared_secret(&self, other_pub: &[u8]) -> Result<Vec<u8>, CryptoError> {
        match self.curve {
            EcCurve::P256 | EcCurve::P384 => {
                let nid = curve_nid(self.curve);

                let key = EcKeyGuard(unsafe { EC_KEY_new_by_curve_name(nid) });
                if key.0.is_null() {
                    return Err(CryptoError::SharedSecretFailed(
                        "EC_KEY_new_by_curve_name failed".into(),
                    ));
                }

                let priv_bn = BnGuard(unsafe {
                    BN_bin2bn(
                        self.private_bytes.as_ptr(),
                        self.private_bytes.len(),
                        std::ptr::null_mut(),
                    )
                });
                if priv_bn.0.is_null() {
                    return Err(CryptoError::SharedSecretFailed("BN_bin2bn failed".into()));
                }
                if unsafe { EC_KEY_set_private_key(key.0, priv_bn.0) } != 1 {
                    return Err(CryptoError::SharedSecretFailed(
                        "EC_KEY_set_private_key failed".into(),
                    ));
                }

                let group = unsafe { EC_KEY_get0_group(key.0) };
                let pub_point = EcPointGuard(unsafe { EC_POINT_new(group) });
                if pub_point.0.is_null() {
                    return Err(CryptoError::SharedSecretFailed(
                        "EC_POINT_new failed".into(),
                    ));
                }

                let ctx = BnCtxGuard(unsafe { BN_CTX_new() });
                if ctx.0.is_null() {
                    return Err(CryptoError::SharedSecretFailed("BN_CTX_new failed".into()));
                }

                if unsafe {
                    EC_POINT_mul(
                        group,
                        pub_point.0,
                        priv_bn.0,
                        std::ptr::null(),
                        std::ptr::null(),
                        ctx.0,
                    )
                } != 1
                {
                    return Err(CryptoError::SharedSecretFailed(
                        "EC_POINT_mul failed".into(),
                    ));
                }
                if unsafe { EC_KEY_set_public_key(key.0, pub_point.0) } != 1 {
                    return Err(CryptoError::SharedSecretFailed(
                        "EC_KEY_set_public_key failed".into(),
                    ));
                }

                let peer_point = EcPointGuard(unsafe { EC_POINT_new(group) });
                if peer_point.0.is_null() {
                    return Err(CryptoError::SharedSecretFailed(
                        "EC_POINT_new for peer failed".into(),
                    ));
                }
                if unsafe {
                    EC_POINT_oct2point(
                        group,
                        peer_point.0,
                        other_pub.as_ptr(),
                        other_pub.len(),
                        ctx.0,
                    )
                } != 1
                {
                    return Err(CryptoError::InvalidKey(
                        "Failed to parse peer public key".into(),
                    ));
                }

                let secret_len = curve_priv_len(self.curve);
                let mut shared = vec![0u8; secret_len];
                let ret = unsafe {
                    ECDH_compute_key(
                        shared.as_mut_ptr() as *mut c_void,
                        secret_len,
                        peer_point.0,
                        key.0,
                        None,
                    )
                };
                if ret <= 0 {
                    return Err(CryptoError::SharedSecretFailed(
                        "ECDH_compute_key failed".into(),
                    ));
                }
                shared.truncate(ret as usize);
                Ok(shared)
            }
            EcCurve::X25519 => x25519_derive(&self.private_bytes, other_pub),
        }
    }

    pub fn public_key_bytes(&self) -> Vec<u8> {
        self.public_bytes.clone()
    }

    pub fn private_key_bytes(&self) -> Vec<u8> {
        self.private_bytes.clone()
    }

    pub fn curve(&self) -> EcCurve {
        self.curve
    }
}

#[cfg(test)]
mod tests {
    //! Real ECDH round-trip tests (BCE regression class for createECDH).
    //! Prove that two independently-generated keypairs on the same curve
    //! derive bit-identical shared secrets via compute_shared_secret — the
    //! actual ECDH contract. Anything weaker (typeof check, empty-object
    //! stub) would not catch a broken or stubbed crypto_create_ecdh.

    use super::*;

    #[test]
    fn ecdh_p256_shared_secret_roundtrip() {
        let alice = EcdhKeyPair::generate(EcCurve::P256).expect("alice P256 generate");
        let bob = EcdhKeyPair::generate(EcCurve::P256).expect("bob P256 generate");
        let alice_pub = alice.public_key_bytes();
        let bob_pub = bob.public_key_bytes();
        assert!(!alice_pub.is_empty(), "P256 public key must be non-empty");
        assert!(!bob_pub.is_empty(), "P256 public key must be non-empty");
        let s_a = alice
            .compute_shared_secret(&bob_pub)
            .expect("alice computeSecret");
        let s_b = bob
            .compute_shared_secret(&alice_pub)
            .expect("bob computeSecret");
        assert_eq!(s_a.len(), 32, "P256 shared secret must be 32 bytes");
        assert_eq!(s_a.len(), s_b.len());
        assert_eq!(s_a, s_b, "P256 shared secrets must be bit-identical");
    }

    #[test]
    fn ecdh_p384_shared_secret_roundtrip() {
        let alice = EcdhKeyPair::generate(EcCurve::P384).expect("alice P384 generate");
        let bob = EcdhKeyPair::generate(EcCurve::P384).expect("bob P384 generate");
        let alice_pub = alice.public_key_bytes();
        let bob_pub = bob.public_key_bytes();
        assert!(!alice_pub.is_empty());
        let s_a = alice
            .compute_shared_secret(&bob_pub)
            .expect("alice P384 computeSecret");
        let s_b = bob
            .compute_shared_secret(&alice_pub)
            .expect("bob P384 computeSecret");
        assert_eq!(s_a.len(), 48, "P384 shared secret must be 48 bytes");
        assert_eq!(s_a, s_b, "P384 shared secrets must be bit-identical");
    }

    #[test]
    fn ecdh_x25519_shared_secret_roundtrip() {
        let alice = EcdhKeyPair::generate(EcCurve::X25519).expect("alice X25519 generate");
        let bob = EcdhKeyPair::generate(EcCurve::X25519).expect("bob X25519 generate");
        let alice_pub = alice.public_key_bytes();
        let bob_pub = bob.public_key_bytes();
        assert_eq!(alice_pub.len(), 32, "X25519 public key must be 32 bytes");
        assert_eq!(bob_pub.len(), 32);
        let s_a = alice
            .compute_shared_secret(&bob_pub)
            .expect("alice X25519 computeSecret");
        let s_b = bob
            .compute_shared_secret(&alice_pub)
            .expect("bob X25519 computeSecret");
        assert_eq!(s_a.len(), 32, "X25519 shared secret must be 32 bytes");
        assert_eq!(s_a, s_b, "X25519 shared secrets must be bit-identical");
    }

    #[test]
    fn ecdh_public_keys_differ_per_party() {
        // Two keypairs on the same curve must produce distinct public keys
        // (else the cipher would be degenerate). This catches a stub that
        // returns a constant buffer.
        let a = EcdhKeyPair::generate(EcCurve::P256).expect("a P256");
        let b = EcdhKeyPair::generate(EcCurve::P256).expect("b P256");
        assert_ne!(
            a.public_key_bytes(),
            b.public_key_bytes(),
            "distinct keypairs must have distinct public keys"
        );
        assert_ne!(
            a.private_key_bytes(),
            b.private_key_bytes(),
            "distinct keypairs must have distinct private keys"
        );
    }

    #[test]
    fn ecdh_curve_rejects_unknown_name() {
        assert!(parse_curve("not-a-curve").is_err());
        assert!(
            parse_curve("P-256").is_err(),
            "Node-style P-256 not supported"
        );
        assert!(parse_curve("prime256v1").is_ok());
        assert!(parse_curve("secp256r1").is_ok());
        assert!(parse_curve("p256").is_ok());
    }

    #[test]
    fn ecdh_cross_curve_secret_does_not_match() {
        // Sanity: a P256 peer public key fed to an X25519 keypair must NOT
        // silently produce a secret (it must error — different curves).
        let alice_p256 = EcdhKeyPair::generate(EcCurve::P256).expect("alice P256");
        let bob_x = EcdhKeyPair::generate(EcCurve::X25519).expect("bob X25519");
        let result = bob_x.compute_shared_secret(&alice_p256.public_key_bytes());
        assert!(
            result.is_err(),
            "cross-curve computeSecret must fail, not silently succeed"
        );
    }
}