jose-rs 0.14.0

Pure-Rust JOSE library (JWS, JWE, JWK, JWT) with software and HSM key support
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! Import keys from DER encodings (PKCS#8 private keys, X.509 SPKI public
//! keys) into the crate's `Jwk` / `SoftwareKey` representation.
//!
//! These are the jose-rs equivalents of josekit's `signer_from_der` /
//! `verifier_from_der`: given the DER bytes that an X.509 toolchain or an
//! HSM export produces, build a `Jwk` (and from there a signer or verifier
//! via the existing JWK-first entry points).
//!
//! Dispatch is by the algorithm OID carried in the PKCS#8
//! `AlgorithmIdentifier` / SPKI header, so an attacker cannot smuggle, say,
//! an RSA key past an EC decoder. Each concrete key type is then handed to
//! its own vetted RustCrypto decoder. Supported families mirror what the
//! crate already signs/verifies with: RSA (RS/PS), EC (P-256/384/521 →
//! ES256/384/512), and Ed25519 / Ed448 (EdDSA).

use p521::elliptic_curve::sec1::ToSec1Point;
use pkcs8::der::Decode;
use pkcs8::spki::{DecodePublicKey, EncodePublicKey, SubjectPublicKeyInfoRef};
use pkcs8::{DecodePrivateKey, EncodePrivateKey, ObjectIdentifier, PrivateKeyInfoRef};
use rsa::traits::PublicKeyParts;

use crate::error::{JoseError, Result};
use crate::jwk::convert::software_key_to_jwk;
use crate::jwk::Jwk;

// Algorithm OIDs (RFC 8017, RFC 5480, RFC 8410). Declared inline rather than
// pulled from a const-oid database feature so the set we accept is explicit
// and auditable.
const OID_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
// RSASSA-PSS keys carry restrictions that a generic RSA JWK cannot retain.
const OID_RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
const OID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
const OID_ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");

// Named-curve OIDs that ride in the EC `AlgorithmIdentifier` parameters.
const OID_P256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
const OID_P384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");
const OID_P521: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");

/// Reject a PSS-specific key before decoding or normalizing its key material.
///
/// Even absent parameters retain a PSS-only restriction through the OID.
/// The generic RSA JWK representation cannot enforce that restriction, so
/// both public and private importers must fail instead of silently losing it.
fn reject_pss_key(oid: ObjectIdentifier) -> Result<()> {
    if oid == OID_RSA_PSS {
        return Err(JoseError::Key(
            "RSA-PSS-specific DER keys are unsupported: JWK conversion cannot preserve their restrictions"
                .into(),
        ));
    }
    Ok(())
}

fn ensure_rsa_min_bits(key: &rsa::PublicKey) -> Result<()> {
    crate::ensure_rsa_bits(key.n().bit_width() as usize)
}

/// Import a PKCS#8 DER-encoded private key into a [`Jwk`].
///
/// Accepts the unencrypted PKCS#8 `OneAsymmetricKey` / `PrivateKeyInfo`
/// structure (RFC 5208 / RFC 5958) for the signature families this crate
/// supports: RSA, EC (P-256/384/521), and Ed25519/Ed448. The returned JWK carries
/// the full private key material plus the matching public components, with
/// no `alg` pinned (the caller selects the precise JWS algorithm — e.g.
/// `RS256` vs `PS256` for the same RSA key — by setting `jwk.alg`).
///
/// RSA-PSS-specific DER keys are rejected, including those with absent
/// parameters: converting them to a generic RSA JWK would lose their
/// PSS-only and parameter restrictions. Ordinary `rsaEncryption` keys
/// remain supported for both RS* and PS* algorithms.
///
/// This is the private-key counterpart of josekit's `signer_from_der`:
/// follow it with [`crate::jws::compact::sign_with_jwk`] after pinning
/// `jwk.alg`.
pub fn jwk_from_pkcs8_der(der: &[u8]) -> Result<Jwk> {
    crate::ensure_key_der_size(der.len())?;
    let info = PrivateKeyInfoRef::from_der(der)
        .map_err(|e| JoseError::Key(format!("invalid PKCS#8 DER: {e}")))?;
    let oid = info.algorithm.oid;
    reject_pss_key(oid)?;

    let sw = if oid == OID_RSA {
        let raw = rsa::pkcs1::RsaPrivateKeyRef::from_der(info.private_key.as_bytes())
            .map_err(|e| JoseError::Key(format!("invalid RSA PKCS#8 key: {e}")))?;
        crate::ensure_rsa_modulus_bytes(raw.modulus.as_bytes())?;
        let key = rsa::PrivateKey::from_pkcs8_der(der)
            .map_err(|e| JoseError::Key(format!("invalid RSA PKCS#8 key: {e}")))?;
        let public = key.to_public_key();
        ensure_rsa_min_bits(&public)?;
        let normalized = key
            .to_pkcs8_der()
            .map_err(|e| JoseError::Key(format!("RSA PKCS#8 normalization failed: {e}")))?;
        kryptering::SoftwareKey::from_pkcs8_der(
            kryptering::KeyAlgorithm::Rsa,
            normalized.as_bytes(),
        )?
    } else if oid == OID_ED25519 {
        ed25519_dalek::SigningKey::from_pkcs8_der(der)
            .map_err(|e| JoseError::Key(format!("invalid Ed25519 PKCS#8 key: {e}")))?;
        kryptering::SoftwareKey::from_pkcs8_der(kryptering::KeyAlgorithm::Ed25519, der)?
    } else if oid == super::ed448::OID {
        kryptering::SoftwareKey::from_pkcs8_der(kryptering::KeyAlgorithm::Ed448, der)?
    } else if oid == OID_EC_PUBLIC_KEY {
        let curve = info
            .algorithm
            .parameters_oid()
            .map_err(|e| JoseError::Key(format!("EC key missing curve parameters: {e}")))?;
        ec_private_from_pkcs8(der, curve)?
    } else {
        return Err(JoseError::Key(format!(
            "unsupported PKCS#8 algorithm OID: {oid}"
        )));
    };

    software_key_to_jwk(&sw)
}

/// Import an X.509 SubjectPublicKeyInfo (SPKI) DER-encoded public key into a
/// [`Jwk`].
///
/// Accepts the SPKI structure (RFC 5280 §4.1.2.7) for RSA, EC
/// (P-256/384/521), and Ed25519/Ed448 public keys. The returned JWK carries only
/// public components and pins no `alg`.
///
/// RSA-PSS-specific DER keys are rejected, including those with absent
/// parameters, because this conversion cannot preserve their restrictions.
/// Ordinary `rsaEncryption` keys remain supported for RS* and PS* algorithms.
///
/// This is the public-key counterpart of josekit's `verifier_from_der`:
/// follow it with [`crate::jws::compact::verify_with_jwk`] (which derives
/// the algorithm from the token header) or build a verifier explicitly.
pub fn jwk_from_spki_der(der: &[u8]) -> Result<Jwk> {
    crate::ensure_key_der_size(der.len())?;
    let spki = SubjectPublicKeyInfoRef::from_der(der)
        .map_err(|e| JoseError::Key(format!("invalid SPKI DER: {e}")))?;
    let oid = spki.algorithm.oid;
    reject_pss_key(oid)?;

    let sw = if oid == OID_RSA {
        let key = rsa::PublicKey::from_public_key_der(der)
            .map_err(|e| JoseError::Key(format!("invalid RSA SPKI key: {e}")))?;
        ensure_rsa_min_bits(&key)?;
        let normalized = key
            .to_public_key_der()
            .map_err(|e| JoseError::Key(format!("RSA SPKI normalization failed: {e}")))?;
        kryptering::SoftwareKey::from_spki_der(
            kryptering::KeyAlgorithm::Rsa,
            normalized.as_bytes(),
        )?
    } else if oid == OID_ED25519 {
        ed25519_dalek::VerifyingKey::from_public_key_der(der)
            .map_err(|e| JoseError::Key(format!("invalid Ed25519 SPKI key: {e}")))?;
        kryptering::SoftwareKey::from_spki_der(kryptering::KeyAlgorithm::Ed25519, der)?
    } else if oid == super::ed448::OID {
        kryptering::SoftwareKey::from_spki_der(kryptering::KeyAlgorithm::Ed448, der)?
    } else if oid == OID_EC_PUBLIC_KEY {
        let curve = spki
            .algorithm
            .parameters_oid()
            .map_err(|e| JoseError::Key(format!("EC key missing curve parameters: {e}")))?;
        ec_public_from_spki(der, curve)?
    } else {
        return Err(JoseError::Key(format!(
            "unsupported SPKI algorithm OID: {oid}"
        )));
    };

    software_key_to_jwk(&sw)
}

/// Import a PKCS#1 (`RSAPrivateKey`) DER-encoded RSA private key into a [`Jwk`].
///
/// PKCS#1 (RFC 8017 §A.1.2) is the older, RSA-only sibling of PKCS#8 — still what
/// `openssl genrsa` writes by default and what `SSH`'s `id_rsa` carries. It states no
/// algorithm, because there is only one to state.
///
/// The bytes are not trusted for what they say. The DER is decoded, and then the key is
/// **rebuilt and validated**: the primes must multiply to the modulus, `d·e ≡ 1 (mod p−1)`
/// must hold for each prime, and the file's own CRT members (`exponent1`, `exponent2`,
/// `coefficient`) must match what the key implies. A file whose CRT values disagree with
/// its key is refused rather than quietly repaired, because a corrupt key that works after
/// we substitute our own arithmetic is a corrupt key nobody notices. The result is then
/// normalized to PKCS#8 and run through [`jwk_from_pkcs8_der`], so the modulus floor and
/// the backend's own checks apply exactly as they do for any other RSA import — a PKCS#1
/// file is not an easier way in.
///
/// **Multi-prime keys are refused by name.** PKCS#1 allows more than two primes (its
/// `multiPrimeVersion`), RFC 7518's RSA JWK has `p` and `q` and no place for a third, and a
/// JWK that silently dropped a prime factor would be a different key that verifies nothing.
///
/// # Errors
///
/// [`JoseError::Key`] for malformed DER, a multi-prime key, an internally inconsistent key,
/// a modulus below [`crate::MIN_RSA_BITS`], and for any non-RSA input.
pub fn jwk_from_pkcs1_der(der: &[u8]) -> Result<Jwk> {
    use rsa::pkcs8::EncodePrivateKey;
    use rsa::traits::PrivateKeyParts;

    crate::ensure_key_der_size(der.len())?;
    let asn1 = rsa::pkcs1::RsaPrivateKeyRef::from_der(der)
        .map_err(|e| JoseError::Key(format!("invalid PKCS#1 RSAPrivateKey DER: {e}")))?;
    if asn1.other_prime_infos.is_some() {
        return Err(JoseError::Key(
            "multi-prime RSA keys are unsupported: RFC 7518 §6.3 gives an RSA JWK `p` and `q`              and no member for a third prime factor, so importing one would produce a different              key that verifies nothing"
                .into(),
        ));
    }

    crate::ensure_rsa_modulus_bytes(asn1.modulus.as_bytes())?;

    let n = biguint(asn1.modulus.as_bytes());
    let e = biguint(asn1.public_exponent.as_bytes());
    let d = biguint(asn1.private_exponent.as_bytes());
    let p = biguint(asn1.prime1.as_bytes());
    let q = biguint(asn1.prime2.as_bytes());

    // Rebuilding is the validation: `from_components` checks that the primes are prime
    // factors of the modulus and that `d` is a valid inverse of `e` modulo each `p−1`,
    // then recomputes the CRT members from the parts that survived.
    let key = rsa::PrivateKey::from_components(n, e, d, vec![p, q]).map_err(|err| {
        JoseError::Key(format!(
            "PKCS#1 RSA key is not internally consistent ({err}); its members do not describe              one key"
        ))
    })?;
    ensure_rsa_min_bits(&key.to_public_key())?;

    // The file's own CRT members are checked against the rebuilt key instead of being
    // trusted or discarded. Both alternatives lose information: trusting a wrong `dp`
    // propagates it, and silently substituting a right one hides the corruption.
    for (name, from_file, computed) in [
        (
            "exponent1 (dp)",
            asn1.exponent1.as_bytes(),
            key.dp().cloned(),
        ),
        (
            "exponent2 (dq)",
            asn1.exponent2.as_bytes(),
            key.dq().cloned(),
        ),
        (
            "coefficient (q^-1 mod p)",
            asn1.coefficient.as_bytes(),
            key.qinv().map(|qi| qi.retrieve()),
        ),
    ] {
        let matches = match computed {
            Some(value) => biguint(from_file) == value,
            // The key we rebuilt has no CRT member to compare against only if it was built
            // without precomputation, which `from_components` does not do. Treat its absence
            // as a mismatch rather than as agreement.
            None => false,
        };
        if !matches {
            return Err(JoseError::Key(format!(
                "PKCS#1 RSA key's {name} does not match its own key material; refusing to                  import a corrupt key or to substitute a computed one"
            )));
        }
    }

    let normalized = key
        .to_pkcs8_der()
        .map_err(|e| JoseError::Key(format!("PKCS#1 to PKCS#8 normalization failed: {e}")))?;
    jwk_from_pkcs8_der(normalized.as_bytes())
}

/// Import a PKCS#1 (`RSAPublicKey`) DER-encoded RSA public key into a [`Jwk`].
///
/// The SPKI form (RFC 5280) wraps these same two integers in an `AlgorithmIdentifier`;
/// PKCS#1 states them bare, which is why the entry point is separate — a bare
/// `RSAPublicKey` carries no algorithm to dispatch on, and a caller who hands one to the
/// SPKI importer should be told the difference rather than given a parse error.
///
/// The key is rebuilt (`PublicKey::new`, which rejects an even or tiny public exponent)
/// and then run through [`jwk_from_spki_der`] once wrapped, so the modulus floor and the
/// backend's checks are the same ones every other RSA public import faces.
///
/// # Errors
///
/// [`JoseError::Key`] for malformed DER, an unusable public exponent, or a modulus below
/// [`crate::MIN_RSA_BITS`].
pub fn jwk_from_pkcs1_public_der(der: &[u8]) -> Result<Jwk> {
    use rsa::pkcs8::EncodePublicKey;

    crate::ensure_key_der_size(der.len())?;
    let asn1 = rsa::pkcs1::RsaPublicKeyRef::from_der(der)
        .map_err(|e| JoseError::Key(format!("invalid PKCS#1 RSAPublicKey DER: {e}")))?;
    crate::ensure_rsa_modulus_bytes(asn1.modulus.as_bytes())?;
    let key = rsa::PublicKey::new(
        biguint(asn1.modulus.as_bytes()),
        biguint(asn1.public_exponent.as_bytes()),
    )
    .map_err(|e| JoseError::Key(format!("invalid PKCS#1 RSA public key: {e}")))?;
    ensure_rsa_min_bits(&key)?;
    let spki = key
        .to_public_key_der()
        .map_err(|e| JoseError::Key(format!("RSA SPKI wrapping failed: {e}")))?;
    jwk_from_spki_der(spki.as_bytes())
}

/// A `BigUint` from big-endian octets, accepting the leading zero octet DER uses to keep
/// a high bit from reading as a negative number.
fn biguint(bytes: &[u8]) -> rsa::BoxedUint {
    rsa::BoxedUint::from_be_slice_vartime(bytes)
}

/// Import a SEC1 (`ECPrivateKey`) DER-encoded EC private key into a [`Jwk`].
///
/// SEC1 (RFC 5915) is what `openssl ec -traditional` and many hardware tools write: the
/// scalar, optionally the curve, optionally the public point. PKCS#8 wraps the same scalar
/// and states the curve in an `AlgorithmIdentifier`, which is why the two need separate entry
/// points — a SEC1 file's curve lives in a different place, and may not be in it at all.
///
/// Three refusals do the security work here, and all three are about not guessing:
///
/// * **No curve, no key.** `parameters` is OPTIONAL in this structure. A bare scalar with no
///   curve is not a key, and the plausible-looking recovery — try each supported curve until
///   one accepts the scalar — is exactly how a P-256 secret ends up being read as a P-384
///   key. Such a file is refused.
/// * **Explicit curve parameters are refused, not matched to the nearest named curve.**
///   RFC 5915 lets a key carry the whole domain-parameter block (`field-id`, `a`, `b`, `base`,
///   `order`, `cofactor`). Reading that as "close enough to P-256" would import a key whose
///   curve is *asserted by the file* rather than named by an OID — and an anomalous or
///   unsafely-generated curve is exactly what an attacker wants this crate to accept. Only
///   named curves this crate supports are read.
/// * **A supplied public point must match the scalar.** `publicKey` is OPTIONAL; when present
///   it is compared against the point the secret derives. A file pairing a scalar with
///   someone else's public point would yield a JWK whose public half verifies nothing, while
///   both halves look valid in isolation.
///
/// What survives is normalized to PKCS#8 and run through [`jwk_from_pkcs8_der`], so curve
/// dispatch, the backend's checks and JWK construction are the same code path every other EC
/// import uses.
///
/// # Errors
///
/// [`JoseError::Key`] for malformed DER, absent or explicit curve parameters, an unsupported
/// named curve, a scalar outside `[1, n−1]`, and a public point that disagrees with it.
pub fn jwk_from_sec1_der(der: &[u8]) -> Result<Jwk> {
    use sec1::der::Decode;
    use sec1::EcParameters;

    crate::ensure_key_der_size(der.len())?;
    let parsed = sec1::EcPrivateKey::from_der(der).map_err(|err| sec1_decode_error(der, err))?;

    let curve = match parsed.parameters {
        Some(EcParameters::NamedCurve(oid)) => oid,
        None => {
            return Err(JoseError::Key(
                "SEC1 EC private key carries no curve parameters; a scalar without its curve is                  not a key, and guessing one would silently change which key this is"
                    .into(),
            ));
        }
    };

    // Per curve: build the scalar (which enforces the range and rejects zero), compare any
    // public point the file asserts against the one it derives, then hand the normalized
    // PKCS#8 form to the shared importer.
    match curve {
        OID_P256 => sec1_p256_import(der, parsed.public_key),
        OID_P384 => sec1_p384_import(der, parsed.public_key),
        OID_P521 => sec1_p521_import(der, parsed.public_key),
        other => Err(JoseError::Key(format!(
            "unsupported SEC1 curve OID {other}; this crate reads P-256, P-384 and P-521"
        ))),
    }
}

/// SEC1 import for one NIST curve, written concretely per curve rather than generically: the
/// three bodies differ in which `SecretKey` type they use and how its public point is
/// reached, and the generic form needed an `elliptic_curve` edge this crate does not have.
macro_rules! sec1_import {
    ($name:ident, $secret:ty, $point:path, $curve_name:literal) => {
        fn $name(der: &[u8], asserted: Option<&[u8]>) -> Result<Jwk> {
            use $point as _;

            let secret = <$secret>::from_sec1_der(der).map_err(|e| {
                // The decoder rejects an out-of-range scalar and an unusable embedded point
                // through the same call, so the message names both possibilities rather than
                // blaming the scalar for a point problem.
                JoseError::Key(format!(
                    "invalid SEC1 {} ECPrivateKey: the scalar must lie in [1, n-1] and any                      embedded public point must be a valid point on that curve ({e})",
                    $curve_name
                ))
            })?;
            // `to_sec1_der` round-trip: the scalar must survive re-encoding at its own
            // width, which catches a representation the curve would otherwise silently
            // reduce.
            secret
                .to_sec1_der()
                .map_err(|e| JoseError::Key(format!("SEC1 scalar is not representable: {e}")))?;
            ensure_point_matches(
                secret.public_key().to_sec1_point(false).as_bytes(),
                asserted,
                $curve_name,
            )?;
            let normalized = secret.to_pkcs8_der().map_err(|e| {
                JoseError::Key(format!(
                    "SEC1 to PKCS#8 normalization failed for {}: {e}",
                    $curve_name
                ))
            })?;
            jwk_from_pkcs8_der(normalized.as_bytes())
        }
    };
}

sec1_import!(
    sec1_p256_import,
    p256::SecretKey,
    p256::elliptic_curve::sec1::ToSec1Point,
    "P-256"
);
sec1_import!(
    sec1_p384_import,
    p384::SecretKey,
    p384::elliptic_curve::sec1::ToSec1Point,
    "P-384"
);

/// P-521, whose key types need the same workaround the PKCS#8 importer uses for them.
fn sec1_p521_import(der: &[u8], asserted: Option<&[u8]>) -> Result<Jwk> {
    use p521::elliptic_curve::sec1::ToSec1Point;

    let secret = p521::SecretKey::from_sec1_der(der).map_err(|e| {
        JoseError::Key(format!(
            "invalid SEC1 P-521 ECPrivateKey: the scalar must lie in [1, n-1] and any embedded              public point must be a valid point on that curve ({e})"
        ))
    })?;
    let point = secret.public_key().to_sec1_point(false);
    ensure_point_matches(point.as_bytes(), asserted, "P-521")?;
    let normalized = secret.to_pkcs8_der().map_err(|e| {
        JoseError::Key(format!(
            "SEC1 to PKCS#8 normalization failed for P-521: {e}"
        ))
    })?;
    jwk_from_pkcs8_der(normalized.as_bytes())
}

/// Compare the public point a file asserts with the one its scalar derives.
fn ensure_point_matches(computed: &[u8], asserted: Option<&[u8]>, name: &str) -> Result<()> {
    match asserted {
        None => Ok(()),
        Some(point) if point == computed => Ok(()),
        Some(_) => Err(JoseError::Key(format!(
            "{name} SEC1 key's public point does not match its private scalar; importing it              would produce a JWK whose public half verifies nothing"
        ))),
    }
}

/// Turn a SEC1 decode failure into the message that explains it.
///
/// `sec1` models only the named-curve form of `ECParameters`, so a file carrying RFC 5915's
/// explicit domain-parameter block fails to decode as a generic ASN.1 error. This looks at the
/// tag of the `parameters` member to say so — which can only ever turn a vague refusal into a
/// specific one. Nothing is accepted here that the decoder did not accept.
fn sec1_decode_error(der: &[u8], err: sec1::der::Error) -> JoseError {
    if carries_explicit_parameters(der) {
        return JoseError::Key(
            "SEC1 keys with explicit curve parameters (RFC 5915's full domain-parameter block)              are unsupported: matching them to the nearest named curve would import a key whose              curve is asserted by the file rather than named by an OID. Export a named curve"
                .into(),
        );
    }
    JoseError::Key(format!("invalid SEC1 ECPrivateKey DER: {err}"))
}

/// Does the `parameters [0]` member hold a SEQUENCE (explicit parameters) rather than an OID?
///
/// A minimal walk over the top-level `ECPrivateKey` SEQUENCE, used *only* to classify a
/// refusal it can already make. Anything it cannot read is reported as "not explicit
/// parameters", so this function can never cause something to be accepted.
fn carries_explicit_parameters(der: &[u8]) -> bool {
    // ECPrivateKey ::= SEQUENCE { version, privateKey, parameters [0], publicKey [1] }
    let Some(mut body) = der_sequence_body(der) else {
        return false;
    };
    while !body.is_empty() {
        let tag = body[0];
        let Some((len, header)) = der_member_header(body) else {
            return false;
        };
        // 0xa0 is the constructed `parameters [0]` member: an OID (named curve) or a
        // SEQUENCE (explicit parameters) inside it.
        if tag == 0xa0 {
            return body
                .get(header..header + len)
                .is_some_and(|value| value.first() == Some(&0x30));
        }
        let Some(next) = header.checked_add(len) else {
            return false;
        };
        let Some(rest) = body.get(next..) else {
            return false;
        };
        body = rest;
    }
    false
}

/// The content of a DER `SEQUENCE`'s body, or `None` if this is not one.
fn der_sequence_body(der: &[u8]) -> Option<&[u8]> {
    if der.first() != Some(&0x30) {
        return None;
    }
    let (len, header) = der_member_header(der)?;
    der.get(header..header + len)
}

/// `(value length, header size)` of the DER member at the start of `buf`.
///
/// Only definite lengths are read; an indefinite length is not valid DER and is reported as
/// unreadable, which the caller treats as "not explicit parameters".
fn der_member_header(buf: &[u8]) -> Option<(usize, usize)> {
    let (&_tag, rest) = buf.split_first()?;
    let &first = rest.first()?;
    if first & 0x80 == 0 {
        return Some((first as usize, 2));
    }
    let octets = (first & 0x7f) as usize;
    if octets == 0 || octets > 4 {
        return None;
    }
    let len = read_length(rest.get(1..1 + octets)?)?;
    Some((len, 2 + octets))
}

/// A length value from its big-endian length octets.
fn read_length(octets: &[u8]) -> Option<usize> {
    let mut acc: usize = 0;
    for byte in octets {
        acc = acc.checked_shl(8)?.checked_add(*byte as usize)?;
    }
    Some(acc)
}

// ── EC dispatch by named-curve OID ──────────────────────────────────────

fn ec_private_from_pkcs8(der: &[u8], curve: ObjectIdentifier) -> Result<kryptering::SoftwareKey> {
    match curve {
        OID_P256 => {
            p256::ecdsa::SigningKey::from_pkcs8_der(der)
                .map_err(|e| JoseError::Key(format!("invalid P-256 PKCS#8 key: {e}")))?;
            kryptering::SoftwareKey::from_pkcs8_der(
                kryptering::KeyAlgorithm::Ec(kryptering::EcCurve::P256),
                der,
            )
            .map_err(Into::into)
        }
        OID_P384 => {
            p384::ecdsa::SigningKey::from_pkcs8_der(der)
                .map_err(|e| JoseError::Key(format!("invalid P-384 PKCS#8 key: {e}")))?;
            kryptering::SoftwareKey::from_pkcs8_der(
                kryptering::KeyAlgorithm::Ec(kryptering::EcCurve::P384),
                der,
            )
            .map_err(Into::into)
        }
        OID_P521 => {
            // p521's ECDSA key types don't implement the pkcs8/spki decoder
            // traits directly; decode the curve key and convert via scalar
            // bytes (matching the `from_slice` path used elsewhere).
            let secret = p521::SecretKey::from_pkcs8_der(der)
                .map_err(|e| JoseError::Key(format!("invalid P-521 PKCS#8 key: {e}")))?;
            p521::ecdsa::SigningKey::from_slice(&secret.to_bytes())
                .map_err(|e| JoseError::Key(format!("invalid P-521 private scalar: {e}")))?;
            kryptering::SoftwareKey::from_pkcs8_der(
                kryptering::KeyAlgorithm::Ec(kryptering::EcCurve::P521),
                der,
            )
            .map_err(Into::into)
        }
        other => Err(JoseError::Key(format!("unsupported EC curve OID: {other}"))),
    }
}

fn ec_public_from_spki(der: &[u8], curve: ObjectIdentifier) -> Result<kryptering::SoftwareKey> {
    match curve {
        OID_P256 => {
            p256::ecdsa::VerifyingKey::from_public_key_der(der)
                .map_err(|e| JoseError::Key(format!("invalid P-256 SPKI key: {e}")))?;
            kryptering::SoftwareKey::from_spki_der(
                kryptering::KeyAlgorithm::Ec(kryptering::EcCurve::P256),
                der,
            )
            .map_err(Into::into)
        }
        OID_P384 => {
            p384::ecdsa::VerifyingKey::from_public_key_der(der)
                .map_err(|e| JoseError::Key(format!("invalid P-384 SPKI key: {e}")))?;
            kryptering::SoftwareKey::from_spki_der(
                kryptering::KeyAlgorithm::Ec(kryptering::EcCurve::P384),
                der,
            )
            .map_err(Into::into)
        }
        OID_P521 => {
            let public = p521::PublicKey::from_public_key_der(der)
                .map_err(|e| JoseError::Key(format!("invalid P-521 SPKI key: {e}")))?;
            p521::ecdsa::VerifyingKey::from_sec1_bytes(public.to_sec1_point(false).as_bytes())
                .map_err(|e| JoseError::Key(format!("invalid P-521 public point: {e}")))?;
            kryptering::SoftwareKey::from_spki_der(
                kryptering::KeyAlgorithm::Ec(kryptering::EcCurve::P521),
                der,
            )
            .map_err(Into::into)
        }
        other => Err(JoseError::Key(format!("unsupported EC curve OID: {other}"))),
    }
}

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

    fn rng() -> getrandom::rand_core::UnwrapErr<getrandom::SysRng> {
        getrandom::rand_core::UnwrapErr(getrandom::SysRng)
    }
    use crate::header::JoseHeader;
    use pkcs8::spki::EncodePublicKey;
    use pkcs8::EncodePrivateKey;

    /// Sign with a JWK imported from a PKCS#8 private key, verify with a JWK
    /// imported from the matching SPKI public key. Exercises the full
    /// DER → Jwk → signer/verifier path for one algorithm.
    fn der_roundtrip(alg: &str, priv_der: &[u8], pub_der: &[u8]) {
        let mut priv_jwk = jwk_from_pkcs8_der(priv_der).unwrap();
        priv_jwk.alg = Some(alg.to_string());

        let mut pub_jwk = jwk_from_spki_der(pub_der).unwrap();
        pub_jwk.alg = Some(alg.to_string());

        let header = JoseHeader::new(alg);
        let payload = b"der-import roundtrip payload";

        let token = crate::jws::compact::sign_with_jwk(&priv_jwk, payload, &header)
            .unwrap_or_else(|e| panic!("{alg} sign failed: {e}"));
        let recovered = crate::jws::compact::verify_with_jwk(&pub_jwk, &token)
            .unwrap_or_else(|e| panic!("{alg} verify failed: {e}"));
        assert_eq!(recovered, payload);
    }

    #[test]
    fn rsa_pkcs8_spki_roundtrip_rs256_and_ps256() {
        let sk = rsa::PrivateKey::new(&mut rng(), 2048).unwrap();
        let pk = sk.to_public_key();
        let priv_der = sk.to_pkcs8_der().unwrap();
        let pub_der = pk.to_public_key_der().unwrap();

        // Same RSA key, two distinct JWS algorithms selected via jwk.alg.
        der_roundtrip("RS256", priv_der.as_bytes(), pub_der.as_bytes());
        der_roundtrip("PS256", priv_der.as_bytes(), pub_der.as_bytes());
        der_roundtrip("PS512", priv_der.as_bytes(), pub_der.as_bytes());
    }

    #[test]
    fn rsa_der_import_rejects_sub_2048_bits() {
        let sk = rsa::PrivateKey::new(&mut rng(), 1024).unwrap();
        let pk = sk.to_public_key();
        let priv_der = sk.to_pkcs8_der().unwrap();
        let pub_der = pk.to_public_key_der().unwrap();

        let err = jwk_from_pkcs8_der(priv_der.as_bytes())
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("below the required minimum"),
            "unexpected: {err}"
        );

        let err = jwk_from_spki_der(pub_der.as_bytes())
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("below the required minimum"),
            "unexpected: {err}"
        );
    }

    #[test]
    fn rsa_pkcs8_rejects_an_oversized_modulus_before_key_validation() {
        use pkcs8::der::{
            asn1::{AnyRef, OctetStringRef, UintRef},
            Encode,
        };
        use pkcs8::{AlgorithmIdentifierRef, PrivateKeyInfoRef};

        // 1025 octets beginning with 1 is exactly 8193 significant bits. The
        // remaining integers need not describe a valid key: the modulus policy must
        // reject this borrowed ASN.1 view before RSA constructs or validates them.
        let modulus = vec![1u8; crate::MAX_RSA_BITS / 8 + 1];
        let one = [1u8];
        let three = [3u8];
        let raw = rsa::pkcs1::RsaPrivateKeyRef {
            modulus: UintRef::new(&modulus).unwrap(),
            public_exponent: UintRef::new(&three).unwrap(),
            private_exponent: UintRef::new(&one).unwrap(),
            prime1: UintRef::new(&one).unwrap(),
            prime2: UintRef::new(&one).unwrap(),
            exponent1: UintRef::new(&one).unwrap(),
            exponent2: UintRef::new(&one).unwrap(),
            coefficient: UintRef::new(&one).unwrap(),
            other_prime_infos: None,
        }
        .to_der()
        .unwrap();
        let algorithm = AlgorithmIdentifierRef {
            oid: OID_RSA,
            parameters: Some(AnyRef::NULL),
        };
        let inner = OctetStringRef::new(&raw).unwrap();
        let der = PrivateKeyInfoRef::new(algorithm, inner).to_der().unwrap();

        let err = jwk_from_pkcs8_der(&der).unwrap_err().to_string();
        assert!(err.contains("8193") && err.contains("maximum"), "{err}");
    }

    /// Neither importer may silently discard the PSS-only identity or
    /// parameter restrictions, even when the inner RSA material is valid.
    #[test]
    fn rsa_pss_oid_wrapped_keys_rejected() {
        use pkcs8::der::{
            asn1::{AnyRef, BitStringRef, OctetStringRef},
            Encode,
        };
        use pkcs8::spki::SubjectPublicKeyInfoRef;
        use pkcs8::{AlgorithmIdentifierRef, PrivateKeyInfoRef};
        use rsa::pkcs1::{EncodeRsaPrivateKey, EncodeRsaPublicKey};

        let sk = rsa::PrivateKey::new(&mut rng(), 2048).unwrap();
        let pk = sk.to_public_key();

        let pkcs1_priv = sk.to_pkcs1_der().unwrap();
        let pkcs1_pub = pk.to_pkcs1_der().unwrap();
        let default_params = rsa::pkcs1::RsaPssParamsRef::default().to_der().unwrap();
        let sha256_params = rsa::pkcs1::RsaPssParamsRef::new::<sha2::Sha256>(32)
            .to_der()
            .unwrap();
        let sha512_params = rsa::pkcs1::RsaPssParamsRef::new::<sha2::Sha512>(64)
            .to_der()
            .unwrap();

        for (label, parameters) in [
            ("absent", None),
            (
                "default sequence",
                Some(AnyRef::from_der(&default_params).unwrap()),
            ),
            ("SHA-256", Some(AnyRef::from_der(&sha256_params).unwrap())),
            ("SHA-512", Some(AnyRef::from_der(&sha512_params).unwrap())),
            ("invalid NULL", Some(AnyRef::NULL)),
        ] {
            let algorithm = AlgorithmIdentifierRef {
                oid: OID_RSA_PSS,
                parameters,
            };
            let private_key = OctetStringRef::new(pkcs1_priv.as_bytes()).unwrap();
            let private = PrivateKeyInfoRef::new(algorithm, private_key)
                .to_der()
                .unwrap();
            let public = SubjectPublicKeyInfoRef {
                algorithm,
                subject_public_key: BitStringRef::from_bytes(pkcs1_pub.as_bytes()).unwrap(),
            }
            .to_der()
            .unwrap();

            for result in [jwk_from_pkcs8_der(&private), jwk_from_spki_der(&public)] {
                assert!(
                    matches!(result, Err(JoseError::Key(ref message))
                    if message.contains("cannot preserve their restrictions")),
                    "PSS parameters {label} must be rejected: {result:?}"
                );
            }
        }
    }

    #[test]
    fn ec_p256_pkcs8_spki_roundtrip_es256() {
        let sk = p256::ecdsa::SigningKey::generate_from_rng(&mut rng());
        let priv_der = sk.to_pkcs8_der().unwrap();
        let pub_der = sk.verifying_key().to_public_key_der().unwrap();
        der_roundtrip("ES256", priv_der.as_bytes(), pub_der.as_bytes());
    }

    #[test]
    fn ec_p384_pkcs8_spki_roundtrip_es384() {
        let sk = p384::ecdsa::SigningKey::generate_from_rng(&mut rng());
        let priv_der = sk.to_pkcs8_der().unwrap();
        let pub_der = sk.verifying_key().to_public_key_der().unwrap();
        der_roundtrip("ES384", priv_der.as_bytes(), pub_der.as_bytes());
    }

    #[test]
    fn ec_p521_pkcs8_spki_roundtrip_es512() {
        // p521 ECDSA keys don't implement the pkcs8/spki encoders directly;
        // round-trip the DER through the curve key types.
        let secret = p521::SecretKey::generate_from_rng(&mut rng());
        let public = secret.public_key();
        let priv_der = secret.to_pkcs8_der().unwrap();
        let pub_der = public.to_public_key_der().unwrap();
        der_roundtrip("ES512", priv_der.as_bytes(), pub_der.as_bytes());
    }

    #[test]
    fn ed25519_pkcs8_spki_roundtrip_eddsa() {
        use pkcs8::EncodePrivateKey;
        let sk = ed25519_dalek::SigningKey::generate(&mut rng());
        let priv_der = sk.to_pkcs8_der().unwrap();
        let pub_der = sk.verifying_key().to_public_key_der().unwrap();
        der_roundtrip("EdDSA", priv_der.as_bytes(), pub_der.as_bytes());
    }

    /// A public-only JWK imported from SPKI must not carry private material.
    #[test]
    fn spki_import_has_no_private_material() {
        let sk = p256::ecdsa::SigningKey::generate_from_rng(&mut rng());
        let pub_der = sk.verifying_key().to_public_key_der().unwrap();
        let jwk = jwk_from_spki_der(pub_der.as_bytes()).unwrap();
        assert!(jwk.d.is_none(), "SPKI import must not produce a private d");
        assert_eq!(jwk.kty, "EC");
        assert_eq!(jwk.crv.as_deref(), Some("P-256"));
    }

    /// A PKCS#8 import carries the private scalar.
    #[test]
    fn pkcs8_import_has_private_material() {
        let sk = p256::ecdsa::SigningKey::generate_from_rng(&mut rng());
        let priv_der = sk.to_pkcs8_der().unwrap();
        let jwk = jwk_from_pkcs8_der(priv_der.as_bytes()).unwrap();
        assert!(jwk.d.is_some(), "PKCS#8 import must produce a private d");
    }

    /// Garbage DER is rejected, not silently mishandled.
    #[test]
    fn invalid_der_is_rejected() {
        let err = jwk_from_pkcs8_der(b"not der at all")
            .unwrap_err()
            .to_string();
        assert!(err.contains("PKCS#8"), "unexpected: {err}");
        let err2 = jwk_from_spki_der(b"not der at all")
            .unwrap_err()
            .to_string();
        assert!(err2.contains("SPKI"), "unexpected: {err2}");
    }
}