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
//! JOSE algorithm identifiers and mapping to kryptering enums.
//!
//! Parse case-sensitive wire names from configuration or a JOSE header:
//!
//! ```
//! use jose_rs::{JweAlgorithm, JweEncryption, JwsAlgorithm};
//!
//! let signature: JwsAlgorithm = "Ed448".parse()?;
//! let key_management: JweAlgorithm = "RSA-OAEP-256".parse()?;
//! let encryption: JweEncryption = "A256GCM".parse()?;
//! # Ok::<(), jose_rs::JoseError>(())
//! ```
//!
//! Parsing identifies the algorithm. Verification and decryption still require
//! the caller's algorithm policy and a suitable key.

use crate::error::{JoseError, Result};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

// ---------------------------------------------------------------------------
// JWS signature algorithms (RFC 7518 ยง3)
// ---------------------------------------------------------------------------

/// JWS signature algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum JwsAlgorithm {
    /// HMAC using SHA-256
    HS256,
    /// HMAC using SHA-384
    HS384,
    /// HMAC using SHA-512
    HS512,
    /// RSASSA-PKCS1-v1_5 using SHA-256
    RS256,
    /// RSASSA-PKCS1-v1_5 using SHA-384
    RS384,
    /// RSASSA-PKCS1-v1_5 using SHA-512
    RS512,
    /// RSASSA-PSS using SHA-256
    PS256,
    /// RSASSA-PSS using SHA-384
    PS384,
    /// RSASSA-PSS using SHA-512
    PS512,
    /// ECDSA using P-256 and SHA-256
    ES256,
    /// ECDSA using P-384 and SHA-384
    ES384,
    /// ECDSA using P-521 and SHA-512
    ES512,
    /// Legacy curve-dependent EdDSA identifier (Ed25519 or Ed448).
    /// Distinct from fully specified names in application algorithm allowlists.
    EdDSA,
    /// Fully specified Ed25519 identifier (RFC 9864 section 2.2).
    /// Uses the same primitive as [`Self::EdDSA`] without aliasing its wire name.
    Ed25519,
    /// Pure Ed448 with an empty context (RFC 9864 section 2.2).
    Ed448,
    /// ECDSA using secp256k1 and SHA-256
    ES256K,
    /// ML-DSA-44 (FIPS 204) post-quantum signature using the RFC 9964 AKP form.
    #[cfg(feature = "post-quantum")]
    #[serde(rename = "ML-DSA-44")]
    MlDsa44,
    /// ML-DSA-65 (FIPS 204) post-quantum signature using the RFC 9964 AKP form.
    #[cfg(feature = "post-quantum")]
    #[serde(rename = "ML-DSA-65")]
    MlDsa65,
    /// ML-DSA-87 (FIPS 204) post-quantum signature using the RFC 9964 AKP form.
    #[cfg(feature = "post-quantum")]
    #[serde(rename = "ML-DSA-87")]
    MlDsa87,
    /// Composite ML-DSA-44 and ECDSA P-256 from draft-ietf-jose-pq-composite-sigs-07.
    #[cfg(feature = "post-quantum")]
    #[serde(rename = "ML-DSA-44-ES256")]
    MlDsa44Es256,
    /// Composite ML-DSA-65 and ECDSA P-256 from draft-ietf-jose-pq-composite-sigs-07.
    #[cfg(feature = "post-quantum")]
    #[serde(rename = "ML-DSA-65-ES256")]
    MlDsa65Es256,
    /// Composite ML-DSA-65 and ECDSA P-384 from draft-ietf-jose-pq-composite-sigs-07.
    #[cfg(feature = "post-quantum")]
    #[serde(rename = "ML-DSA-65-ES384")]
    MlDsa65Es384,
    /// Composite ML-DSA-87 and ECDSA P-384 from draft-ietf-jose-pq-composite-sigs-07.
    #[cfg(feature = "post-quantum")]
    #[serde(rename = "ML-DSA-87-ES384")]
    MlDsa87Es384,
    /// Composite ML-DSA-44 and Ed25519 from draft-ietf-jose-pq-composite-sigs-07.
    #[cfg(feature = "post-quantum")]
    #[serde(rename = "ML-DSA-44-Ed25519")]
    MlDsa44Ed25519,
    /// No digital signature (DANGEROUS -- only available with the `deprecated` feature)
    #[cfg(feature = "deprecated")]
    None,
}

