jose-rs 0.7.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
//! 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 (EdDSA).

use p521::elliptic_curve::sec1::ToEncodedPoint;
use pkcs8::der::Decode;
use pkcs8::spki::{DecodePublicKey, EncodePublicKey, SubjectPublicKeyInfoRef};
use pkcs8::{DecodePrivateKey, EncodePrivateKey, ObjectIdentifier, PrivateKeyInfo};
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 (RFC 8017 §A.2.3). Keys for PS* JWS algorithms are sometimes
// wrapped under this OID instead of plain rsaEncryption; the inner key
// material is the same PKCS#1 structure.
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");

fn ensure_rsa_min_bits(key: &rsa::RsaPublicKey) -> Result<()> {
    if key.n().bits() < crate::MIN_RSA_BITS {
        return Err(JoseError::Key(format!(
            "RSA key size {} bits is below the required minimum of {}",
            key.n().bits(),
            crate::MIN_RSA_BITS
        )));
    }
    Ok(())
}

/// 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. 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`).
///
/// 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> {
    let info = PrivateKeyInfo::from_der(der)
        .map_err(|e| JoseError::Key(format!("invalid PKCS#8 DER: {e}")))?;
    let oid = info.algorithm.oid;

    let sw = if oid == OID_RSA || oid == OID_RSA_PSS {
        // rsaEncryption-wrapped keys decode through the standard PKCS#8 path.
        // rsassaPss-wrapped keys carry the same PKCS#1 `RSAPrivateKey` in the
        // `privateKey` field, but the rsa crate's PKCS#8 decoder only accepts
        // the rsaEncryption OID, so parse the inner PKCS#1 structure directly.
        let key = if oid == OID_RSA {
            rsa::RsaPrivateKey::from_pkcs8_der(der)
                .map_err(|e| JoseError::Key(format!("invalid RSA PKCS#8 key: {e}")))?
        } else {
            use rsa::pkcs1::DecodeRsaPrivateKey;
            rsa::RsaPrivateKey::from_pkcs1_der(info.private_key)
                .map_err(|e| JoseError::Key(format!("invalid RSA-PSS 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 == 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 public keys. The returned JWK carries only
/// public components and pins no `alg`.
///
/// 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> {
    let spki = SubjectPublicKeyInfoRef::from_der(der)
        .map_err(|e| JoseError::Key(format!("invalid SPKI DER: {e}")))?;
    let oid = spki.algorithm.oid;

    let sw = if oid == OID_RSA || oid == OID_RSA_PSS {
        // As on the private side: rsaEncryption decodes through the SPKI path,
        // while an rssaPss-wrapped SPKI carries the same PKCS#1 `RSAPublicKey`
        // in its BIT STRING, which the rsa crate's SPKI decoder rejects.
        let key = if oid == OID_RSA {
            rsa::RsaPublicKey::from_public_key_der(der)
                .map_err(|e| JoseError::Key(format!("invalid RSA SPKI key: {e}")))?
        } else {
            use rsa::pkcs1::DecodeRsaPublicKey;
            let inner = spki.subject_public_key.as_bytes().ok_or_else(|| {
                JoseError::Key("RSA-PSS SPKI public key is not byte-aligned".into())
            })?;
            rsa::RsaPublicKey::from_pkcs1_der(inner)
                .map_err(|e| JoseError::Key(format!("invalid RSA-PSS 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 == 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)
}

// ── 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_encoded_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 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::RsaPrivateKey::new(&mut rand::thread_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::RsaPrivateKey::new(&mut rand::thread_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}"
        );
    }

    /// RSASSA-PSS-wrapped keys (OID 1.2.840.113549.1.1.10) import as RSA and
    /// round-trip through a PS256 sign/verify. The rsa crate's PKCS#8/SPKI
    /// decoders reject this OID, so the importer parses the inner PKCS#1.
    #[test]
    fn rsa_pss_oid_wrapped_keys_import() {
        use pkcs8::der::{asn1::BitStringRef, Encode};
        use pkcs8::spki::SubjectPublicKeyInfoRef;
        use pkcs8::{AlgorithmIdentifierRef, PrivateKeyInfo};
        use rsa::pkcs1::{EncodeRsaPrivateKey, EncodeRsaPublicKey};

        let sk = rsa::RsaPrivateKey::new(&mut rand::thread_rng(), 2048).unwrap();
        let pk = sk.to_public_key();

        // Wrap the PKCS#1 RSAPrivateKey in a PKCS#8 PrivateKeyInfo bearing the
        // rsassaPss OID.
        let pkcs1_priv = sk.to_pkcs1_der().unwrap();
        let priv_info = PrivateKeyInfo {
            algorithm: AlgorithmIdentifierRef {
                oid: OID_RSA_PSS,
                parameters: None,
            },
            private_key: pkcs1_priv.as_bytes(),
            public_key: None,
        };
        let priv_der = priv_info.to_der().unwrap();

        // Wrap the PKCS#1 RSAPublicKey in an SPKI bearing the rsassaPss OID.
        let pkcs1_pub = pk.to_pkcs1_der().unwrap();
        let spki = SubjectPublicKeyInfoRef {
            algorithm: AlgorithmIdentifierRef {
                oid: OID_RSA_PSS,
                parameters: None,
            },
            subject_public_key: BitStringRef::from_bytes(pkcs1_pub.as_bytes()).unwrap(),
        };
        let pub_der = spki.to_der().unwrap();

        der_roundtrip("PS256", &priv_der, &pub_der);
    }

    #[test]
    fn ec_p256_pkcs8_spki_roundtrip_es256() {
        let sk = p256::ecdsa::SigningKey::random(&mut rand::thread_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::random(&mut rand::thread_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::random(&mut rand::thread_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 rand::thread_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::random(&mut rand::thread_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::random(&mut rand::thread_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}");
    }
}