auths-crypto 0.1.2

Cryptographic primitives for Auths: KERI key parsing and DID:key encoding
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Curve-agnostic key operations.
//!
//! Single source of truth for parsing, signing, and public key derivation
//! across Ed25519 and P-256. The [`TypedSeed`] enum carries the curve with
//! the key material — callers never need to guess which curve a key uses.

// INVARIANT: sanctioned crypto boundary — the only legitimate caller of ring
// Ed25519 APIs inside the workspace. Every other crate must route through
// auths_crypto::sign / public_key / TypedSignerKey. Permanent allow; do NOT
// remove in fn-114.40.
#![allow(clippy::disallowed_methods)]

use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::provider::{CryptoError, CurveType, SecureSeed};

/// A private key seed that knows its curve.
///
/// Adding a new curve means adding a variant here. The compiler then errors
/// on every `match` that doesn't handle it — no grep needed.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub enum TypedSeed {
    /// Ed25519 private key seed (32 bytes).
    Ed25519(#[zeroize] [u8; 32]),
    /// P-256 private scalar (32 bytes).
    P256(#[zeroize] [u8; 32]),
}

impl TypedSeed {
    /// Returns the curve this seed belongs to.
    pub fn curve(&self) -> CurveType {
        match self {
            Self::Ed25519(_) => CurveType::Ed25519,
            Self::P256(_) => CurveType::P256,
        }
    }

    /// Returns the raw seed bytes (32 bytes for both Ed25519 and P-256).
    pub fn as_bytes(&self) -> &[u8; 32] {
        match self {
            Self::Ed25519(b) | Self::P256(b) => b,
        }
    }

    /// Convert to a legacy `SecureSeed` (loses curve info — use sparingly).
    pub fn to_secure_seed(&self) -> SecureSeed {
        SecureSeed::new(*self.as_bytes())
    }
}

impl std::fmt::Debug for TypedSeed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Ed25519(_) => f.write_str("TypedSeed::Ed25519([REDACTED])"),
            Self::P256(_) => f.write_str("TypedSeed::P256([REDACTED])"),
        }
    }
}

/// Parsed key material with curve baked in.
#[derive(Debug)]
pub struct ParsedKey {
    /// The private key seed, typed to its curve.
    pub seed: TypedSeed,
    /// The public key bytes (32 for Ed25519, 33 for P-256 compressed).
    pub public_key: Vec<u8>,
}

/// Parse any supported PKCS8 DER (or raw seed) to extract seed + public key + curve.
///
/// This is the single source of truth for "what curve is this key?"
/// The curve is detected here and carried in `TypedSeed` — never re-guessed.
///
/// Usage:
/// ```ignore
/// let parsed = parse_key_material(&pkcs8_bytes)?;
/// let sig = sign(&parsed.seed, message)?;
/// ```
pub fn parse_key_material(bytes: &[u8]) -> Result<ParsedKey, CryptoError> {
    // Try Ed25519 first (most common, multiple PKCS8 formats)
    if let Ok((seed, maybe_pk)) = crate::key_material::parse_ed25519_key_material(bytes) {
        let public_key = match maybe_pk {
            Some(pk) => pk.to_vec(),
            None => {
                // Derive from seed via ring
                #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
                {
                    use ring::signature::{Ed25519KeyPair, KeyPair};
                    let kp = Ed25519KeyPair::from_seed_unchecked(seed.as_bytes()).map_err(|e| {
                        CryptoError::OperationFailed(format!("Ed25519 pubkey: {e}"))
                    })?;
                    kp.public_key().as_ref().to_vec()
                }
                #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
                {
                    return Err(CryptoError::UnsupportedTarget);
                }
            }
        };
        return Ok(ParsedKey {
            seed: TypedSeed::Ed25519(*seed.as_bytes()),
            public_key,
        });
    }

    // Try P-256 PKCS8
    #[cfg(feature = "native")]
    {
        use p256::pkcs8::DecodePrivateKey;
        if let Ok(sk) = p256::ecdsa::SigningKey::from_pkcs8_der(bytes) {
            let vk = p256::ecdsa::VerifyingKey::from(&sk);
            let compressed = vk.to_encoded_point(true);
            let mut scalar = [0u8; 32];
            scalar.copy_from_slice(&sk.to_bytes());
            return Ok(ParsedKey {
                seed: TypedSeed::P256(scalar),
                public_key: compressed.as_bytes().to_vec(),
            });
        }
    }

    Err(CryptoError::InvalidPrivateKey(format!(
        "Unrecognized key format ({} bytes)",
        bytes.len()
    )))
}