impl JwsAlgorithm {
    /// Map to the corresponding kryptering signature algorithm.
    ///
    /// Returns `Err` for algorithms that kryptering does not yet support
    /// (ES256K) or that have no meaningful cryptographic operation (None).
    /// Without key context, `EdDSA` retains its historical Ed25519 mapping.
    /// JWK APIs dispatch it on the key curve; raw Ed448 signers/verifiers also
    /// accept `EdDSA`. Use exact JOSE enum values for application allowlists.
    pub fn to_crypto(self) -> Result<kryptering::SignatureAlgorithm> {
        use kryptering::{EcCurve, HashAlgorithm, SignatureAlgorithm};
        match self {
            Self::HS256 => Ok(SignatureAlgorithm::Hmac(HashAlgorithm::Sha256)),
            Self::HS384 => Ok(SignatureAlgorithm::Hmac(HashAlgorithm::Sha384)),
            Self::HS512 => Ok(SignatureAlgorithm::Hmac(HashAlgorithm::Sha512)),
            Self::RS256 => Ok(SignatureAlgorithm::RsaPkcs1v15(HashAlgorithm::Sha256)),
            Self::RS384 => Ok(SignatureAlgorithm::RsaPkcs1v15(HashAlgorithm::Sha384)),
            Self::RS512 => Ok(SignatureAlgorithm::RsaPkcs1v15(HashAlgorithm::Sha512)),
            Self::PS256 => Ok(SignatureAlgorithm::RsaPss(HashAlgorithm::Sha256)),
            Self::PS384 => Ok(SignatureAlgorithm::RsaPss(HashAlgorithm::Sha384)),
            Self::PS512 => Ok(SignatureAlgorithm::RsaPss(HashAlgorithm::Sha512)),
            Self::ES256 => Ok(SignatureAlgorithm::Ecdsa(
                EcCurve::P256,
                HashAlgorithm::Sha256,
            )),
            Self::ES384 => Ok(SignatureAlgorithm::Ecdsa(
                EcCurve::P384,
                HashAlgorithm::Sha384,
            )),
            Self::ES512 => Ok(SignatureAlgorithm::Ecdsa(
                EcCurve::P521,
                HashAlgorithm::Sha512,
            )),
            Self::EdDSA | Self::Ed25519 => Ok(SignatureAlgorithm::Ed25519),
            Self::Ed448 => Ok(SignatureAlgorithm::Ed448),
            Self::ES256K => Err(JoseError::UnsupportedAlgorithm(
                "ES256K (secp256k1) is not yet supported by kryptering".into(),
            )),
            #[cfg(feature = "post-quantum")]
            Self::MlDsa44 => Ok(SignatureAlgorithm::MlDsa(kryptering::MlDsaVariant::MlDsa44)),
            #[cfg(feature = "post-quantum")]
            Self::MlDsa65 => Ok(SignatureAlgorithm::MlDsa(kryptering::MlDsaVariant::MlDsa65)),
            #[cfg(feature = "post-quantum")]
            Self::MlDsa87 => Ok(SignatureAlgorithm::MlDsa(kryptering::MlDsaVariant::MlDsa87)),
            #[cfg(feature = "post-quantum")]
            Self::MlDsa44Es256 => Ok(SignatureAlgorithm::CompositeMlDsa(
                kryptering::CompositeMlDsaVariant::MlDsa44Es256,
            )),
            #[cfg(feature = "post-quantum")]
            Self::MlDsa65Es256 => Ok(SignatureAlgorithm::CompositeMlDsa(
                kryptering::CompositeMlDsaVariant::MlDsa65Es256,
            )),
            #[cfg(feature = "post-quantum")]
            Self::MlDsa65Es384 => Ok(SignatureAlgorithm::CompositeMlDsa(
                kryptering::CompositeMlDsaVariant::MlDsa65Es384,
            )),
            #[cfg(feature = "post-quantum")]
            Self::MlDsa87Es384 => Ok(SignatureAlgorithm::CompositeMlDsa(
                kryptering::CompositeMlDsaVariant::MlDsa87Es384,
            )),
            #[cfg(feature = "post-quantum")]
            Self::MlDsa44Ed25519 => Ok(SignatureAlgorithm::CompositeMlDsa(
                kryptering::CompositeMlDsaVariant::MlDsa44Ed25519,
            )),
            #[cfg(feature = "deprecated")]
            Self::None => Err(JoseError::UnsupportedAlgorithm(
                "\"none\" algorithm has no cryptographic operation".into(),
            )),
        }
    }

