Skip to main content

script_webcrypto/subtlecrypto/
ml_kem_operation.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use js::context::JSContext;
6use ml_dsa::KeyExport;
7use ml_kem::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
8use ml_kem::{
9    Decapsulate, DecapsulationKey, Encapsulate, EncapsulationKey, Generate, KeyInit, MlKem512,
10    MlKem768, MlKem1024, TryKeyInit,
11};
12use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
13    CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage,
14};
15use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::{JsonWebKey, KeyFormat};
16use script_bindings::error::Error;
17use script_bindings::root::DomRoot;
18use script_bindings::str::DOMString;
19use script_bindings::trace::RootedTraceableBox;
20
21use crate::cryptokey::{CryptoKey, Handle, KeyUsageSliceHelper};
22use crate::subtlecrypto::{
23    Algorithm, CryptoAlgorithm, EncapsulatedBits, ExportedKey, JsonWebKeyHelper, JwkStringField,
24    KeyAlgorithm, KeyAlgorithmAndDerivatives,
25};
26use crate::traits::Equivalence;
27
28/// <https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-encapsulate>
29pub(crate) fn encapsulate<D: Equivalence>(
30    normalized_algorithm: &Algorithm,
31    key: &CryptoKey<D>,
32) -> Result<EncapsulatedBits, Error> {
33    // Step 1. If the [[type]] internal slot of key is not "public", then throw an
34    // InvalidAccessError.
35    key.ensure_type(KeyType::Public)?;
36
37    // Step 2. Perform the encapsulation key check described in Section 7.2 of [FIPS-203] with the
38    // parameter set indicated by the name member of algorithm, using the key represented by the
39    // [[handle]] internal slot of key as the ek input parameter.
40    // Step 3. If the encapsulation key check failed, throw an OperationError.
41    // Step 4. Let sharedKey and ciphertext be the outputs that result from performing the
42    // ML-KEM.Encaps function described in Section 7.2 of [FIPS-203] with the parameter set
43    // indicated by the name member of algorithm, using the key represented by the [[handle]]
44    // internal slot of key as the ek input parameter.
45    // Step 5. If the ML-KEM.Encaps function returned an error, throw an OperationError.
46    let (shared_key, ciphertext) = match normalized_algorithm.name {
47        CryptoAlgorithm::MlKem512 => {
48            let Handle::MlKem512PublicKey(public_key) = key.handle() else {
49                return Err(Error::Operation(Some(
50                    "The key handle is not representing an ML-KEM-512 public key".into(),
51                )));
52            };
53            let (ciphertext, shared_key) = public_key.encapsulate();
54            (shared_key.to_vec(), ciphertext.to_vec())
55        },
56        CryptoAlgorithm::MlKem768 => {
57            let Handle::MlKem768PublicKey(public_key) = key.handle() else {
58                return Err(Error::Operation(Some(
59                    "The key handle is not representing an ML-KEM-768 public key".into(),
60                )));
61            };
62            let (ciphertext, shared_key) = public_key.encapsulate();
63            (shared_key.to_vec(), ciphertext.to_vec())
64        },
65        CryptoAlgorithm::MlKem1024 => {
66            let Handle::MlKem1024PublicKey(public_key) = key.handle() else {
67                return Err(Error::Operation(Some(
68                    "The key handle is not representing an ML-KEM-1024 public key".into(),
69                )));
70            };
71            let (ciphertext, shared_key) = public_key.encapsulate();
72            (shared_key.to_vec(), ciphertext.to_vec())
73        },
74        name => {
75            return Err(Error::NotSupported(Some(format!(
76                "{} is not an ML-KEM algorithm",
77                name.as_str()
78            ))));
79        },
80    };
81
82    // Step 6. Let result be a new EncapsulatedBits dictionary.
83    // Step 7. Set the sharedKey attribute of result to the result of creating an ArrayBuffer
84    // containing sharedKey.
85    // Step 8. Set the ciphertext attribute of result to the result of creating an ArrayBuffer
86    // containing ciphertext.
87    let result = EncapsulatedBits {
88        shared_key: Some(shared_key.into()),
89        ciphertext: Some(ciphertext),
90    };
91
92    // Step 9. Return result.
93    Ok(result)
94}
95
96/// <https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-decapsulate>
97pub(crate) fn decapsulate<D: Equivalence>(
98    normalized_algorithm: &Algorithm,
99    key: &CryptoKey<D>,
100    ciphertext: &[u8],
101) -> Result<Vec<u8>, Error> {
102    // Step 1. If the [[type]] internal slot of key is not "private", then throw an
103    // InvalidAccessError.
104    key.ensure_type(KeyType::Private)?;
105
106    // Step 2. Perform the decapsulation input check described in Section 7.3 of [FIPS-203] with
107    // the parameter set indicated by the name member of algorithm, using the key represented by
108    // the [[handle]] internal slot of key as the dk input parameter, and ciphertext as the c input
109    // parameter.
110    // Step 3. If the decapsulation input check failed, throw an OperationError.
111    // Step 4. Let sharedKey be the output that results from performing the ML-KEM.Decaps function
112    // described in Section 7.3 of [FIPS-203] with the parameter set indicated by the name member
113    // of algorithm, using the key represented by the [[handle]] internal slot of key as the dk
114    // input parameter, and ciphertext as the c input parameter.
115    let shared_key = match normalized_algorithm.name {
116        CryptoAlgorithm::MlKem512 => {
117            let Handle::MlKem512PrivateKey(private_key) = key.handle() else {
118                return Err(Error::Operation(Some(
119                    "The key handle is not representing an ML-KEM-512 private key".into(),
120                )));
121            };
122            private_key
123                .decapsulate_slice(ciphertext)
124                .map_err(|_| {
125                    Error::Operation(Some("Failed to perform ML-KEM decapsulation".into()))
126                })?
127                .to_vec()
128        },
129        CryptoAlgorithm::MlKem768 => {
130            let Handle::MlKem768PrivateKey(private_key) = key.handle() else {
131                return Err(Error::Operation(Some(
132                    "The key handle is not representing an ML-KEM-768 private key".into(),
133                )));
134            };
135            private_key
136                .decapsulate_slice(ciphertext)
137                .map_err(|_| {
138                    Error::Operation(Some("Failed to perform ML-KEM decapsulation".into()))
139                })?
140                .to_vec()
141        },
142        CryptoAlgorithm::MlKem1024 => {
143            let Handle::MlKem1024PrivateKey(private_key) = key.handle() else {
144                return Err(Error::Operation(Some(
145                    "The key handle is not representing an ML-KEM-1024 private key".into(),
146                )));
147            };
148            private_key
149                .decapsulate_slice(ciphertext)
150                .map_err(|_| {
151                    Error::Operation(Some("Failed to perform ML-KEM decapsulation".into()))
152                })?
153                .to_vec()
154        },
155        name => {
156            return Err(Error::NotSupported(Some(format!(
157                "{} is not an ML-KEM algorithm",
158                name.as_str()
159            ))));
160        },
161    };
162
163    // Step 5. Return sharedKey.
164    Ok(shared_key)
165}
166
167/// <https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-get-shared-key-length>
168pub(crate) fn get_shared_key_length() -> u32 {
169    // Step 1. Return 256.
170    256
171}
172
173/// <https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-generate-key>
174pub(crate) fn generate_key<D: Equivalence>(
175    cx: &mut JSContext,
176    global: &D::GlobalScope,
177    normalized_algorithm: &Algorithm,
178    extractable: bool,
179    usages: Vec<KeyUsage>,
180) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
181    // Step 1. If usages contains any entry which is not one of "encapsulateKey",
182    // "encapsulateBits", "decapsulateKey" or "decapsulateBits", then throw a SyntaxError.
183    usages.ensure_only_contain_entries_from(&[
184        KeyUsage::EncapsulateKey,
185        KeyUsage::EncapsulateBits,
186        KeyUsage::DecapsulateKey,
187        KeyUsage::DecapsulateBits,
188    ])?;
189
190    // Step 2. Generate an ML-KEM key pair, as described in Section 7.1 of [FIPS-203], with the
191    // parameter set indicated by the name member of normalizedAlgorithm.
192    // Step 3. If the key generation step fails, then throw an OperationError.
193    let (private_key_handle, public_key_handle) = match normalized_algorithm.name {
194        CryptoAlgorithm::MlKem512 => {
195            let decapsulation_key = DecapsulationKey::<MlKem512>::generate();
196            let encapsulation_key = decapsulation_key.encapsulation_key().clone();
197            (
198                Handle::MlKem512PrivateKey(decapsulation_key),
199                Handle::MlKem512PublicKey(encapsulation_key),
200            )
201        },
202        CryptoAlgorithm::MlKem768 => {
203            let decapsulation_key = DecapsulationKey::<MlKem768>::generate();
204            let encapsulation_key = decapsulation_key.encapsulation_key().clone();
205            (
206                Handle::MlKem768PrivateKey(decapsulation_key),
207                Handle::MlKem768PublicKey(encapsulation_key),
208            )
209        },
210        CryptoAlgorithm::MlKem1024 => {
211            let decapsulation_key = DecapsulationKey::<MlKem1024>::generate();
212            let encapsulation_key = decapsulation_key.encapsulation_key().clone();
213            (
214                Handle::MlKem1024PrivateKey(decapsulation_key),
215                Handle::MlKem1024PublicKey(encapsulation_key),
216            )
217        },
218        name => {
219            return Err(Error::NotSupported(Some(format!(
220                "{} is not an ML-KEM algorithm",
221                name.as_str()
222            ))));
223        },
224    };
225
226    // Step 4. Let algorithm be a new KeyAlgorithm object.
227    // Step 5. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
228    let algorithm = KeyAlgorithm {
229        name: normalized_algorithm.name,
230    };
231
232    // Step 6. Let publicKey be a new CryptoKey representing the encapsulation key of the generated
233    // key pair.
234    // Step 7. Set the [[type]] internal slot of publicKey to "public".
235    // Step 8. Set the [[algorithm]] internal slot of publicKey to algorithm.
236    // Step 9. Set the [[extractable]] internal slot of publicKey to true.
237    // Step 10. Set the [[usages]] internal slot of publicKey to be the usage intersection of
238    // usages and [ "encapsulateKey", "encapsulateBits" ].
239    let public_key = CryptoKey::new(
240        cx,
241        global,
242        KeyType::Public,
243        true,
244        KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm.clone()),
245        usages.usage_intersection(&[KeyUsage::EncapsulateKey, KeyUsage::EncapsulateBits]),
246        public_key_handle,
247    );
248
249    // Step 11. Let privateKey be a new CryptoKey representing the decapsulation key of the
250    // generated key pair.
251    // Step 12. Set the [[type]] internal slot of privateKey to "private".
252    // Step 13. Set the [[algorithm]] internal slot of privateKey to algorithm.
253    // Step 14. Set the [[extractable]] internal slot of privateKey to extractable.
254    // Step 15. Set the [[usages]] internal slot of privateKey to be the usage intersection of
255    // usages and [ "decapsulateKey", "decapsulateBits" ].
256    let private_key = CryptoKey::new(
257        cx,
258        global,
259        KeyType::Private,
260        extractable,
261        KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
262        usages.usage_intersection(&[KeyUsage::DecapsulateKey, KeyUsage::DecapsulateBits]),
263        private_key_handle,
264    );
265
266    // Step 16. Let result be a new CryptoKeyPair dictionary.
267    // Step 17. Set the publicKey attribute of result to be publicKey.
268    // Step 18. Set the privateKey attribute of result to be privateKey.
269    let result = RootedTraceableBox::new(CryptoKeyPair {
270        publicKey: Some(public_key.as_traced()),
271        privateKey: Some(private_key.as_traced()),
272    });
273
274    // Step 19. Return result.
275    Ok(result)
276}
277
278/// <https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-import-key>
279pub(crate) fn import_key<D: Equivalence>(
280    cx: &mut JSContext,
281    global: &D::GlobalScope,
282    normalized_algorithm: &Algorithm,
283    format: KeyFormat,
284    key_data: &[u8],
285    extractable: bool,
286    usages: Vec<KeyUsage>,
287) -> Result<DomRoot<CryptoKey<D>>, Error> {
288    // Step 1. Let keyData be the key data to be imported.
289
290    // Step 2.
291    let key = match format {
292        // If format is "spki":
293        KeyFormat::Spki => {
294            // Step 2.1. If usages contains an entry which is not "encapsulateKey" or
295            // "encapsulateBits" then throw a SyntaxError.
296            usages.ensure_only_contain_entries_from(&[
297                KeyUsage::EncapsulateKey,
298                KeyUsage::EncapsulateBits,
299            ])?;
300
301            // Step 2.2. Let spki be the result of running the parse a subjectPublicKeyInfo
302            // algorithm over keyData.
303            // Step 2.3. If an error occurred while parsing, then throw a DataError.
304            // Step 2.4.
305            // If the name member of normalizedAlgorithm is "ML-KEM-512":
306            //     Let expectedOid be id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1).
307            // If the name member of normalizedAlgorithm is "ML-KEM-768":
308            //     Let expectedOid be id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2).
309            // If the name member of normalizedAlgorithm is "ML-KEM-1024":
310            //     Let expectedOid be id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3).
311            // Otherwise:
312            //     throw a NotSupportedError.
313            // Step 2.5. If the algorithm object identifier field of the algorithm
314            // AlgorithmIdentifier field of spki is not equal to expectedOid, then throw a
315            // DataError.
316            // Step 2.6. If the parameters field of the algorithm AlgorithmIdentifier field of spki
317            // is present, then throw a DataError.
318            // Step 2.7. Let publicKey be the ML-KEM public key identified by the subjectPublicKey
319            // field of spki.
320            let public_key = match normalized_algorithm.name {
321                CryptoAlgorithm::MlKem512 => Handle::MlKem512PublicKey(
322                    EncapsulationKey::from_public_key_der(key_data).map_err(|_| {
323                        Error::Data(Some(
324                            "Failed to decode the ML-KEM-512 public key from SPKI format".into(),
325                        ))
326                    })?,
327                ),
328                CryptoAlgorithm::MlKem768 => Handle::MlKem768PublicKey(
329                    EncapsulationKey::from_public_key_der(key_data).map_err(|_| {
330                        Error::Data(Some(
331                            "Failed to decode the ML-KEM-768 public key from SPKI format".into(),
332                        ))
333                    })?,
334                ),
335                CryptoAlgorithm::MlKem1024 => Handle::MlKem1024PublicKey(
336                    EncapsulationKey::from_public_key_der(key_data).map_err(|_| {
337                        Error::Data(Some(
338                            "Failed to decode the ML-KEM-1024 public key from SPKI format".into(),
339                        ))
340                    })?,
341                ),
342                name => {
343                    return Err(Error::NotSupported(Some(format!(
344                        "{} is not an ML-KEM algorithm",
345                        name.as_str()
346                    ))));
347                },
348            };
349
350            // Step 2.8. Let key be a new CryptoKey that represents publicKey.
351            // Step 2.9. Set the [[type]] internal slot of key to "public"
352            // Step 2.10. Let algorithm be a new KeyAlgorithm.
353            // Step 2.11. Set the name attribute of algorithm to the name attribute of
354            // normalizedAlgorithm.
355            // Step 2.12. Set the [[algorithm]] internal slot of key to algorithm.
356            let algorithm = KeyAlgorithm {
357                name: normalized_algorithm.name,
358            };
359            CryptoKey::new(
360                cx,
361                global,
362                KeyType::Public,
363                extractable,
364                KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
365                usages.normalized_value(),
366                public_key,
367            )
368        },
369        // If format is "pkcs8":
370        KeyFormat::Pkcs8 => {
371            // Step 2.1. If usages contains an entry which is not "decapsulateKey" or
372            // "decapsulateBits" then throw a SyntaxError.
373            if usages
374                .iter()
375                .any(|usage| !matches!(usage, KeyUsage::DecapsulateKey | KeyUsage::DecapsulateBits))
376            {
377                return Err(Error::Syntax(Some(
378                    "Usages contains an entry which is not \"decapsulateKey\" or \
379                    \"decapsulateBits\""
380                        .into(),
381                )));
382            }
383
384            // Step 2.2. Let privateKeyInfo be the result of running the parse a privateKeyInfo
385            // algorithm over keyData.
386            // Step 2.3. If an error occurs while parsing, then throw a DataError.
387            // Step 2.4.
388            // If the name member of normalizedAlgorithm is "ML-KEM-512":
389            //     Let expectedOid be id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1).
390            //     Let asn1Structure be the ASN.1 ML-KEM-512-PrivateKey structure.
391            // If the name member of normalizedAlgorithm is "ML-KEM-768":
392            //     Let expectedOid be id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2).
393            //     Let asn1Structure be the ASN.1 ML-KEM-768-PrivateKey structure.
394            // If the name member of normalizedAlgorithm is "ML-KEM-1024":
395            //     Let expectedOid be id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3).
396            //     Let asn1Structure be the ASN.1 ML-KEM-1024-PrivateKey structure.
397            // Otherwise:
398            //     throw a NotSupportedError.
399            // Step 2.5. If the algorithm object identifier field of the privateKeyAlgorithm
400            // PrivateKeyAlgorithm field of privateKeyInfo is not equal to expectedOid, then throw
401            // a DataError.
402            // Step 2.6. If the parameters field of the privateKeyAlgorithm
403            // PrivateKeyAlgorithmIdentifier field of privateKeyInfo is present, then throw a
404            // DataError.
405            // Step 2.7. Let mlKemPrivateKey be the result of performing the parse an ASN.1
406            // structure algorithm, with data as the privateKey field of privateKeyInfo, structure
407            // as asn1Structure, and exactData set to true.
408            // Step 2.8. If an error occurred while parsing, then throw a DataError.
409            // Step 2.9. If mlKemPrivateKey represents an ML-KEM key in the expandedKey format, or
410            // if mlKemPrivateKey represents an ML-KEM key in the both format and the both format
411            // is not supported, throw a NotSupportedError.
412            // Step 2.10. If mlKemPrivateKey represents an ML-KEM key in the both format, and the
413            // seed field does not correspond to the expandedKey field, throw a DataError.
414            //
415            // NOTE: We do not support the `both` format.
416            let ml_kem_private_key = match normalized_algorithm.name {
417                CryptoAlgorithm::MlKem512 => Handle::MlKem512PrivateKey(
418                    DecapsulationKey::from_pkcs8_der(key_data).map_err(|_| {
419                        Error::Data(Some(
420                            "Failed to decode the ML-KEM-512 private key from PKCS#8 format".into(),
421                        ))
422                    })?,
423                ),
424                CryptoAlgorithm::MlKem768 => Handle::MlKem768PrivateKey(
425                    DecapsulationKey::from_pkcs8_der(key_data).map_err(|_| {
426                        Error::Data(Some(
427                            "Failed to decode the ML-KEM-768 private key from PKCS#8 format".into(),
428                        ))
429                    })?,
430                ),
431                CryptoAlgorithm::MlKem1024 => Handle::MlKem1024PrivateKey(
432                    DecapsulationKey::from_pkcs8_der(key_data).map_err(|_| {
433                        Error::Data(Some(
434                            "Failed to decode the ML-KEM-1024 private key from PKCS#8 format"
435                                .into(),
436                        ))
437                    })?,
438                ),
439                name => {
440                    return Err(Error::NotSupported(Some(format!(
441                        "{} is not an ML-KEM algorithm",
442                        name.as_str()
443                    ))));
444                },
445            };
446
447            // Step 2.11. Let key be a new CryptoKey that represents the ML-KEM private key
448            // identified by mlKemPrivateKey.
449            // Step 2.12. Set the [[type]] internal slot of key to "private"
450            // Step 2.13. Let algorithm be a new KeyAlgorithm.
451            // Step 2.14. Set the name attribute of algorithm to the name attribute of
452            // normalizedAlgorithm.
453            // Step 2.15. Set the [[algorithm]] internal slot of key to algorithm.
454            let algorithm = KeyAlgorithm {
455                name: normalized_algorithm.name,
456            };
457            CryptoKey::new(
458                cx,
459                global,
460                KeyType::Private,
461                extractable,
462                KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
463                usages.normalized_value(),
464                ml_kem_private_key,
465            )
466        },
467        // If format is "raw-public":
468        KeyFormat::Raw_public => {
469            // Step 2.1. If usages contains an entry which is not "encapsulateKey" or
470            // "encapsulateBits" then throw a SyntaxError.
471            if usages
472                .iter()
473                .any(|usage| !matches!(usage, KeyUsage::EncapsulateKey | KeyUsage::EncapsulateBits))
474            {
475                return Err(Error::Syntax(Some(
476                    "Usages contains an entry which is not \"encapsulateKey\" or \
477                    \"encapsulateBits\""
478                        .into(),
479                )));
480            }
481
482            // Step 2.2. Let data be keyData.
483            // Step 2.3. Let key be a new CryptoKey that represents the ML-KEM public key data in
484            // data.
485            // Step 2.4. Set the [[type]] internal slot of key to "public"
486            // Step 2.5. Let algorithm be a new KeyAlgorithm.
487            // Step 2.6. Set the name attribute of algorithm to the name attribute of
488            // normalizedAlgorithm.
489            // Step 2.7. Set the [[algorithm]] internal slot of key to algorithm.
490            let public_key = match normalized_algorithm.name {
491                CryptoAlgorithm::MlKem512 => {
492                    let encapsulation_key =
493                        EncapsulationKey::new_from_slice(key_data).map_err(|_| {
494                            Error::Data(Some(
495                                "Failed to parse the public ML-KEM-512 key in raw format".into(),
496                            ))
497                        })?;
498                    Handle::MlKem512PublicKey(encapsulation_key)
499                },
500                CryptoAlgorithm::MlKem768 => {
501                    let encapsulation_key =
502                        EncapsulationKey::new_from_slice(key_data).map_err(|_| {
503                            Error::Data(Some(
504                                "Failed to parse the public ML-KEM-768 key in raw format".into(),
505                            ))
506                        })?;
507                    Handle::MlKem768PublicKey(encapsulation_key)
508                },
509                CryptoAlgorithm::MlKem1024 => {
510                    let encapsulation_key =
511                        EncapsulationKey::new_from_slice(key_data).map_err(|_| {
512                            Error::Data(Some(
513                                "Failed to parse the public ML-KEM-1024 key in raw format".into(),
514                            ))
515                        })?;
516                    Handle::MlKem1024PublicKey(encapsulation_key)
517                },
518                name => {
519                    return Err(Error::NotSupported(Some(format!(
520                        "{} is not an ML-KEM algorithm",
521                        name.as_str()
522                    ))));
523                },
524            };
525            let algorithm = KeyAlgorithm {
526                name: normalized_algorithm.name,
527            };
528            CryptoKey::new(
529                cx,
530                global,
531                KeyType::Public,
532                extractable,
533                KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
534                usages.normalized_value(),
535                public_key,
536            )
537        },
538        // If format is "raw-seed":
539        KeyFormat::Raw_seed => {
540            // Step 2.1. If usages contains an entry which is not "decapsulateKey" or
541            // "decapsulateBits" then throw a SyntaxError.
542            if usages
543                .iter()
544                .any(|usage| !matches!(usage, KeyUsage::DecapsulateKey | KeyUsage::DecapsulateBits))
545            {
546                return Err(Error::Syntax(Some(
547                    "Usages contains an entry which is not \"decapsulateKey\" or \
548                    \"decapsulateBits\""
549                        .into(),
550                )));
551            }
552
553            // Step 2.2. Let data be keyData.
554            let data = key_data;
555
556            // Step 2.3. If the length in bits of data is not 512 then throw a DataError.
557            if data.len() != 64 {
558                return Err(Error::Data(Some(
559                    "The length in bits of data is not 512".into(),
560                )));
561            }
562
563            // Step 2.4. Let privateKey be the result of performing the ML-KEM.KeyGen_internal
564            // function described in Section 6.1 of [FIPS-203] with the parameter set indicated by
565            // the name member of normalizedAlgorithm, using the first 256 bits of data as d and
566            // the last 256 bits of data as z.
567            let private_key = match normalized_algorithm.name {
568                CryptoAlgorithm::MlKem512 => {
569                    let decapsulation_key =
570                        DecapsulationKey::new_from_slice(key_data).map_err(|_| {
571                            Error::Data(Some(
572                                "Failed to parse the private ML-KEM-512 key in raw format".into(),
573                            ))
574                        })?;
575                    Handle::MlKem512PrivateKey(decapsulation_key)
576                },
577                CryptoAlgorithm::MlKem768 => {
578                    let decapsulation_key =
579                        DecapsulationKey::new_from_slice(key_data).map_err(|_| {
580                            Error::Data(Some(
581                                "Failed to parse the private ML-KEM-768 key in raw format".into(),
582                            ))
583                        })?;
584                    Handle::MlKem768PrivateKey(decapsulation_key)
585                },
586                CryptoAlgorithm::MlKem1024 => {
587                    let decapsulation_key =
588                        DecapsulationKey::new_from_slice(key_data).map_err(|_| {
589                            Error::Data(Some(
590                                "Failed to parse the private ML-KEM-1024 key in raw format".into(),
591                            ))
592                        })?;
593                    Handle::MlKem1024PrivateKey(decapsulation_key)
594                },
595                name => {
596                    return Err(Error::NotSupported(Some(format!(
597                        "{} is not an ML-KEM algorithm",
598                        name.as_str()
599                    ))));
600                },
601            };
602
603            // Step 2.5. Let key be a new CryptoKey that represents the ML-KEM private key
604            // identified by privateKey.
605            // Step 2.6. Set the [[type]] internal slot of key to "private"
606            // Step 2.7. Let algorithm be a new KeyAlgorithm.
607            // Step 2.8. Set the name attribute of algorithm to the name attribute of
608            // normalizedAlgorithm.
609            // Step 2.9. Set the [[algorithm]] internal slot of key to algorithm.
610            let algorithm = KeyAlgorithm {
611                name: normalized_algorithm.name,
612            };
613            CryptoKey::new(
614                cx,
615                global,
616                KeyType::Private,
617                extractable,
618                KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
619                usages.normalized_value(),
620                private_key,
621            )
622        },
623        // If format is "jwk":
624        KeyFormat::Jwk => {
625            // Step 2.1.
626            // If keyData is a JsonWebKey dictionary:
627            //     Let jwk equal keyData.
628            // Otherwise:
629            //     Throw a DataError.
630            let jwk = JsonWebKey::parse(cx, key_data)?;
631
632            // Step 2.2. If the priv field of jwk is present and if usages contains an entry which
633            // is not "decapsulateKey" or "decapsulateBits" then throw a SyntaxError.
634            // Step 2.3. If the priv field of jwk is not present and if usages contains an entry
635            // which is not "encapsulateKey" or "encapsulateBits" then throw a SyntaxError.
636            match jwk.priv_.as_ref() {
637                Some(_) => usages.ensure_only_contain_entries_from(&[
638                    KeyUsage::DecapsulateKey,
639                    KeyUsage::DecapsulateBits,
640                ])?,
641                None => usages.ensure_only_contain_entries_from(&[
642                    KeyUsage::EncapsulateKey,
643                    KeyUsage::EncapsulateBits,
644                ])?,
645            }
646
647            // Step 2.4. If the kty field of jwk is not "AKP", then throw a DataError.
648            if jwk.kty.as_ref().is_none_or(|kty| kty != "AKP") {
649                return Err(Error::Data(Some(
650                    "The kty field of jwk is not \"AKP\"".into(),
651                )));
652            }
653
654            // Step 2.5. If the alg field of jwk is not present, or its value does not identify the
655            // ML-KEM parameter set indicated by the name member of normalizedAlgorithm, then throw
656            // a DataError.
657            //
658            // NOTE: The "alg" values registered in the IANA JSON Web Signature and Encryption
659            // Algorithms registry for the ML-KEM parameter sets defined by this specification are
660            // ML-KEM-512, ML-KEM-768, and ML-KEM-1024. Implementations should also accept other
661            // values from this registry that identify a JWE algorithm using the same ML-KEM
662            // parameter set, provided that the JWE algorithm's JWK representation is compatible
663            // with the representation defined here apart from the "alg" value. Examples include the
664            // values proposed in [draft-ietf-jose-hpke-pq-pqt], once registered.
665            match normalized_algorithm.name {
666                CryptoAlgorithm::MlKem512 => {
667                    if jwk.alg.as_ref().is_none_or(|alg| alg != "ML-KEM-512") {
668                        return Err(Error::Data(Some(
669                            "The alg field of jwk is not invalid.".into(),
670                        )));
671                    }
672                },
673                CryptoAlgorithm::MlKem768 => {
674                    if jwk
675                        .alg
676                        .as_ref()
677                        .is_none_or(|alg| alg != "ML-KEM-768" && alg != "HPKE-12")
678                    {
679                        return Err(Error::Data(Some(
680                            "The alg field of jwk is not invalid.".into(),
681                        )));
682                    }
683                },
684                CryptoAlgorithm::MlKem1024 => {
685                    if jwk
686                        .alg
687                        .as_ref()
688                        .is_none_or(|alg| alg != "ML-KEM-1024" && alg != "HPKE-13")
689                    {
690                        return Err(Error::Data(Some(
691                            "The alg field of jwk is not invalid.".into(),
692                        )));
693                    }
694                },
695                _ => {
696                    return Err(Error::NotSupported(Some(format!(
697                        "{} is not an ML-KEM algorithm",
698                        normalized_algorithm.name.as_str()
699                    ))));
700                },
701            };
702
703            // Step 2.6. If usages is non-empty and the use field of jwk is present and is not
704            // equal to "enc", then throw a DataError.
705            if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "enc") {
706                return Err(Error::Data(Some(
707                    "usages is non-empty and the use field of jwk is present and is not \
708                    equal to \"enc\""
709                        .into(),
710                )));
711            }
712
713            // Step 2.7. If the key_ops field of jwk is present, and is invalid according to the
714            // requirements of JSON Web Key [JWK], or it does not contain all of the specified
715            // usages values, then throw a DataError.
716            jwk.check_key_ops(&usages)?;
717
718            // Step 2.8. If the ext field of jwk is present and has the value false and extractable
719            // is true, then throw a DataError.
720            if jwk.ext.is_some_and(|ext| !ext) && extractable {
721                return Err(Error::Data(Some(
722                    "The ext field of jwk is present and has the value false and extractable \
723                    is true"
724                        .into(),
725                )));
726            }
727
728            // Step 2.9.
729            // If the priv field of jwk is present:
730            let (key_type, key_handle) = if jwk.priv_.is_some() {
731                // Step 2.9.1. If the priv attribute of jwk does not contain a valid base64url
732                // encoded seed representing an ML-KEM private key, then throw a DataError.
733                let priv_bytes = jwk.decode_required_string_field(JwkStringField::Priv)?;
734
735                // Step 2.9.2. Let key be a new CryptoKey object that represents the ML-KEM private
736                // key identified by interpreting the priv attribute of jwk as a base64url encoded
737                // seed.
738                // Step 2.9.3. Set the [[type]] internal slot of Key to "private".
739                // Step 2.9.4. If the pub attribute of jwk does not contain the base64url encoded
740                // public key representing the ML-KEM public key corresponding to key, then throw a
741                // DataError.
742                // NOTE: The CryptoKey object is created in Step 2.10 - 2.12.
743                let pub_bytes = jwk.decode_required_string_field(JwkStringField::Pub)?;
744                let private_key_handle = match normalized_algorithm.name {
745                    CryptoAlgorithm::MlKem512 => {
746                        let decapsulation_key = DecapsulationKey::new_from_slice(&priv_bytes)
747                            .map_err(|_| {
748                                Error::Data(Some(
749                                    "Failed to parse the private ML-KEM-512 key in priv attribute"
750                                        .into(),
751                                ))
752                            })?;
753                        let encapsulation_key = EncapsulationKey::new_from_slice(&pub_bytes)
754                            .map_err(|_| {
755                                Error::Data(Some(
756                                    "Failed to parse the public ML-KEM-512 key in pub attribute"
757                                        .into(),
758                                ))
759                            })?;
760                        if *decapsulation_key.encapsulation_key() != encapsulation_key {
761                            return Err(Error::Data(Some(
762                                "The public key in pub attribute does not match \
763                                    the private key in priv attribute"
764                                    .into(),
765                            )));
766                        }
767                        Handle::MlKem512PrivateKey(decapsulation_key)
768                    },
769                    CryptoAlgorithm::MlKem768 => {
770                        let decapsulation_key = DecapsulationKey::new_from_slice(&priv_bytes)
771                            .map_err(|_| {
772                                Error::Data(Some(
773                                    "Failed to parse the private ML-KEM-768 key in priv attribute"
774                                        .into(),
775                                ))
776                            })?;
777                        let encapsulation_key = EncapsulationKey::new_from_slice(&pub_bytes)
778                            .map_err(|_| {
779                                Error::Data(Some(
780                                    "Failed to parse the public ML-KEM-768 key in pub attribute"
781                                        .into(),
782                                ))
783                            })?;
784                        if *decapsulation_key.encapsulation_key() != encapsulation_key {
785                            return Err(Error::Data(Some(
786                                "The public key in pub attribute does not match \
787                                    the private key in priv attribute"
788                                    .into(),
789                            )));
790                        }
791                        Handle::MlKem768PrivateKey(decapsulation_key)
792                    },
793                    CryptoAlgorithm::MlKem1024 => {
794                        let decapsulation_key = DecapsulationKey::new_from_slice(&priv_bytes)
795                            .map_err(|_| {
796                                Error::Data(Some(
797                                    "Failed to parse the private ML-KEM-1024 key in priv attribute"
798                                        .into(),
799                                ))
800                            })?;
801                        let encapsulation_key = EncapsulationKey::new_from_slice(&pub_bytes)
802                            .map_err(|_| {
803                                Error::Data(Some(
804                                    "Failed to parse the public ML-KEM-1024 key in pub attribute"
805                                        .into(),
806                                ))
807                            })?;
808                        if *decapsulation_key.encapsulation_key() != encapsulation_key {
809                            return Err(Error::Data(Some(
810                                "The public key in pub attribute does not match \
811                                    the private key in priv attribute"
812                                    .into(),
813                            )));
814                        }
815                        Handle::MlKem1024PrivateKey(decapsulation_key)
816                    },
817                    name => {
818                        return Err(Error::NotSupported(Some(format!(
819                            "{} is not an ML-KEM algorithm",
820                            name.as_str()
821                        ))));
822                    },
823                };
824                (KeyType::Private, private_key_handle)
825            }
826            // Otherwise:
827            else {
828                // Step 2.9.1. If the pub attribute of jwk does not contain a valid base64url
829                // encoded public key representing an ML-KEM public key, then throw a DataError.
830                let pub_bytes = jwk.decode_required_string_field(JwkStringField::Pub)?;
831
832                // Step 2.9.2. Let key be a new CryptoKey object that represents the ML-KEM public
833                // key identified by interpreting the pub attribute of jwk as a base64url encoded
834                // public key.
835                // Step 2.9.3. Set the [[type]] internal slot of Key to "public".
836                // NOTE: The CryptoKey object is created in Step 2.10 - 2.12.
837                let public_key_handle = match normalized_algorithm.name {
838                    CryptoAlgorithm::MlKem512 => {
839                        let encapsulation_key = EncapsulationKey::new_from_slice(&pub_bytes)
840                            .map_err(|_| {
841                                Error::Data(Some(
842                                    "Failed to parse the public ML-KEM-512 key in pub attribute"
843                                        .into(),
844                                ))
845                            })?;
846                        Handle::MlKem512PublicKey(encapsulation_key)
847                    },
848                    CryptoAlgorithm::MlKem768 => {
849                        let encapsulation_key = EncapsulationKey::new_from_slice(&pub_bytes)
850                            .map_err(|_| {
851                                Error::Data(Some(
852                                    "Failed to parse the public ML-KEM-768 key in pub attribute"
853                                        .into(),
854                                ))
855                            })?;
856                        Handle::MlKem768PublicKey(encapsulation_key)
857                    },
858                    CryptoAlgorithm::MlKem1024 => {
859                        let encapsulation_key = EncapsulationKey::new_from_slice(&pub_bytes)
860                            .map_err(|_| {
861                                Error::Data(Some(
862                                    "Failed to parse the public ML-KEM-1024 key in pub attribute"
863                                        .into(),
864                                ))
865                            })?;
866                        Handle::MlKem1024PublicKey(encapsulation_key)
867                    },
868                    name => {
869                        return Err(Error::NotSupported(Some(format!(
870                            "{} is not an ML-KEM algorithm",
871                            name.as_str()
872                        ))));
873                    },
874                };
875                (KeyType::Public, public_key_handle)
876            };
877
878            // Step 2.10. Let algorithm be a new instance of a KeyAlgorithm object.
879            // Step 2.11. Set the name attribute of algorithm to the name member of
880            // normalizedAlgorithm.
881            // Step 2.12. Set the [[algorithm]] internal slot of key to algorithm.
882            let algorithm = KeyAlgorithm {
883                name: normalized_algorithm.name,
884            };
885            CryptoKey::new(
886                cx,
887                global,
888                key_type,
889                extractable,
890                KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
891                usages.normalized_value(),
892                key_handle,
893            )
894        },
895        // Otherwise:
896        _ => {
897            // throw a NotSupportedError.
898            return Err(Error::NotSupported(Some(
899                "Unsupported import key format for ML-KEM key".into(),
900            )));
901        },
902    };
903
904    // Step 3. Return key.
905    Ok(key)
906}
907
908/// <https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-export-key>
909pub(crate) fn export_key<D: Equivalence>(
910    format: KeyFormat,
911    key: &CryptoKey<D>,
912) -> Result<ExportedKey, Error> {
913    // Step 1. If the underlying cryptographic key material represented by the [[handle]] internal
914    // slot of key cannot be accessed, then throw an OperationError.
915
916    // Step 2.
917    let result = match format {
918        // If format is "spki":
919        KeyFormat::Spki => {
920            // Step 2.1. If the [[type]] internal slot of key is not "public", then throw an
921            // InvalidAccessError.
922            key.ensure_type(KeyType::Public)?;
923
924            // Step 2.2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
925            let KeyAlgorithmAndDerivatives::KeyAlgorithm(key_algorithm) = key.algorithm() else {
926                return Err(Error::Operation(Some(
927                    "[[algorithm]] internal slot of key is not a KeyAlgorithm".into(),
928                )));
929            };
930
931            // Step 2.3.
932            // Let data be an instance of the SubjectPublicKeyInfo ASN.1 structure defined in
933            // [RFC5280] with the following properties:
934            //
935            //     Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following
936            //     properties:
937            //
938            //         If the name member of keyAlgorithm is "ML-KEM-512":
939            //             Set the algorithm object identifier to the id-alg-ml-kem-512
940            //             (2.16.840.1.101.3.4.4.1) OID.
941            //
942            //         If the name member of keyAlgorithm is "ML-KEM-768":
943            //             Set the algorithm object identifier to the id-alg-ml-kem-768
944            //             (2.16.840.1.101.3.4.4.2) OID.
945            //
946            //         If the name member of keyAlgorithm is "ML-KEM-1024":
947            //             Set the algorithm object identifier to the id-alg-ml-kem-1024
948            //             (2.16.840.1.101.3.4.4.3) OID.
949            //
950            //         Otherwise:
951            //             throw a NotSupportedError.
952            //
953            //     Set the subjectPublicKey field to keyData.
954            let data = match (key_algorithm.name, key.handle()) {
955                (CryptoAlgorithm::MlKem512, Handle::MlKem512PublicKey(public_key)) => {
956                    public_key.to_public_key_der().map_err(|_| {
957                        Error::Operation(Some(
958                            "Failed to encode the ML-KEM-512 public key into SPKI format".into(),
959                        ))
960                    })?
961                },
962                (CryptoAlgorithm::MlKem768, Handle::MlKem768PublicKey(public_key)) => {
963                    public_key.to_public_key_der().map_err(|_| {
964                        Error::Operation(Some(
965                            "Failed to encode the ML-KEM-768 public key into SPKI format".into(),
966                        ))
967                    })?
968                },
969                (CryptoAlgorithm::MlKem1024, Handle::MlKem1024PublicKey(public_key)) => {
970                    public_key.to_public_key_der().map_err(|_| {
971                        Error::Operation(Some(
972                            "Failed to encode the ML-KEM-1024 public key into SPKI format".into(),
973                        ))
974                    })?
975                },
976                _ => {
977                    return Err(Error::Operation(Some(
978                        "The key handle is not representing an ML-KEM public key".into(),
979                    )));
980                },
981            };
982
983            // Step 2.4. Let result be the result of DER-encoding data.
984            ExportedKey::new_bytes(data.into_vec())
985        },
986        // If format is "pkcs8":
987        KeyFormat::Pkcs8 => {
988            // Step 2.1. If the [[type]] internal slot of key is not "private", then throw an
989            // InvalidAccessError.
990            key.ensure_type(KeyType::Private)?;
991
992            // Step 2.2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
993            let KeyAlgorithmAndDerivatives::KeyAlgorithm(key_algorithm) = key.algorithm() else {
994                return Err(Error::Operation(Some(
995                    "[[algorithm]] internal slot of key is not a KeyAlgorithm".into(),
996                )));
997            };
998
999            // Step 2.3.
1000            // Let data be an instance of the PrivateKeyInfo ASN.1 structure defined in [RFC5208]
1001            // with the following properties:
1002            //
1003            //     Set the version field to 0.
1004            //
1005            //     Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 type
1006            //     with the following properties:
1007            //
1008            //         If the name member of keyAlgorithm is "ML-KEM-512":
1009            //             Set the algorithm object identifier to the id-alg-ml-kem-512
1010            //             (2.16.840.1.101.3.4.4.1) OID.
1011            //
1012            //         If the name member of keyAlgorithm is "ML-KEM-768":
1013            //             Set the algorithm object identifier to the id-alg-ml-kem-768
1014            //             (2.16.840.1.101.3.4.4.2) OID.
1015            //
1016            //         If the name member of keyAlgorithm is "ML-KEM-1024":
1017            //             Set the algorithm object identifier to the id-alg-ml-kem-1024
1018            //             (2.16.840.1.101.3.4.4.3) OID.
1019            //
1020            //         Otherwise:
1021            //             throw a NotSupportedError.
1022            //
1023            //     Set the privateKey field as follows:
1024            //
1025            //         If the name member of keyAlgorithm is "ML-KEM-512":
1026            //             Set the privateKey field to the result of DER-encoding a
1027            //             ML-KEM-512-PrivateKey ASN.1 type that represents the ML-KEM private key
1028            //             seed represented by the [[handle]] internal slot of key using the
1029            //             seed-only format (using a context-specific [0] primitive tag with an
1030            //             implicit encoding of OCTET STRING).
1031            //
1032            //         If the name member of keyAlgorithm is "ML-KEM-768":
1033            //             Set the privateKey field to the result of DER-encoding a
1034            //             ML-KEM-768-PrivateKey ASN.1 type that represents the ML-KEM private key
1035            //             seed represented by the [[handle]] internal slot of key using the
1036            //             seed-only format (using a context-specific [0] primitive tag with an
1037            //             implicit encoding of OCTET STRING).
1038            //
1039            //         If the name member of keyAlgorithm is "ML-KEM-1024":
1040            //             Set the privateKey field to the result of DER-encoding a
1041            //             ML-KEM-1024-PrivateKey ASN.1 type that represents the ML-KEM private key
1042            //             seed represented by the [[handle]] internal slot of key using the
1043            //             seed-only format (using a context-specific [0] primitive tag with an
1044            //             implicit encoding of OCTET STRING).
1045            //
1046            //         Otherwise:
1047            //             throw a NotSupportedError.
1048            let private_key_info = match (key_algorithm.name, key.handle()) {
1049                (CryptoAlgorithm::MlKem512, Handle::MlKem512PrivateKey(private_key)) => {
1050                    private_key.to_pkcs8_der().map_err(|_| {
1051                        Error::Operation(Some(
1052                            "Failed to encode the ML-KEM-512 private key into PKCS#8 format".into(),
1053                        ))
1054                    })?
1055                },
1056                (CryptoAlgorithm::MlKem768, Handle::MlKem768PrivateKey(private_key)) => {
1057                    private_key.to_pkcs8_der().map_err(|_| {
1058                        Error::Operation(Some(
1059                            "Failed to encode the ML-KEM-768 private key into PKCS#8 format".into(),
1060                        ))
1061                    })?
1062                },
1063                (CryptoAlgorithm::MlKem1024, Handle::MlKem1024PrivateKey(private_key)) => {
1064                    private_key.to_pkcs8_der().map_err(|_| {
1065                        Error::Operation(Some(
1066                            "Failed to encode the ML-KEM-1024 private key into PKCS#8 format"
1067                                .into(),
1068                        ))
1069                    })?
1070                },
1071                _ => {
1072                    return Err(Error::Operation(Some(
1073                        "The key handle is not representing an ML-KEM private key".into(),
1074                    )));
1075                },
1076            };
1077
1078            // Step 2.4. Let result be the result of DER-encoding data.
1079            ExportedKey::Bytes(private_key_info.to_bytes())
1080        },
1081        // If format is "raw-public":
1082        KeyFormat::Raw_public => {
1083            // Step 2.1. If the [[type]] internal slot of key is not "public", then throw an
1084            // InvalidAccessError.
1085            key.ensure_type(KeyType::Public)?;
1086
1087            // Step 2.2. Let data be a byte sequence containing the raw octets of the key
1088            // represented by the [[handle]] internal slot of key.
1089            let data = match key.handle() {
1090                Handle::MlKem512PublicKey(public_key) => public_key.to_bytes().as_slice().to_vec(),
1091                Handle::MlKem768PublicKey(public_key) => public_key.to_bytes().as_slice().to_vec(),
1092                Handle::MlKem1024PublicKey(public_key) => public_key.to_bytes().as_slice().to_vec(),
1093                _ => {
1094                    return Err(Error::Operation(Some(
1095                        "The key handle is not representing an ML-KEM public key".into(),
1096                    )));
1097                },
1098            };
1099
1100            // Step 2.3. Let result be data.
1101            ExportedKey::new_bytes(data)
1102        },
1103        // If format is "raw-seed":
1104        KeyFormat::Raw_seed => {
1105            // Step 2.1. If the [[type]] internal slot of key is not "private", then throw an
1106            // InvalidAccessError.
1107            key.ensure_type(KeyType::Private)?;
1108
1109            // Step 2.2. Let data be a byte sequence containing the concatenation of the d and z
1110            // seed variables of the key represented by the [[handle]] internal slot of key.
1111            let data = match key.handle() {
1112                Handle::MlKem512PrivateKey(private_key) => private_key
1113                    .to_seed()
1114                    .expect("This decapsulation key should contain seed value")
1115                    .as_slice()
1116                    .to_vec(),
1117                Handle::MlKem768PrivateKey(private_key) => private_key
1118                    .to_seed()
1119                    .expect("This decapsulation key should contain seed value")
1120                    .as_slice()
1121                    .to_vec(),
1122                Handle::MlKem1024PrivateKey(private_key) => private_key
1123                    .to_seed()
1124                    .expect("This decapsulation key should contain seed value")
1125                    .as_slice()
1126                    .to_vec(),
1127                _ => {
1128                    return Err(Error::Operation(Some(
1129                        "The key handle is not representing an ML-KEM private key".into(),
1130                    )));
1131                },
1132            };
1133
1134            // Step 2.3. Let result be data.
1135            ExportedKey::new_bytes(data)
1136        },
1137        // If format is "jwk":
1138        KeyFormat::Jwk => {
1139            // Step 2.1. Let jwk be a new JsonWebKey dictionary.
1140            let mut jwk = JsonWebKey::default();
1141
1142            // Step 2.2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
1143            let KeyAlgorithmAndDerivatives::KeyAlgorithm(key_algorithm) = key.algorithm() else {
1144                return Err(Error::Operation(Some(
1145                    "[[algorithm]] internal slot of key is not a KeyAlgorithm".into(),
1146                )));
1147            };
1148
1149            // Step 2.3. Set the kty attribute of jwk to "AKP".
1150            jwk.kty = Some(DOMString::from_static("AKP"));
1151
1152            // Step 2.4.  Set the alg attribute of jwk to the name member of keyAlgorithm.
1153            jwk.alg = Some(DOMString::from_static(key_algorithm.name.as_str()));
1154
1155            // Step 2.5. Set the pub attribute of jwk to the base64url encoded public key
1156            // corresponding to the [[handle]] internal slot of key.
1157            // Step 2.6.
1158            // If the [[type]] internal slot of key is "private":
1159            //     Set the priv attribute of jwk to the base64url encoded seed represented by the
1160            //     [[handle]] internal slot of key.
1161            if key.Type() == KeyType::Private {
1162                match key.handle() {
1163                    Handle::MlKem512PrivateKey(private_key) => {
1164                        jwk.encode_string_field(
1165                            JwkStringField::Priv,
1166                            private_key
1167                                .to_seed()
1168                                .expect("This decapsulation key should contain seed value")
1169                                .as_slice(),
1170                        );
1171                        jwk.encode_string_field(
1172                            JwkStringField::Pub,
1173                            private_key.encapsulation_key().to_bytes().as_slice(),
1174                        );
1175                    },
1176                    Handle::MlKem768PrivateKey(private_key) => {
1177                        jwk.encode_string_field(
1178                            JwkStringField::Priv,
1179                            private_key
1180                                .to_seed()
1181                                .expect("This decapsulation key should contain seed value")
1182                                .as_slice(),
1183                        );
1184                        jwk.encode_string_field(
1185                            JwkStringField::Pub,
1186                            private_key.encapsulation_key().to_bytes().as_slice(),
1187                        );
1188                    },
1189                    Handle::MlKem1024PrivateKey(private_key) => {
1190                        jwk.encode_string_field(
1191                            JwkStringField::Priv,
1192                            private_key
1193                                .to_seed()
1194                                .expect("This decapsulation key should contain seed value")
1195                                .as_slice(),
1196                        );
1197                        jwk.encode_string_field(
1198                            JwkStringField::Pub,
1199                            private_key.encapsulation_key().to_bytes().as_slice(),
1200                        );
1201                    },
1202                    _ => {
1203                        return Err(Error::Operation(Some(
1204                            "The key handle is not representing an ML-KEM private key".into(),
1205                        )));
1206                    },
1207                }
1208            } else {
1209                match key.handle() {
1210                    Handle::MlKem512PublicKey(public_key) => {
1211                        jwk.encode_string_field(
1212                            JwkStringField::Pub,
1213                            public_key.to_bytes().as_slice(),
1214                        );
1215                    },
1216                    Handle::MlKem768PublicKey(public_key) => {
1217                        jwk.encode_string_field(
1218                            JwkStringField::Pub,
1219                            public_key.to_bytes().as_slice(),
1220                        );
1221                    },
1222                    Handle::MlKem1024PublicKey(public_key) => {
1223                        jwk.encode_string_field(
1224                            JwkStringField::Pub,
1225                            public_key.to_bytes().as_slice(),
1226                        );
1227                    },
1228                    _ => {
1229                        return Err(Error::Operation(Some(
1230                            "The key handle is not representing an ML-KEM public key".into(),
1231                        )));
1232                    },
1233                };
1234            }
1235
1236            // Step 2.7. Set the key_ops attribute of jwk to the usages attribute of key.
1237            jwk.set_key_ops(key.usages());
1238
1239            // Step 2.8. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
1240            jwk.ext = Some(key.Extractable());
1241
1242            // Step 2.9. Let result be jwk.
1243            ExportedKey::new_jwk(jwk)
1244        },
1245        // Otherwise:
1246        _ => {
1247            // throw a NotSupportedError.
1248            return Err(Error::NotSupported(Some(
1249                "Unsupported export key format for ML-KEM key".into(),
1250            )));
1251        },
1252    };
1253
1254    // Step 3. Return result.
1255    Ok(result)
1256}
1257
1258/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
1259/// Step 9 - 15, for ML-KEM
1260pub(crate) fn get_public_key<D: Equivalence>(
1261    cx: &mut JSContext,
1262    global: &D::GlobalScope,
1263    key: &CryptoKey<D>,
1264    algorithm: &KeyAlgorithmAndDerivatives,
1265    usages: Vec<KeyUsage>,
1266) -> Result<DomRoot<CryptoKey<D>>, Error> {
1267    // Step 9. If usages contains an entry which is not supported for a public key by the algorithm
1268    // identified by algorithm, then throw a SyntaxError.
1269    //
1270    // NOTE: See "importKey" operation for supported usages
1271    usages
1272        .ensure_only_contain_entries_from(&[KeyUsage::EncapsulateKey, KeyUsage::EncapsulateBits])?;
1273
1274    // Step 10. Let publicKey be a new CryptoKey representing the public key corresponding to the
1275    // private key represented by the [[handle]] internal slot of key.
1276    // Step 11. If an error occurred, then throw a OperationError.
1277    // Step 12. Set the [[type]] internal slot of publicKey to "public".
1278    // Step 13. Set the [[algorithm]] internal slot of publicKey to algorithm.
1279    // Step 14. Set the [[extractable]] internal slot of publicKey to true.
1280    // Step 15. Set the [[usages]] internal slot of publicKey to the normalized value of usages.
1281    let public_key_handle = match key.handle() {
1282        Handle::MlKem512PrivateKey(decapsulation_key) => {
1283            Handle::MlKem512PublicKey(decapsulation_key.encapsulation_key().clone())
1284        },
1285        Handle::MlKem768PrivateKey(decapsulation_key) => {
1286            Handle::MlKem768PublicKey(decapsulation_key.encapsulation_key().clone())
1287        },
1288        Handle::MlKem1024PrivateKey(decapsulation_key) => {
1289            Handle::MlKem1024PublicKey(decapsulation_key.encapsulation_key().clone())
1290        },
1291        _ => {
1292            return Err(Error::Operation(Some(
1293                "[[handle]] internal slot of key is not an ML-KEM private key".into(),
1294            )));
1295        },
1296    };
1297    let public_key = CryptoKey::new(
1298        cx,
1299        global,
1300        KeyType::Public,
1301        true,
1302        algorithm.clone(),
1303        usages.normalized_value(),
1304        public_key_handle,
1305    );
1306
1307    Ok(public_key)
1308}