// Compile-time provider selection for the sync dispatchers below:
// - `--features fips` → `AwsLcProvider` (AWS-LC-FIPS 140-3)
// - `--features cnsa` → `CnsaProvider` (rejects P-256; forwards Ed25519/P-384)
// - default → `RingCryptoProvider`
// One cfg block, one import, everything downstream is provider-agnostic.
#[cfg(all(feature = "fips", not(target_arch = "wasm32")))]
use crate::aws_lc_provider::AwsLcProvider as SyncProvider;
#[cfg(all(feature = "cnsa", not(feature = "fips"), not(target_arch = "wasm32")))]
use crate::cnsa_provider::CnsaProvider as SyncProvider;
#[cfg(all(
    feature = "native",
    not(feature = "fips"),
    not(feature = "cnsa"),
    not(target_arch = "wasm32")
))]
use crate::ring_provider::RingCryptoProvider as SyncProvider;

/// Sign a message using the seed's curve. No curve parameter needed.
///
/// This is the sync curve-agnostic dispatcher. Each arm delegates to a
/// `SyncProvider` inherent method — the single swap point when FIPS
/// (fn-128.T3) or CNSA (fn-128.T4) replaces the default provider. Domain code
/// never matches on curve; this function does it once.
///
/// Usage:
/// ```ignore
/// let parsed = parse_key_material(&pkcs8)?;
/// let sig = sign(&parsed.seed, b"hello")?;
/// ```
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
pub fn sign(seed: &TypedSeed, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
    match seed {
        TypedSeed::Ed25519(s) => SyncProvider::ed25519_sign(s, message),
        TypedSeed::P256(s) => SyncProvider::p256_sign(s, message),
    }
}

/// Derive the public key from the seed's curve.
///
/// Returns 32 bytes for Ed25519, 33 bytes compressed SEC1 for P-256.
/// Same dispatcher shape as [`sign`] — one `match`, each arm a cfg-swappable
/// provider inherent method.
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
pub fn public_key(seed: &TypedSeed) -> Result<Vec<u8>, CryptoError> {
    match seed {
        TypedSeed::Ed25519(s) => Ok(SyncProvider::ed25519_public_key(s)?.to_vec()),
        TypedSeed::P256(s) => SyncProvider::p256_public_key_from_seed(s),
    }
}

/// Parsed signing key with curve carried explicitly — the authoritative owner
/// of a private-key + curve pair across sign / verify / PKCS8 export / CESR
/// encoding flows.
///
/// `TypedSignerKey` replaces every `(SecureSeed, CurveType)` pair, every
/// `[u8; 32]` seed passed alongside an implicit "assume Ed25519", and every
/// replaces the historic `(SecureSeed, CurveType)` pair pattern throughout the workspace.
///
/// Constructed from PKCS8 DER bytes via [`TypedSignerKey::from_pkcs8`], which
/// delegates to [`parse_key_material`] for curve detection.
///
/// Args on construction:
/// * `bytes`: PKCS8 DER (Ed25519 v1/v2 or P-256).
///
/// Usage:
/// ```ignore
/// let s = TypedSignerKey::from_pkcs8(&pkcs8)?;
/// let sig = s.sign(b"payload bytes")?;
/// let cesr = s.cesr_encoded_pubkey(); // "D..." for Ed25519, "1AAJ..." for P-256 (transferable verkey)
/// let pkcs8 = s.to_pkcs8()?;          // curve-aware encode (replaces build_ed25519_pkcs8_v2)
/// ```
#[derive(Debug)]
pub struct TypedSignerKey {
    /// The private seed, tagged with its curve. Private — access via [`TypedSignerKey::curve`]
    /// or the typed sign/to_pkcs8 methods. Prevents callers from grabbing raw bytes and
    /// re-introducing curve-less dispatch.
    seed: TypedSeed,
    /// The public key bytes (32 Ed25519, 33 P-256 compressed). Private — access via
    /// [`TypedSignerKey::public_key`].
    public_key: Vec<u8>,
}