    /// Resolve a JOSE wire algorithm against a concrete backend primitive.
    /// EdDSA is polymorphic; explicit names remain bound to one curve.
    pub(crate) fn matches_crypto(self, actual: kryptering::SignatureAlgorithm) -> Result<bool> {
        if self == Self::EdDSA && actual == kryptering::SignatureAlgorithm::Ed448 {
            return Ok(true);
        }
        Ok(self.to_crypto()? == actual)
    }

    /// Select the primitive using the JWK curve for legacy EdDSA.
    pub(crate) fn crypto_for_jwk(
        self,
        jwk: &crate::jwk::Jwk,
    ) -> Result<kryptering::SignatureAlgorithm> {
        if self == Self::EdDSA && jwk.kty == "OKP" && jwk.crv.as_deref() == Some("Ed448") {
            return Ok(kryptering::SignatureAlgorithm::Ed448);
        }
        self.to_crypto()
    }

    /// Parse an exact JOSE `alg` name, also available through [`str::parse`].
    ///
    /// # Errors
    ///
    /// Returns [`JoseError::UnsupportedAlgorithm`] if this build does not recognize the name.
    #[allow(
        clippy::should_implement_trait,
        reason = "retain the inherent API for callers without FromStr in scope"
    )]
    pub fn from_str(s: &str) -> Result<Self> {
        match s {
            "HS256" => Ok(Self::HS256),
            "HS384" => Ok(Self::HS384),
            "HS512" => Ok(Self::HS512),
            "RS256" => Ok(Self::RS256),
            "RS384" => Ok(Self::RS384),
            "RS512" => Ok(Self::RS512),
            "PS256" => Ok(Self::PS256),
            "PS384" => Ok(Self::PS384),
            "PS512" => Ok(Self::PS512),
            "ES256" => Ok(Self::ES256),
            "ES384" => Ok(Self::ES384),
            "ES512" => Ok(Self::ES512),
            "EdDSA" => Ok(Self::EdDSA),
            "Ed25519" => Ok(Self::Ed25519),
            "Ed448" => Ok(Self::Ed448),
            "ES256K" => Ok(Self::ES256K),
            #[cfg(feature = "post-quantum")]
            "ML-DSA-44" => Ok(Self::MlDsa44),
            #[cfg(feature = "post-quantum")]
            "ML-DSA-65" => Ok(Self::MlDsa65),
            #[cfg(feature = "post-quantum")]
            "ML-DSA-87" => Ok(Self::MlDsa87),
            #[cfg(feature = "post-quantum")]
            "ML-DSA-44-ES256" => Ok(Self::MlDsa44Es256),
            #[cfg(feature = "post-quantum")]
            "ML-DSA-65-ES256" => Ok(Self::MlDsa65Es256),
            #[cfg(feature = "post-quantum")]
            "ML-DSA-65-ES384" => Ok(Self::MlDsa65Es384),
            #[cfg(feature = "post-quantum")]
            "ML-DSA-87-ES384" => Ok(Self::MlDsa87Es384),
            #[cfg(feature = "post-quantum")]
            "ML-DSA-44-Ed25519" => Ok(Self::MlDsa44Ed25519),
            #[cfg(feature = "deprecated")]
            "none" => Ok(Self::None),
            other => Err(JoseError::UnsupportedAlgorithm(other.to_string())),
        }
    }

    /// Return the `alg` header string.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::HS256 => "HS256",
            Self::HS384 => "HS384",
            Self::HS512 => "HS512",
            Self::RS256 => "RS256",
            Self::RS384 => "RS384",
            Self::RS512 => "RS512",
            Self::PS256 => "PS256",
            Self::PS384 => "PS384",
            Self::PS512 => "PS512",
            Self::ES256 => "ES256",
            Self::ES384 => "ES384",
            Self::ES512 => "ES512",
            Self::EdDSA => "EdDSA",
            Self::Ed25519 => "Ed25519",
            Self::Ed448 => "Ed448",
            Self::ES256K => "ES256K",
            #[cfg(feature = "post-quantum")]
            Self::MlDsa44 => "ML-DSA-44",
            #[cfg(feature = "post-quantum")]
            Self::MlDsa65 => "ML-DSA-65",
            #[cfg(feature = "post-quantum")]
            Self::MlDsa87 => "ML-DSA-87",
            #[cfg(feature = "post-quantum")]
            Self::MlDsa44Es256 => "ML-DSA-44-ES256",
            #[cfg(feature = "post-quantum")]
            Self::MlDsa65Es256 => "ML-DSA-65-ES256",
            #[cfg(feature = "post-quantum")]
            Self::MlDsa65Es384 => "ML-DSA-65-ES384",
            #[cfg(feature = "post-quantum")]
            Self::MlDsa87Es384 => "ML-DSA-87-ES384",
            #[cfg(feature = "post-quantum")]
            Self::MlDsa44Ed25519 => "ML-DSA-44-Ed25519",
            #[cfg(feature = "deprecated")]
            Self::None => "none",
        }
    }
}