// Marker impl — the inner `TypedSeed` is itself `ZeroizeOnDrop`, so dropping
// a `TypedSignerKey` transitively zeroes the private key. The public key
// field intentionally does not need to be scrubbed. This empty impl formally
// declares the invariant so fn-128.T5's `Secret` trait bound is satisfiable.
impl zeroize::ZeroizeOnDrop for TypedSignerKey {}

impl TypedSignerKey {
    /// Parse a PKCS8 DER blob into a curve-tagged signer.
    pub fn from_pkcs8(bytes: &[u8]) -> Result<Self, CryptoError> {
        let parsed = parse_key_material(bytes)?;
        Ok(Self {
            seed: parsed.seed,
            public_key: parsed.public_key,
        })
    }

    /// Construct directly from a typed seed and its derived public key.
    /// Caller must ensure the public key matches the seed's curve; if the
    /// lengths disagree with the curve, returns `InvalidPrivateKey`.
    pub fn from_parts(seed: TypedSeed, public_key: Vec<u8>) -> Result<Self, CryptoError> {
        let expected = seed.curve().public_key_len();
        if public_key.len() != expected {
            return Err(CryptoError::InvalidPrivateKey(format!(
                "public key length {} does not match {} expected {} bytes",
                public_key.len(),
                seed.curve(),
                expected
            )));
        }
        Ok(Self { seed, public_key })
    }

    /// Derive from a typed seed by recomputing the public key.
    #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
    pub fn from_seed(seed: TypedSeed) -> Result<Self, CryptoError> {
        let pk = public_key(&seed)?;
        Ok(Self {
            seed,
            public_key: pk,
        })
    }

    /// CESR-encoded public key string.
    ///
    /// Uses the spec-correct derivation codes:
    /// - `D` + base64url(32 bytes) for Ed25519 (transferable verkey)
    /// - `1AAJ` + base64url(33 bytes compressed SEC1) for P-256 (transferable verkey)
    ///
    /// Per the CESR master code table, `1AAJ` (`ECDSA_256r1`) is the
    /// transferable secp256r1 verkey code — the P-256 analogue of Ed25519 `D`.
    /// (`1AAI` / `ECDSA_256r1N` is the non-transferable variant.) Auths
    /// identities rotate, so signers emit the transferable code.
    pub fn cesr_encoded_pubkey(&self) -> String {
        use cesride::Matter;
        let code = match self.seed.curve() {
            CurveType::Ed25519 => cesride::matter::Codex::Ed25519,
            CurveType::P256 => cesride::matter::Codex::ECDSA_256r1,
        };
        #[allow(clippy::expect_used)]
        // INVARIANT: every constructor validates public_key length against the curve, so cesride encode under the matching fixed-size code cannot fail
        cesride::Verfer::new(Some(code), Some(&self.public_key), None, None, None)
            .and_then(|v| v.qb64())
            .expect("cesride verkey encode is infallible for a validated key")
    }

    /// Legacy alias; callers should prefer [`cesr_encoded_pubkey`].
    pub fn cesr_encoded(&self) -> String {
        self.cesr_encoded_pubkey()
    }

    /// Curve-aware PKCS8 DER encode — replaces `build_ed25519_pkcs8_v2` and
    /// `encode_seed_as_pkcs8`. Dispatches on the seed's curve so a P-256 seed
    /// never silently wraps as an Ed25519 PKCS8 blob (hazard S3/S4).
    #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
    pub fn to_pkcs8(&self) -> Result<crate::pkcs8::Pkcs8Der, CryptoError> {
        match &self.seed {
            TypedSeed::Ed25519(seed_bytes) => {
                if self.public_key.len() != crate::provider::ED25519_PUBLIC_KEY_LEN {
                    return Err(CryptoError::InvalidPrivateKey(
                        "Ed25519 public key must be 32 bytes".to_string(),
                    ));
                }
                let mut pk = [0u8; 32];
                pk.copy_from_slice(&self.public_key);
                let bytes = crate::key_material::build_ed25519_pkcs8_v2(seed_bytes, &pk);
                Ok(crate::pkcs8::Pkcs8Der::new(bytes))
            }
            TypedSeed::P256(scalar) => {
                use p256::ecdsa::SigningKey;
                use p256::pkcs8::EncodePrivateKey;
                let sk = SigningKey::from_slice(scalar)
                    .map_err(|e| CryptoError::InvalidPrivateKey(format!("P-256 scalar: {e}")))?;
                let doc = sk
                    .to_pkcs8_der()
                    .map_err(|e| CryptoError::OperationFailed(format!("P-256 PKCS8: {e}")))?;
                Ok(crate::pkcs8::Pkcs8Der::new(doc.as_bytes().to_vec()))
            }
        }
    }