impl FromStr for JwsAlgorithm {
    type Err = JoseError;

    fn from_str(s: &str) -> Result<Self> {
        JwsAlgorithm::from_str(s)
    }
}

impl std::fmt::Display for JwsAlgorithm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

// ---------------------------------------------------------------------------
// JWE key management algorithms (RFC 7518 ยง4)
// ---------------------------------------------------------------------------

/// JWE key management algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum JweAlgorithm {
    /// Direct use of a shared symmetric key
    #[serde(rename = "dir")]
    Dir,
    /// AES Key Wrap (128-bit)
    A128KW,
    /// AES Key Wrap (192-bit)
    A192KW,
    /// AES Key Wrap (256-bit)
    A256KW,
    /// AES GCM key wrapping with a 128-bit key (RFC 7518 ยง4.7)
    #[serde(rename = "A128GCMKW")]
    A128Gcmkw,
    /// AES GCM key wrapping with a 192-bit key (RFC 7518 ยง4.7)
    #[serde(rename = "A192GCMKW")]
    A192Gcmkw,
    /// AES GCM key wrapping with a 256-bit key (RFC 7518 ยง4.7)
    #[serde(rename = "A256GCMKW")]
    A256Gcmkw,
    /// RSAES-OAEP using default parameters (SHA-1 โ€” only available with the `rsa-oaep` feature)
    #[cfg(feature = "rsa-oaep")]
    #[serde(rename = "RSA-OAEP")]
    RsaOaep,
    /// RSAES-OAEP using SHA-256 and MGF1 with SHA-256
    #[serde(rename = "RSA-OAEP-256")]
    RsaOaep256,
    /// ECDH-ES
    #[serde(rename = "ECDH-ES")]
    EcdhEs,
    /// ECDH-ES + A128KW
    #[serde(rename = "ECDH-ES+A128KW")]
    EcdhEsA128kw,
    /// ECDH-ES + A192KW
    #[serde(rename = "ECDH-ES+A192KW")]
    EcdhEsA192kw,
    /// ECDH-ES + A256KW
    #[serde(rename = "ECDH-ES+A256KW")]
    EcdhEsA256kw,
    /// PBES2-HS256+A128KW
    #[serde(rename = "PBES2-HS256+A128KW")]
    Pbes2Hs256A128kw,
    /// PBES2-HS384+A192KW
    #[serde(rename = "PBES2-HS384+A192KW")]
    Pbes2Hs384A192kw,
    /// PBES2-HS512+A256KW
    #[serde(rename = "PBES2-HS512+A256KW")]
    Pbes2Hs512A256kw,
}