    /// Sign bytes using the signer's curve.
    #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
    pub fn sign(&self, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
        sign(&self.seed, message)
    }

    /// Returns the curve this signer uses.
    pub fn curve(&self) -> CurveType {
        self.seed.curve()
    }

    /// Returns the public key bytes (32 for Ed25519, 33 for P-256 compressed).
    pub fn public_key(&self) -> &[u8] {
        &self.public_key
    }

    /// Returns a reference to the typed seed. Scoped access for signing paths that
    /// need the `TypedSeed` directly (e.g. `auths_crypto::sign(&seed, msg)`) without
    /// exposing the raw bytes.
    pub fn seed(&self) -> &TypedSeed {
        &self.seed
    }
}

/// Normalize raw public key bytes to the canonical verkey form for `curve`.
///
/// Hardware backends and foreign encodings may hand back non-canonical forms
/// (e.g. an uncompressed SEC1 point); wire formats carry exactly one canonical
/// shape per curve — 32 raw bytes for Ed25519, the 33-byte compressed SEC1
/// point for P-256. Rejects bytes that are not a valid key on `curve`.
///
/// Args:
/// * `bytes`: Raw public key bytes in any encoding the curve accepts.
/// * `curve`: The curve the key belongs to (never inferred from length).
///
/// Usage:
/// ```ignore
/// let verkey = normalize_verkey(&hardware_pubkey, CurveType::P256)?;
/// assert_eq!(verkey.len(), 33);
/// ```
pub fn normalize_verkey(bytes: &[u8], curve: CurveType) -> Result<Vec<u8>, CryptoError> {
    match curve {
        CurveType::Ed25519 => {
            if bytes.len() != 32 {
                return Err(CryptoError::OperationFailed(format!(
                    "Ed25519 verkey must be 32 bytes, got {}",
                    bytes.len()
                )));
            }
            Ok(bytes.to_vec())
        }
        CurveType::P256 => {
            #[cfg(feature = "native")]
            {
                use p256::elliptic_curve::sec1::ToEncodedPoint;
                let pk = p256::PublicKey::from_sec1_bytes(bytes).map_err(|e| {
                    CryptoError::OperationFailed(format!("invalid P-256 public key: {e}"))
                })?;
                Ok(pk.to_encoded_point(true).as_bytes().to_vec())
            }
            #[cfg(not(feature = "native"))]
            {
                let _ = bytes;
                Err(CryptoError::UnsupportedTarget)
            }
        }
        #[allow(unreachable_patterns)]
        other => Err(CryptoError::OperationFailed(format!(
            "normalize_verkey: unsupported curve {other:?}"
        ))),
    }
}

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

    #[test]
    fn typed_seed_curve_identification() {
        let ed = TypedSeed::Ed25519([1u8; 32]);
        assert_eq!(ed.curve(), CurveType::Ed25519);

        let p = TypedSeed::P256([2u8; 32]);
        assert_eq!(p.curve(), CurveType::P256);
    }

    #[test]
    fn typed_seed_as_bytes() {
        let seed = TypedSeed::Ed25519([42u8; 32]);
        assert_eq!(seed.as_bytes(), &[42u8; 32]);
    }

    #[test]
    fn typed_seed_debug_redacts() {
        let seed = TypedSeed::P256([0u8; 32]);
        let debug = format!("{:?}", seed);
        assert!(debug.contains("REDACTED"));
        assert!(!debug.contains("0, 0, 0"));
    }

    #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
    mod native {
        use super::*;

        #[test]
        fn parse_ed25519_pkcs8_v2() {
            // Generate via ring, parse back
            use ring::rand::SystemRandom;
            use ring::signature::Ed25519KeyPair;
            let rng = SystemRandom::new();
            let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
            let parsed = parse_key_material(pkcs8.as_ref()).unwrap();
            assert_eq!(parsed.seed.curve(), CurveType::Ed25519);
            assert_eq!(parsed.public_key.len(), 32);
        }

        #[test]
        fn parse_p256_pkcs8() {
            use p256::ecdsa::SigningKey;
            use p256::elliptic_curve::rand_core::OsRng;
            use p256::pkcs8::EncodePrivateKey;
            let sk = SigningKey::random(&mut OsRng);
            let pkcs8 = sk.to_pkcs8_der().unwrap();
            let parsed = parse_key_material(pkcs8.as_bytes()).unwrap();
            assert_eq!(parsed.seed.curve(), CurveType::P256);
            assert_eq!(parsed.public_key.len(), 33);
        }

        #[test]
        fn parse_raw_32_bytes_is_ed25519() {
            let raw = [7u8; 32];
            let parsed = parse_key_material(&raw).unwrap();
            assert_eq!(parsed.seed.curve(), CurveType::Ed25519);
        }

        #[test]
        fn parse_garbage_fails() {
            let garbage = [0xFFu8; 50];
            assert!(parse_key_material(&garbage).is_err());
        }

        #[test]
        fn parse_empty_fails() {
            assert!(parse_key_material(&[]).is_err());
        }

        #[test]
        fn sign_ed25519_roundtrip() {
            use ring::signature::{ED25519, UnparsedPublicKey};
            let seed = TypedSeed::Ed25519([1u8; 32]);
            let msg = b"hello world";
            let sig = sign(&seed, msg).unwrap();
            assert_eq!(sig.len(), 64);

            let pk = public_key(&seed).unwrap();
            let verifier = UnparsedPublicKey::new(&ED25519, &pk);
            assert!(verifier.verify(msg, &sig).is_ok());
        }

        #[test]
        fn sign_p256_roundtrip() {
            use p256::ecdsa::{Signature, VerifyingKey, signature::Verifier};
            let seed = TypedSeed::P256([3u8; 32]);
            let msg = b"hello p256";
            let sig_bytes = sign(&seed, msg).unwrap();
            assert_eq!(sig_bytes.len(), 64);

            let pk_bytes = public_key(&seed).unwrap();
            assert_eq!(pk_bytes.len(), 33);

            let vk = VerifyingKey::from_sec1_bytes(&pk_bytes).unwrap();
            let sig = Signature::from_slice(&sig_bytes).unwrap();
            assert!(vk.verify(msg, &sig).is_ok());
        }

        #[test]
        fn cross_curve_isolation() {
            // Same raw bytes, different curves, different outputs
            let bytes = [5u8; 32];
            let ed_seed = TypedSeed::Ed25519(bytes);
            let p256_seed = TypedSeed::P256(bytes);

            let ed_pk = public_key(&ed_seed).unwrap();
            let p256_pk = public_key(&p256_seed).unwrap();

            // Different lengths (32 vs 33) and different values
            assert_ne!(ed_pk.len(), p256_pk.len());

            let msg = b"test";
            let ed_sig = sign(&ed_seed, msg).unwrap();
            let p256_sig = sign(&p256_seed, msg).unwrap();

            // Both 64 bytes but different values
            assert_eq!(ed_sig.len(), 64);
            assert_eq!(p256_sig.len(), 64);
            assert_ne!(ed_sig, p256_sig);
        }

        #[test]
        fn parse_then_sign_ed25519() {
            use ring::rand::SystemRandom;
            use ring::signature::{ED25519, Ed25519KeyPair, UnparsedPublicKey};
            let rng = SystemRandom::new();
            let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
            let parsed = parse_key_material(pkcs8.as_ref()).unwrap();

            let msg = b"end to end";
            let sig = sign(&parsed.seed, msg).unwrap();
            let verifier = UnparsedPublicKey::new(&ED25519, &parsed.public_key);
            assert!(verifier.verify(msg, &sig).is_ok());
        }

        #[test]
        fn parse_then_sign_p256() {
            use p256::ecdsa::{Signature, SigningKey, VerifyingKey, signature::Verifier};
            use p256::elliptic_curve::rand_core::OsRng;
            use p256::pkcs8::EncodePrivateKey;

            let sk = SigningKey::random(&mut OsRng);
            let pkcs8 = sk.to_pkcs8_der().unwrap();
            let parsed = parse_key_material(pkcs8.as_bytes()).unwrap();

            let msg = b"end to end p256";
            let sig_bytes = sign(&parsed.seed, msg).unwrap();

            let vk = VerifyingKey::from_sec1_bytes(&parsed.public_key).unwrap();
            let sig = Signature::from_slice(&sig_bytes).unwrap();
            assert!(vk.verify(msg, &sig).is_ok());
        }

        #[test]
        fn typed_signer_key_ed25519_roundtrip() {
            use ring::rand::SystemRandom;
            use ring::signature::Ed25519KeyPair;
            let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap();
            let s = TypedSignerKey::from_pkcs8(pkcs8.as_ref()).unwrap();
            assert_eq!(s.curve(), CurveType::Ed25519);
            assert!(s.cesr_encoded_pubkey().starts_with('D'));
            assert_eq!(s.public_key().len(), 32);
            let sig = s.sign(b"msg").unwrap();
            assert_eq!(sig.len(), 64);
        }

        #[test]
        fn typed_signer_key_p256_roundtrip() {
            use p256::ecdsa::SigningKey;
            use p256::elliptic_curve::rand_core::OsRng;
            use p256::pkcs8::EncodePrivateKey;
            let sk = SigningKey::random(&mut OsRng);
            let pkcs8 = sk.to_pkcs8_der().unwrap();
            let s = TypedSignerKey::from_pkcs8(pkcs8.as_bytes()).unwrap();
            assert_eq!(s.curve(), CurveType::P256);
            assert!(s.cesr_encoded_pubkey().starts_with("1AAJ"));
            assert_eq!(s.public_key().len(), 33);
            let sig = s.sign(b"msg").unwrap();
            assert_eq!(sig.len(), 64);
        }

        #[test]
        fn typed_signer_key_to_pkcs8_ed25519_roundtrip() {
            use ring::rand::SystemRandom;
            use ring::signature::Ed25519KeyPair;
            let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap();
            let s = TypedSignerKey::from_pkcs8(pkcs8.as_ref()).unwrap();
            let encoded = s.to_pkcs8().unwrap();
            let reparsed = TypedSignerKey::from_pkcs8(encoded.as_ref()).unwrap();
            assert_eq!(reparsed.curve(), CurveType::Ed25519);
            assert_eq!(reparsed.public_key(), s.public_key());
            assert_eq!(reparsed.seed.as_bytes(), s.seed.as_bytes());
        }

        #[test]
        fn typed_signer_key_to_pkcs8_p256_roundtrip() {
            let seed = TypedSeed::P256({
                let mut scalar = [9u8; 32];
                scalar[0] |= 1;
                scalar
            });
            let s = TypedSignerKey::from_seed(seed).unwrap();
            let encoded = s.to_pkcs8().unwrap();
            let reparsed = TypedSignerKey::from_pkcs8(encoded.as_ref()).unwrap();
            assert_eq!(reparsed.curve(), CurveType::P256);
            assert_eq!(reparsed.public_key(), s.public_key());
            assert_eq!(reparsed.seed.as_bytes(), s.seed.as_bytes());
        }

        #[test]
        fn rotation_signer_alias_still_works() {
            use ring::rand::SystemRandom;
            use ring::signature::Ed25519KeyPair;
            let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap();
            // Via the transitional alias
            let s = TypedSignerKey::from_pkcs8(pkcs8.as_ref()).unwrap();
            assert_eq!(s.curve(), CurveType::Ed25519);
        }

        #[test]
        fn typed_signer_key_from_parts_rejects_mismatched_pubkey_length() {
            let seed = TypedSeed::Ed25519([1u8; 32]);
            let wrong_len_pk = vec![0u8; 33]; // 33 bytes, expected 32 for Ed25519
            let err = TypedSignerKey::from_parts(seed, wrong_len_pk).unwrap_err();
            assert!(matches!(err, CryptoError::InvalidPrivateKey(_)));
        }

        /// Regression — ECDSA-P256 must be deterministic (RFC 6979). If this
        /// breaks, something has routed signing through a randomized-nonce
        /// path, which is class-breaking (Sony PS3 failure mode).
        ///
        /// NOTE: The FIPS provider (aws-lc-rs) adds randomized blinding to
        /// nonce computation for side-channel resistance. Signatures are still
        /// RFC 6979 compliant (verifiable) but not byte-deterministic. This
        /// test is gated to the default (ring) provider only.
        #[test]
        #[cfg(not(feature = "fips"))]
        fn sign_p256_is_rfc6979_deterministic() {
            let seed = TypedSeed::P256([7u8; 32]);
            let msg = b"fn-128.T2 determinism";
            let a = sign(&seed, msg).unwrap();
            let b = sign(&seed, msg).unwrap();
            let c = sign(&seed, msg).unwrap();
            assert_eq!(a, b);
            assert_eq!(b, c);
            assert_eq!(a.len(), 64);
        }

        /// Regression — Ed25519 is deterministic by construction (RFC 8032).
        /// Pairs with the P-256 test to assert the whole sign surface is
        /// deterministic.
        #[test]
        fn sign_ed25519_is_deterministic() {
            let seed = TypedSeed::Ed25519([11u8; 32]);
            let msg = b"fn-128.T2 determinism";
            let a = sign(&seed, msg).unwrap();
            let b = sign(&seed, msg).unwrap();
            assert_eq!(a, b);
            assert_eq!(a.len(), 64);
        }

        /// Regression — the sync `sign` free function and the async trait
        /// `sign_typed` method must produce byte-identical output. Proves the
        /// T2 refactor did not fork signing behavior across the two entry
        /// points; a FIPS/CNSA swap that changes one must change the other
        /// and this test will catch a drift.
        ///
        /// Gated to non-FIPS: under `--features fips`, the sync provider is
        /// aws-lc-rs (randomized blinding) while this test compares against
        /// Ring (deterministic). The two produce valid but non-identical sigs.
        #[tokio::test]
        #[cfg(not(feature = "fips"))]
        async fn sync_sign_matches_async_sign_typed_p256() {
            use crate::provider::CryptoProvider;
            use crate::ring_provider::RingCryptoProvider;

            let seed = TypedSeed::P256([42u8; 32]);
            let msg = b"parity check";

            let sync_sig = sign(&seed, msg).unwrap();
            let async_sig = RingCryptoProvider.sign_typed(&seed, msg).await.unwrap();

            assert_eq!(sync_sig, async_sig);
        }

        #[tokio::test]
        async fn sync_sign_matches_async_sign_typed_ed25519() {
            use crate::provider::CryptoProvider;
            use crate::ring_provider::RingCryptoProvider;

            let seed = TypedSeed::Ed25519([19u8; 32]);
            let msg = b"parity check";

            let sync_sig = sign(&seed, msg).unwrap();
            let async_sig = RingCryptoProvider.sign_typed(&seed, msg).await.unwrap();

            assert_eq!(sync_sig, async_sig);
        }

        /// Regression — the sync `public_key` free function and the async
        /// trait `typed_public_key_from_seed` method must produce byte-identical
        /// output across curves.
        #[tokio::test]
        async fn sync_public_key_matches_async_typed_public_key() {
            use crate::provider::CryptoProvider;
            use crate::ring_provider::RingCryptoProvider;

            for (name, seed) in [
                ("ed25519", TypedSeed::Ed25519([23u8; 32])),
                ("p256", TypedSeed::P256([29u8; 32])),
            ] {
                let sync_pk = public_key(&seed).unwrap();
                let async_pk = RingCryptoProvider
                    .typed_public_key_from_seed(&seed)
                    .await
                    .unwrap();
                assert_eq!(sync_pk, async_pk, "pub key drift on {name}");
            }
        }

        /// Regression — the async trait `sign_typed` round-trips through
        /// `verify_typed` with the public key derived from the same seed.
        /// Covers the curve-agnostic path end-to-end.
        #[tokio::test]
        async fn sign_typed_and_verify_typed_round_trip() {
            use crate::provider::CryptoProvider;
            use crate::ring_provider::RingCryptoProvider;

            for seed in [TypedSeed::Ed25519([31u8; 32]), TypedSeed::P256([37u8; 32])] {
                let msg = b"curve-agnostic round trip";
                let pk = RingCryptoProvider
                    .typed_public_key_from_seed(&seed)
                    .await
                    .unwrap();
                let sig = RingCryptoProvider.sign_typed(&seed, msg).await.unwrap();
                RingCryptoProvider
                    .verify_typed(seed.curve(), &pk, msg, &sig)
                    .await
                    .expect("verify_typed should accept matching signature");
            }
        }
    }
}