impl JweAlgorithm {
    /// Parse an exact JOSE `alg` name, also available through [`str::parse`].
    ///
    /// # Errors
    ///
    /// Returns [`JoseError::UnsupportedAlgorithm`] if this build does not recognize the name.
    #[allow(
        clippy::should_implement_trait,
        reason = "retain the inherent API for callers without FromStr in scope"
    )]
    pub fn from_str(s: &str) -> Result<Self> {
        match s {
            "dir" => Ok(Self::Dir),
            "A128KW" => Ok(Self::A128KW),
            "A192KW" => Ok(Self::A192KW),
            "A256KW" => Ok(Self::A256KW),
            "A128GCMKW" => Ok(Self::A128Gcmkw),
            "A192GCMKW" => Ok(Self::A192Gcmkw),
            "A256GCMKW" => Ok(Self::A256Gcmkw),
            #[cfg(feature = "rsa-oaep")]
            "RSA-OAEP" => Ok(Self::RsaOaep),
            "RSA-OAEP-256" => Ok(Self::RsaOaep256),
            "ECDH-ES" => Ok(Self::EcdhEs),
            "ECDH-ES+A128KW" => Ok(Self::EcdhEsA128kw),
            "ECDH-ES+A192KW" => Ok(Self::EcdhEsA192kw),
            "ECDH-ES+A256KW" => Ok(Self::EcdhEsA256kw),
            "PBES2-HS256+A128KW" => Ok(Self::Pbes2Hs256A128kw),
            "PBES2-HS384+A192KW" => Ok(Self::Pbes2Hs384A192kw),
            "PBES2-HS512+A256KW" => Ok(Self::Pbes2Hs512A256kw),
            other => Err(JoseError::UnsupportedAlgorithm(other.to_string())),
        }
    }

    /// Return the `alg` header string.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Dir => "dir",
            Self::A128KW => "A128KW",
            Self::A192KW => "A192KW",
            Self::A256KW => "A256KW",
            Self::A128Gcmkw => "A128GCMKW",
            Self::A192Gcmkw => "A192GCMKW",
            Self::A256Gcmkw => "A256GCMKW",
            #[cfg(feature = "rsa-oaep")]
            Self::RsaOaep => "RSA-OAEP",
            Self::RsaOaep256 => "RSA-OAEP-256",
            Self::EcdhEs => "ECDH-ES",
            Self::EcdhEsA128kw => "ECDH-ES+A128KW",
            Self::EcdhEsA192kw => "ECDH-ES+A192KW",
            Self::EcdhEsA256kw => "ECDH-ES+A256KW",
            Self::Pbes2Hs256A128kw => "PBES2-HS256+A128KW",
            Self::Pbes2Hs384A192kw => "PBES2-HS384+A192KW",
            Self::Pbes2Hs512A256kw => "PBES2-HS512+A256KW",
        }
    }
}

impl FromStr for JweAlgorithm {
    type Err = JoseError;

    fn from_str(s: &str) -> Result<Self> {
        JweAlgorithm::from_str(s)
    }
}

// ---------------------------------------------------------------------------
// JWE content encryption algorithms (RFC 7518 ยง5)
// ---------------------------------------------------------------------------

/// JWE content encryption algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum JweEncryption {
    /// AES-CBC using 128-bit key with HMAC SHA-256
    #[serde(rename = "A128CBC-HS256")]
    A128CbcHs256,
    /// AES-CBC using 192-bit key with HMAC SHA-384
    #[serde(rename = "A192CBC-HS384")]
    A192CbcHs384,
    /// AES-CBC using 256-bit key with HMAC SHA-512
    #[serde(rename = "A256CBC-HS512")]
    A256CbcHs512,
    /// AES-GCM using 128-bit key
    A128GCM,
    /// AES-GCM using 192-bit key
    A192GCM,
    /// AES-GCM using 256-bit key
    A256GCM,
}

impl JweEncryption {
    /// Content Encryption Key size in bytes.
    pub fn cek_size(self) -> usize {
        match self {
            Self::A128CbcHs256 => 32, // 128-bit AES + 128-bit HMAC
            Self::A192CbcHs384 => 48, // 192-bit AES + 192-bit HMAC
            Self::A256CbcHs512 => 64, // 256-bit AES + 256-bit HMAC
            Self::A128GCM => 16,
            Self::A192GCM => 24,
            Self::A256GCM => 32,
        }
    }

    /// Parse an exact JOSE `enc` name, also available through [`str::parse`].
    ///
    /// # Errors
    ///
    /// Returns [`JoseError::UnsupportedAlgorithm`] if this build does not recognize the name.
    #[allow(
        clippy::should_implement_trait,
        reason = "retain the inherent API for callers without FromStr in scope"
    )]
    pub fn from_str(s: &str) -> Result<Self> {
        match s {
            "A128CBC-HS256" => Ok(Self::A128CbcHs256),
            "A192CBC-HS384" => Ok(Self::A192CbcHs384),
            "A256CBC-HS512" => Ok(Self::A256CbcHs512),
            "A128GCM" => Ok(Self::A128GCM),
            "A192GCM" => Ok(Self::A192GCM),
            "A256GCM" => Ok(Self::A256GCM),
            other => Err(JoseError::UnsupportedAlgorithm(other.to_string())),
        }
    }

    /// Return the `enc` header string.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::A128CbcHs256 => "A128CBC-HS256",
            Self::A192CbcHs384 => "A192CBC-HS384",
            Self::A256CbcHs512 => "A256CBC-HS512",
            Self::A128GCM => "A128GCM",
            Self::A192GCM => "A192GCM",
            Self::A256GCM => "A256GCM",
        }
    }
}

impl FromStr for JweEncryption {
    type Err = JoseError;

    fn from_str(s: &str) -> Result<Self> {
        JweEncryption::from_str(s)
    }
}

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

    #[test]
    fn es256k_from_str() {
        let alg = JwsAlgorithm::from_str("ES256K").unwrap();
        assert_eq!(alg, JwsAlgorithm::ES256K);
    }

    #[test]
    fn es256k_as_str() {
        assert_eq!(JwsAlgorithm::ES256K.as_str(), "ES256K");
    }

    #[test]
    fn es256k_to_crypto_returns_error() {
        let result = JwsAlgorithm::ES256K.to_crypto();
        assert!(result.is_err());
    }

    #[test]
    fn es256k_roundtrip() {
        let alg = JwsAlgorithm::from_str(JwsAlgorithm::ES256K.as_str()).unwrap();
        assert_eq!(alg, JwsAlgorithm::ES256K);
    }

    #[test]
    fn existing_algorithms_to_crypto_still_work() {
        // Verify the signature change didn't break existing algorithms.
        assert!(JwsAlgorithm::HS256.to_crypto().is_ok());
        assert!(JwsAlgorithm::RS256.to_crypto().is_ok());
        assert!(JwsAlgorithm::ES256.to_crypto().is_ok());
        assert!(JwsAlgorithm::EdDSA.to_crypto().is_ok());
    }

    #[cfg(feature = "post-quantum")]
    #[test]
    fn composite_algorithms_roundtrip_and_map_to_kryptering() {
        use kryptering::CompositeMlDsaVariant as Variant;

        let cases = [
            (
                "ML-DSA-44-ES256",
                JwsAlgorithm::MlDsa44Es256,
                Variant::MlDsa44Es256,
            ),
            (
                "ML-DSA-65-ES256",
                JwsAlgorithm::MlDsa65Es256,
                Variant::MlDsa65Es256,
            ),
            (
                "ML-DSA-65-ES384",
                JwsAlgorithm::MlDsa65Es384,
                Variant::MlDsa65Es384,
            ),
            (
                "ML-DSA-87-ES384",
                JwsAlgorithm::MlDsa87Es384,
                Variant::MlDsa87Es384,
            ),
            (
                "ML-DSA-44-Ed25519",
                JwsAlgorithm::MlDsa44Ed25519,
                Variant::MlDsa44Ed25519,
            ),
        ];

        for (name, jose, crypto) in cases {
            assert_eq!(JwsAlgorithm::from_str(name).unwrap(), jose);
            assert_eq!(jose.as_str(), name);
            assert_eq!(
                jose.to_crypto().unwrap(),
                kryptering::SignatureAlgorithm::CompositeMlDsa(crypto)
            );
            assert_eq!(serde_json::to_string(&jose).unwrap(), format!("\"{name}\""));
        }
    }
}