Skip to main content

script_webcrypto/
subtlecrypto.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
5mod aes_cbc_operation;
6mod aes_common;
7mod aes_ctr_operation;
8mod aes_gcm_operation;
9mod aes_kw_operation;
10mod aes_ocb_operation;
11mod argon2_operation;
12mod chacha20_poly1305_operation;
13mod cshake_operation;
14mod ec_common;
15mod ecdh_operation;
16mod ecdsa_operation;
17mod ed25519_operation;
18mod ed448_operation;
19mod hkdf_operation;
20mod hmac_operation;
21mod hybrid_kem_operation;
22mod kangarootwelve_operation;
23mod kmac_operation;
24mod ml_dsa_operation;
25mod ml_kem_operation;
26mod pbkdf2_operation;
27mod rsa_common;
28mod rsa_oaep_operation;
29mod rsa_pss_operation;
30mod rsassa_pkcs1_v1_5_operation;
31mod sha3_operation;
32mod sha_operation;
33mod turboshake_operation;
34mod x25519_operation;
35mod x448_operation;
36
37use std::collections::HashSet;
38use std::fmt::Display;
39use std::marker::PhantomData;
40use std::ptr;
41use std::str::FromStr;
42
43use base64ct::{Base64UrlUnpadded, Encoding};
44use dom_struct::dom_struct;
45use js::context::JSContext;
46use js::conversions::{
47    ConversionBehavior, ConversionResult, FromJSValConvertible, ToJSValConvertible,
48};
49use js::jsapi::{Heap, JSObject};
50use js::jsval::{ObjectOrNullValue, UndefinedValue};
51use js::realm::CurrentRealm;
52use js::rooted;
53use js::rust::wrappers2::JS_ParseJSON;
54use js::rust::{HandleObject, MutableHandleValue, Trace};
55use js::typedarray::{ArrayBufferU8, HeapUint8Array};
56use jstraceable_derive::JSTraceable;
57use malloc_size_of_derive::MallocSizeOf;
58use script_bindings::buffer_source::{create_buffer_source, get_buffer_source_copy};
59use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
60    CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage,
61};
62use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::{
63    Algorithm as AlgorithmWithDOMString, AlgorithmIdentifier, JsonWebKey, KeyFormat,
64    SubtleCryptoMethods, Wrap as SubtleCryptoWrap,
65};
66use script_bindings::codegen::GenericUnionTypes::{
67    ArrayBufferViewOrArrayBuffer, ArrayBufferViewOrArrayBufferOrJsonWebKey,
68};
69use script_bindings::conversions::{StringificationBehavior, get_property};
70use script_bindings::error::{Error, Fallible};
71use script_bindings::interfaces::{
72    PromiseHelpers, StackRootPromiseHelpers, ThreadTrustedPromiseHelpers,
73};
74use script_bindings::js::JS_NewObject;
75use script_bindings::refcounted::Trusted;
76use script_bindings::reflector::{DomGlobalGeneric, Reflector, reflect_dom_object_with_wrap};
77use script_bindings::root::DomRoot;
78use script_bindings::str::{DOMString, serialize_jsval_to_json_utf8};
79use script_bindings::trace::RootedTraceableBox;
80use script_bindings::utils::set_dictionary_property;
81use script_bindings::{DomTypes, task};
82use servo_constellation_traits::{
83    SerializableAesKeyAlgorithm, SerializableAlgorithm, SerializableCShakeParams,
84    SerializableDigestAlgorithm, SerializableEcKeyAlgorithm, SerializableHmacKeyAlgorithm,
85    SerializableKangarooTwelveParams, SerializableKeyAlgorithm,
86    SerializableKeyAlgorithmAndDerivatives, SerializableKmacKeyAlgorithm,
87    SerializableRsaHashedKeyAlgorithm, SerializableTurboShakeParams,
88};
89use strum::{EnumString, IntoStaticStr, VariantArray};
90use zeroize::Zeroizing;
91
92use crate::cryptokey::{CryptoKey, CryptoKeyOrCryptoKeyPair};
93use crate::traits::{Equivalence, WebCryptoGlobalTrait};
94
95// Named elliptic curves
96const NAMED_CURVE_P256: &str = "P-256";
97const NAMED_CURVE_P384: &str = "P-384";
98const NAMED_CURVE_P521: &str = "P-521";
99
100static SUPPORTED_CURVES: &[&str] = &[NAMED_CURVE_P256, NAMED_CURVE_P384, NAMED_CURVE_P521];
101
102#[derive(EnumString, VariantArray, IntoStaticStr, PartialEq, Clone, Copy, MallocSizeOf)]
103enum CryptoAlgorithm {
104    #[strum(serialize = "RSASSA-PKCS1-v1_5")]
105    RsassaPkcs1V1_5,
106    #[strum(serialize = "RSA-PSS")]
107    RsaPss,
108    #[strum(serialize = "RSA-OAEP")]
109    RsaOaep,
110    #[strum(serialize = "ECDSA")]
111    Ecdsa,
112    #[strum(serialize = "ECDH")]
113    Ecdh,
114    #[strum(serialize = "Ed25519")]
115    Ed25519,
116    #[strum(serialize = "X25519")]
117    X25519,
118    #[strum(serialize = "Ed448")]
119    Ed448,
120    #[strum(serialize = "X448")]
121    X448,
122    #[strum(serialize = "AES-CTR")]
123    AesCtr,
124    #[strum(serialize = "AES-CBC")]
125    AesCbc,
126    #[strum(serialize = "AES-GCM")]
127    AesGcm,
128    #[strum(serialize = "AES-KW")]
129    AesKw,
130    #[strum(serialize = "HMAC")]
131    Hmac,
132    #[strum(serialize = "SHA-1")]
133    Sha1,
134    #[strum(serialize = "SHA-256")]
135    Sha256,
136    #[strum(serialize = "SHA-384")]
137    Sha384,
138    #[strum(serialize = "SHA-512")]
139    Sha512,
140    #[strum(serialize = "HKDF")]
141    Hkdf,
142    #[strum(serialize = "PBKDF2")]
143    Pbkdf2,
144    #[strum(serialize = "ML-KEM-512")]
145    MlKem512,
146    #[strum(serialize = "ML-KEM-768")]
147    MlKem768,
148    #[strum(serialize = "ML-KEM-1024")]
149    MlKem1024,
150    #[strum(serialize = "MLKEM768-X25519")]
151    MlKem768X25519,
152    #[strum(serialize = "ML-DSA-44")]
153    MlDsa44,
154    #[strum(serialize = "ML-DSA-65")]
155    MlDsa65,
156    #[strum(serialize = "ML-DSA-87")]
157    MlDsa87,
158    #[strum(serialize = "AES-OCB")]
159    AesOcb,
160    #[strum(serialize = "ChaCha20-Poly1305")]
161    ChaCha20Poly1305,
162    #[strum(serialize = "SHA3-256")]
163    Sha3_256,
164    #[strum(serialize = "SHA3-384")]
165    Sha3_384,
166    #[strum(serialize = "SHA3-512")]
167    Sha3_512,
168    #[strum(serialize = "cSHAKE128")]
169    CShake128,
170    #[strum(serialize = "cSHAKE256")]
171    CShake256,
172    #[strum(serialize = "TurboSHAKE128")]
173    TurboShake128,
174    #[strum(serialize = "TurboSHAKE256")]
175    TurboShake256,
176    #[strum(serialize = "KT128")]
177    Kt128,
178    #[strum(serialize = "KT256")]
179    Kt256,
180    #[strum(serialize = "KMAC128")]
181    Kmac128,
182    #[strum(serialize = "KMAC256")]
183    Kmac256,
184    #[strum(serialize = "Argon2d")]
185    Argon2D,
186    #[strum(serialize = "Argon2i")]
187    Argon2I,
188    #[strum(serialize = "Argon2id")]
189    Argon2ID,
190}
191
192impl CryptoAlgorithm {
193    /// <https://w3c.github.io/webcrypto/#recognized-algorithm-name>
194    fn as_str(&self) -> &'static str {
195        (*self).into()
196    }
197
198    fn from_str_ignore_case(algorithm_name: &str) -> Fallible<CryptoAlgorithm> {
199        Self::VARIANTS
200            .iter()
201            .find(|algorithm| algorithm.as_str().eq_ignore_ascii_case(algorithm_name))
202            .cloned()
203            .ok_or(Error::NotSupported(Some(format!(
204                "Unsupported algorithm: {algorithm_name}"
205            ))))
206    }
207}
208
209/// <https://w3c.github.io/webcrypto/#subtlecrypto-interface>
210#[dom_struct]
211pub struct SubtleCrypto<D: DomTypes> {
212    reflector_: Reflector,
213    #[no_trace = "PhantomData does not exist"]
214    phantom: PhantomData<D>,
215}
216
217impl<D> SubtleCrypto<D>
218where
219    D: Equivalence,
220    Self: DomGlobalGeneric<D>,
221{
222    fn new_inherited() -> SubtleCrypto<D> {
223        SubtleCrypto {
224            reflector_: Reflector::new(),
225            phantom: PhantomData,
226        }
227    }
228
229    pub(crate) fn new(cx: &mut JSContext, global: &D::GlobalScope) -> DomRoot<SubtleCrypto<D>> {
230        reflect_dom_object_with_wrap::<D, _, _>(
231            cx,
232            Box::new(SubtleCrypto::new_inherited()),
233            global,
234            SubtleCryptoWrap::<D>,
235        )
236    }
237
238    /// Queue a global task on the crypto task source, given realm's global object, to resolve
239    /// promise with the result of creating an ArrayBuffer in realm, containing data. If it fails
240    /// to create buffer source, reject promise with a JSFailedError.
241    fn resolve_promise_with_data(
242        &self,
243        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
244        data: Zeroizing<Vec<u8>>,
245    ) {
246        let trusted_promise = promise.to_trusted();
247        self.global_from_reflector()
248            .queue_crypto_task_source(task!(resolve_data: move |cx| {
249                let promise = trusted_promise.root(cx);
250
251                rooted!(&in(cx) let mut array_buffer_ptr = ptr::null_mut::<JSObject>());
252                match create_buffer_source::<ArrayBufferU8>(cx,
253                    &data,
254                    array_buffer_ptr.handle_mut(),
255                ) {
256                    Ok(_) => promise.resolve_native(cx, &*array_buffer_ptr),
257                    Err(_) => promise.reject_error(cx, Error::JSFailed),
258                }
259            }));
260    }
261
262    /// Queue a global task on the crypto task source, given realm's global object, to resolve
263    /// promise with the result of converting a JsonWebKey dictionary to an ECMAScript Object in
264    /// realm, as defined by [WebIDL].
265    fn resolve_promise_with_jwk(
266        &self,
267        cx: &mut JSContext,
268        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
269        jwk: Box<JsonWebKey>,
270    ) {
271        // NOTE: Serialize the JsonWebKey dictionary by stringifying it, in order to pass it to
272        // other threads.
273        let stringified_jwk = match jwk.stringify(cx) {
274            Ok(stringified_jwk) => Zeroizing::new(stringified_jwk.to_string()),
275            Err(error) => {
276                self.reject_promise_with_error(promise, error);
277                return;
278            },
279        };
280
281        let trusted_subtle = Trusted::new(self);
282        let trusted_promise = promise.to_trusted();
283        self.global_from_reflector()
284            .queue_crypto_task_source(task!(resolve_jwk: move |cx| {
285                let subtle = trusted_subtle.root();
286                let promise = trusted_promise.root(cx);
287
288                match JsonWebKey::parse(cx, stringified_jwk.as_bytes()) {
289                    Ok(jwk) => {
290                        rooted!(&in(cx) let mut rval = UndefinedValue());
291                        jwk.to_jsval(cx, rval.handle_mut());
292                        rooted!(&in(cx) let mut object = rval.to_object());
293                        promise.resolve_native(cx, &*object);
294                    },
295                    Err(error) => {
296                        subtle.reject_promise_with_error(&promise, error);
297                        return;
298                    },
299                }
300            }));
301    }
302
303    /// Queue a global task on the crypto task source, given realm's global object, to resolve
304    /// promise with a CryptoKey.
305    fn resolve_promise_with_key(
306        &self,
307        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
308        key: &CryptoKey<D>,
309    ) {
310        let trusted_key = Trusted::new(key);
311        let trusted_promise = promise.to_trusted();
312        self.global_from_reflector()
313            .queue_crypto_task_source(task!(resolve_key: move |cx| {
314                let key = trusted_key.root();
315                let promise = trusted_promise.root(cx);
316                promise.resolve_native(cx, &key);
317            }));
318    }
319
320    /// Queue a global task on the crypto task source, given realm's global object, to resolve
321    /// promise with a CryptoKeyPair.
322    fn resolve_promise_with_key_pair(
323        &self,
324        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
325        key_pair: &CryptoKeyPair<D>,
326    ) {
327        let trusted_private_key = key_pair.privateKey.as_deref().map(Trusted::new);
328        let trusted_public_key = key_pair.publicKey.as_deref().map(Trusted::new);
329        let trusted_promise = promise.to_trusted();
330        self.global_from_reflector()
331            .queue_crypto_task_source(task!(resolve_key: move |cx| {
332                let key_pair = RootedTraceableBox::new(CryptoKeyPair::<D> {
333                    privateKey: trusted_private_key.map(|trusted_key| trusted_key.root().as_traced()),
334                    publicKey: trusted_public_key.map(|trusted_key| trusted_key.root().as_traced()),
335                });
336                let promise = trusted_promise.root(cx);
337                promise.resolve_native(cx, &key_pair);
338            }));
339    }
340
341    /// Queue a global task on the crypto task source, given realm's global object, to resolve
342    /// promise with a bool value.
343    fn resolve_promise_with_bool(
344        &self,
345        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
346        result: bool,
347    ) {
348        let trusted_promise = promise.to_trusted();
349        self.global_from_reflector()
350            .queue_crypto_task_source(task!(resolve_bool: move |cx| {
351                let promise = trusted_promise.root(cx);
352                promise.resolve_native(cx, &result);
353            }));
354    }
355
356    /// Queue a global task on the crypto task source, given realm's global object, to reject
357    /// promise with an error.
358    fn reject_promise_with_error(
359        &self,
360        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
361        error: Error,
362    ) {
363        let trusted_promise = promise.to_trusted();
364        self.global_from_reflector()
365            .queue_crypto_task_source(task!(reject_error: move |cx| {
366                let promise = trusted_promise.root(cx);
367                promise.reject_error(cx, error);
368            }));
369    }
370
371    /// Queue a global task on the crypto task source, given realm's global object, to resolve
372    /// promise with the result of converting EncapsulatedKey to an ECMAScript Object in realm, as
373    /// defined by [WebIDL].
374    fn resolve_promise_with_encapsulated_key(
375        &self,
376        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
377        encapsulated_key: EncapsulatedKey<D>,
378    ) {
379        let trusted_promise = promise.to_trusted();
380        self.global_from_reflector().queue_crypto_task_source(
381            task!(resolve_encapsulated_key: move |cx| {
382                let promise = trusted_promise.root(cx);
383                promise.resolve_native(cx, &encapsulated_key);
384            }),
385        );
386    }
387
388    /// Queue a global task on the crypto task source, given realm's global object, to resolve
389    /// promise with the result of converting EncapsulateBits to an ECMAScript Object in realm, as
390    /// defined by [WebIDL].
391    fn resolve_promise_with_encapsulated_bits(
392        &self,
393        promise: &<D::Promise as PromiseHelpers<D>>::StackRoot,
394        encapsulated_bits: EncapsulatedBits,
395    ) {
396        let trusted_promise = promise.to_trusted();
397        self.global_from_reflector().queue_crypto_task_source(
398            task!(resolve_encapsulated_bits: move |cx| {
399                let promise = trusted_promise.root(cx);
400                promise.resolve_native(cx, &encapsulated_bits);
401            }),
402        );
403    }
404}
405
406impl<D> SubtleCryptoMethods<D> for SubtleCrypto<D>
407where
408    D: Equivalence,
409    Self: DomGlobalGeneric<D>,
410{
411    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-encrypt>
412    fn Encrypt(
413        &self,
414        cx: &mut CurrentRealm,
415        algorithm: AlgorithmIdentifier,
416        key: &CryptoKey<D>,
417        data: ArrayBufferViewOrArrayBuffer,
418    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
419        // Step 1. Let algorithm and key be the algorithm and key parameters passed to the
420        // encrypt() method, respectively.
421        // NOTE: We did that in method parameter.
422
423        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
424        // to algorithm and op set to "encrypt".
425        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
426        let normalized_algorithm = match normalize_algorithm::<EncryptOperation>(cx, &algorithm) {
427            Ok(normalized_algorithm) => normalized_algorithm,
428            Err(error) => {
429                let promise = D::Promise::new_in_realm(cx);
430                promise.reject_error(cx, error);
431                return promise;
432            },
433        };
434
435        // Step 4. Let data be the result of getting a copy of the bytes held by the data parameter
436        // passed to the encrypt() method.
437        let data = Zeroizing::new(get_buffer_source_copy((&data).into()));
438
439        // Step 5. Let realm be the relevant realm of this.
440        // Step 6. Let promise be a new Promise.
441        let promise = D::Promise::new_in_realm(cx);
442
443        // Step 7. Return promise and perform the remaining steps in parallel.
444        let this = Trusted::new(self);
445        let trusted_promise = promise.to_trusted();
446        let trusted_key = Trusted::new(key);
447        self.global_from_reflector()
448            .queue_dom_manipulation_task_source(task!(encrypt: move |cx| {
449                let subtle = this.root();
450                let promise = &trusted_promise.root(cx);
451                let key = trusted_key.root();
452
453                // Step 8. If the following steps or referenced procedures say to throw an error,
454                // queue a global task on the crypto task source, given realm's global object, to
455                // reject promise with the returned error; and then terminate the algorithm.
456
457                // Step 9. If the name member of normalizedAlgorithm is not equal to the name
458                // attribute of the [[algorithm]] internal slot of key then throw an
459                // InvalidAccessError.
460                if normalized_algorithm.name() != key.algorithm().name() {
461                    subtle.reject_promise_with_error(promise,
462                        Error::InvalidAccess(Some(
463                            "Algorithm's name does not equal key algorithm name".into()
464                        )));
465                    return;
466                }
467
468                // Step 10. If the [[usages]] internal slot of key does not contain an entry that
469                // is "encrypt", then throw an InvalidAccessError.
470                if !key.usages().contains(&KeyUsage::Encrypt) {
471                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
472                        "Key usages does not contain 'encrypt' entry".into()
473                    )));
474                    return;
475                }
476
477                // Step 11. Let ciphertext be the result of performing the encrypt operation
478                // specified by normalizedAlgorithm using algorithm and key and with data as
479                // plaintext.
480                let ciphertext = match normalized_algorithm.encrypt(&key, &data) {
481                    Ok(ciphertext) => ciphertext,
482                    Err(error) => {
483                        subtle.reject_promise_with_error(promise, error);
484                        return;
485                    },
486                };
487
488                // Step 12. Queue a global task on the crypto task source, given realm's global
489                // object, to perform the remaining steps.
490                // Step 13. Let result be the result of creating an ArrayBuffer in realm,
491                // containing ciphertext.
492                // Step 14. Resolve promise with result.
493                subtle.resolve_promise_with_data(promise, ciphertext.into());
494            }));
495        promise
496    }
497
498    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-decrypt>
499    fn Decrypt(
500        &self,
501        cx: &mut CurrentRealm,
502        algorithm: AlgorithmIdentifier,
503        key: &CryptoKey<D>,
504        data: ArrayBufferViewOrArrayBuffer,
505    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
506        // Step 1. Let algorithm and key be the algorithm and key parameters passed to the
507        // decrypt() method, respectively.
508        // NOTE: We did that in method parameter.
509
510        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
511        // to algorithm and op set to "decrypt".
512        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
513        let normalized_algorithm = match normalize_algorithm::<DecryptOperation>(cx, &algorithm) {
514            Ok(normalized_algorithm) => normalized_algorithm,
515            Err(error) => {
516                let promise = D::Promise::new_in_realm(cx);
517                promise.reject_error(cx, error);
518                return promise;
519            },
520        };
521
522        // Step 4. Let data be the result of getting a copy of the bytes held by the data parameter
523        // passed to the decrypt() method.
524        let data = get_buffer_source_copy((&data).into());
525
526        // Step 5. Let realm be the relevant realm of this.
527        // Step 6. Let promise be a new Promise.
528        let promise = D::Promise::new_in_realm(cx);
529
530        // Step 7. Return promise and perform the remaining steps in parallel.
531        let this = Trusted::new(self);
532        let trusted_promise = promise.to_trusted();
533        let trusted_key = Trusted::new(key);
534        self.global_from_reflector()
535            .queue_dom_manipulation_task_source(task!(decrypt: move |cx| {
536                let subtle = this.root();
537                let promise = &trusted_promise.root(cx);
538                let key = trusted_key.root();
539
540                // Step 8. If the following steps or referenced procedures say to throw an error,
541                // queue a global task on the crypto task source, given realm's global object, to
542                // reject promise with the returned error; and then terminate the algorithm.
543
544                // Step 9. If the name member of normalizedAlgorithm is not equal to the name
545                // attribute of the [[algorithm]] internal slot of key then throw an
546                // InvalidAccessError.
547                if normalized_algorithm.name() != key.algorithm().name() {
548                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
549                        "Normalized algorithm name does not equal key algorithm name".into()
550                    )));
551                    return;
552                }
553
554                // Step 10. If the [[usages]] internal slot of key does not contain an entry that
555                // is "decrypt", then throw an InvalidAccessError.
556                if !key.usages().contains(&KeyUsage::Decrypt) {
557                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
558                        "Key usages does not contain 'decrypt' entry".into()
559                    )));
560                    return;
561                }
562
563                // Step 11. Let plaintext be the result of performing the decrypt operation
564                // specified by normalizedAlgorithm using key and algorithm and with data as
565                // ciphertext.
566                let plaintext = match normalized_algorithm.decrypt(&key, &data) {
567                    Ok(plaintext) => Zeroizing::new(plaintext),
568                    Err(error) => {
569                        subtle.reject_promise_with_error(promise, error);
570                        return;
571                    },
572                };
573
574                // Step 12. Queue a global task on the crypto task source, given realm's global
575                // object, to perform the remaining steps.
576                // Step 13. Let result be the result of creating an ArrayBuffer in realm,
577                // containing plaintext.
578                // Step 14. Resolve promise with result.
579                subtle.resolve_promise_with_data(promise, plaintext);
580            }));
581        promise
582    }
583
584    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-sign>
585    fn Sign(
586        &self,
587        cx: &mut CurrentRealm,
588        algorithm: AlgorithmIdentifier,
589        key: &CryptoKey<D>,
590        data: ArrayBufferViewOrArrayBuffer,
591    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
592        // Step 1. Let algorithm and key be the algorithm and key parameters passed to the sign()
593        // method, respectively.
594        // NOTE: We did that in method parameter.
595
596        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
597        // to algorithm and op set to "sign".
598        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
599        let normalized_algorithm = match normalize_algorithm::<SignOperation>(cx, &algorithm) {
600            Ok(normalized_algorithm) => normalized_algorithm,
601            Err(error) => {
602                let promise = D::Promise::new_in_realm(cx);
603                promise.reject_error(cx, error);
604                return promise;
605            },
606        };
607
608        // Step 4. Let data be the result of getting a copy of the bytes held by the data parameter
609        // passed to the sign() method.
610        let data = get_buffer_source_copy((&data).into());
611
612        // Step 5. Let realm be the relevant realm of this.
613        // Step 6. Let promise be a new Promise.
614        let promise = D::Promise::new_in_realm(cx);
615
616        // Step 7. Return promise and perform the remaining steps in parallel.
617        let this = Trusted::new(self);
618        let trusted_promise = promise.to_trusted();
619        let trusted_key = Trusted::new(key);
620        self.global_from_reflector()
621            .queue_dom_manipulation_task_source(task!(sign: move |cx| {
622                let subtle = this.root();
623                let promise = &trusted_promise.root(cx);
624                let key = trusted_key.root();
625
626                // Step 8. If the following steps or referenced procedures say to throw an error,
627                // queue a global task on the crypto task source, given realm's global object, to
628                // reject promise with the returned error; and then terminate the algorithm.
629
630                // Step 9. If the name member of normalizedAlgorithm is not equal to the name
631                // attribute of the [[algorithm]] internal slot of key then throw an
632                // InvalidAccessError.
633                if normalized_algorithm.name() != key.algorithm().name() {
634                    subtle.reject_promise_with_error(promise,Error::InvalidAccess(Some(
635                        "Normalized algorithm name does not equal key algorithm name".into()
636                    )));
637                    return;
638                }
639
640                // Step 10. If the [[usages]] internal slot of key does not contain an entry that
641                // is "sign", then throw an InvalidAccessError.
642                if !key.usages().contains(&KeyUsage::Sign) {
643                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
644                        "Key usages does not contain 'sign' entry".into()
645                    )));
646                    return;
647                }
648
649                // Step 11. Let signature be the result of performing the sign operation specified
650                // by normalizedAlgorithm using key and algorithm and with data as message.
651                let signature = match normalized_algorithm.sign(&key, &data) {
652                    Ok(signature) => signature,
653                    Err(error) => {
654                        subtle.reject_promise_with_error(promise, error);
655                        return;
656                    },
657                };
658
659                // Step 12. Queue a global task on the crypto task source, given realm's global
660                // object, to perform the remaining steps.
661                // Step 13. Let result be the result of creating an ArrayBuffer in realm,
662                // containing signature.
663                // Step 14. Resolve promise with result.
664                subtle.resolve_promise_with_data(promise, signature.into());
665            }));
666        promise
667    }
668
669    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-verify>
670    fn Verify(
671        &self,
672        cx: &mut CurrentRealm,
673        algorithm: AlgorithmIdentifier,
674        key: &CryptoKey<D>,
675        signature: ArrayBufferViewOrArrayBuffer,
676        data: ArrayBufferViewOrArrayBuffer,
677    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
678        // Step 1. Let algorithm and key be the algorithm and key parameters passed to the verify()
679        // method, respectively.
680        // NOTE: We did that in method parameter.
681
682        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to
683        // algorithm and op set to "verify".
684        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
685        let normalized_algorithm = match normalize_algorithm::<VerifyOperation>(cx, &algorithm) {
686            Ok(algorithm) => algorithm,
687            Err(error) => {
688                let promise = D::Promise::new_in_realm(cx);
689                promise.reject_error(cx, error);
690                return promise;
691            },
692        };
693
694        // Step 4. Let signature be the result of getting a copy of the bytes held by the signature
695        // parameter passed to the verify() method.
696        let signature = get_buffer_source_copy((&signature).into());
697
698        // Step 5. Let data be the result of getting a copy of the bytes held by the data parameter
699        // passed to the verify() method.
700        let data = get_buffer_source_copy((&data).into());
701
702        // Step 6. Let realm be the relevant realm of this.
703        // Step 7. Let promise be a new Promise.
704        let promise = D::Promise::new_in_realm(cx);
705
706        // Step 8. Return promise and perform the remaining steps in parallel.
707        let this = Trusted::new(self);
708        let trusted_promise = promise.to_trusted();
709        let trusted_key = Trusted::new(key);
710        self.global_from_reflector()
711            .queue_dom_manipulation_task_source(task!(sign: move |cx| {
712                let subtle = this.root();
713                let promise = &trusted_promise.root(cx);
714                let key = trusted_key.root();
715
716                // Step 9. If the following steps or referenced procedures say to throw an error,
717                // queue a global task on the crypto task source, given realm's global object, to
718                // reject promise with the returned error; and then terminate the algorithm.
719
720                // Step 10. If the name member of normalizedAlgorithm is not equal to the name
721                // attribute of the [[algorithm]] internal slot of key then throw an
722                // InvalidAccessError.
723                if normalized_algorithm.name() != key.algorithm().name() {
724                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
725                        "Normalized algorithm name does not equal key algorithm name".into()
726                    )));
727                    return;
728                }
729
730                // Step 11. If the [[usages]] internal slot of key does not contain an entry that
731                // is "verify", then throw an InvalidAccessError.
732                if !key.usages().contains(&KeyUsage::Verify) {
733                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
734                        "Key usages does not contain 'verify' entry".into()
735                    )));
736                    return;
737                }
738
739                // Step 12. Let result be the result of performing the verify operation specified
740                // by normalizedAlgorithm using key, algorithm and signature and with data as
741                // message.
742                let result = match normalized_algorithm.verify(&key, &data, &signature) {
743                    Ok(result) => result,
744                    Err(error) => {
745                        subtle.reject_promise_with_error(promise, error);
746                        return;
747                    },
748                };
749
750                // Step 13. Queue a global task on the crypto task source, given realm's global
751                // object, to perform the remaining steps.
752                // Step 14. Resolve promise with result.
753                subtle.resolve_promise_with_bool(promise, result);
754            }));
755        promise
756    }
757
758    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-digest>
759    fn Digest(
760        &self,
761        cx: &mut CurrentRealm,
762        algorithm: AlgorithmIdentifier,
763        data: ArrayBufferViewOrArrayBuffer,
764    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
765        // Step 1. Let algorithm be the algorithm parameter passed to the digest() method.
766        // NOTE: We did that in method parameter.
767
768        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm,
769        // with alg set to algorithm and op set to "digest".
770        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
771        let normalized_algorithm = match normalize_algorithm::<DigestOperation>(cx, &algorithm) {
772            Ok(normalized_algorithm) => normalized_algorithm,
773            Err(error) => {
774                let promise = D::Promise::new_in_realm(cx);
775                promise.reject_error(cx, error);
776                return promise;
777            },
778        };
779
780        // Step 4. Let data be the result of getting a copy of the bytes held by the
781        // data parameter passed to the digest() method.
782        let data = get_buffer_source_copy((&data).into());
783
784        // Step 5. Let realm be the relevant realm of this.
785        // Step 6. Let promise be a new Promise.
786        let promise = D::Promise::new_in_realm(cx);
787
788        // Step 7. Return promise and perform the remaining steps in parallel.
789        let this = Trusted::new(self);
790        let trusted_promise = promise.to_trusted();
791        self.global_from_reflector()
792            .queue_dom_manipulation_task_source(task!(digest_: move |cx| {
793                let subtle = this.root();
794                let promise = &trusted_promise.root(cx);
795
796                // Step 8. If the following steps or referenced procedures say to throw an error,
797                // queue a global task on the crypto task source, given realm's global object, to
798                // reject promise with the returned error; and then terminate the algorithm.
799
800                // Step 9. Let digest be the result of performing the digest operation specified by
801                // normalizedAlgorithm using algorithm, with data as message.
802                let digest = match normalized_algorithm.digest(&data) {
803                    Ok(digest) => digest,
804                    Err(error) => {
805                        subtle.reject_promise_with_error(promise, error);
806                        return;
807                    }
808                };
809
810                // Step 10. Queue a global task on the crypto task source, given realm's global
811                // object, to perform the remaining steps.
812                // Step 11. Let result be the result of creating an ArrayBuffer in realm,
813                // containing digest.
814                // Step 12. Resolve promise with result.
815                subtle.resolve_promise_with_data(promise, digest.into());
816            }));
817        promise
818    }
819
820    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-generateKey>
821    fn GenerateKey(
822        &self,
823        cx: &mut CurrentRealm,
824        algorithm: AlgorithmIdentifier,
825        extractable: bool,
826        key_usages: Vec<KeyUsage>,
827    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
828        // Step 1. Let algorithm, extractable and usages be the algorithm, extractable and
829        // keyUsages parameters passed to the generateKey() method, respectively.
830
831        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
832        // to algorithm and op set to "generateKey".
833        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
834        let promise = D::Promise::new_in_realm(cx);
835        let normalized_algorithm = match normalize_algorithm::<GenerateKeyOperation>(cx, &algorithm)
836        {
837            Ok(normalized_algorithm) => normalized_algorithm,
838            Err(error) => {
839                promise.reject_error(cx, error);
840                return promise;
841            },
842        };
843
844        // Step 4. Let realm be the relevant realm of this.
845        // Step 5. Let promise be a new Promise.
846        // NOTE: We did that in preparation of Step 3.
847
848        // Step 6. Return promise and perform the remaining steps in parallel.
849        let trusted_subtle = Trusted::new(self);
850        let trusted_promise = promise.to_trusted();
851        self.global_from_reflector()
852            .queue_dom_manipulation_task_source(task!(generate_key: move |cx| {
853                let subtle = trusted_subtle.root();
854                let promise = &trusted_promise.root(cx);
855
856                // Step 7. If the following steps or referenced procedures say to throw an error,
857                // queue a global task on the crypto task source, given realm's global object, to
858                // reject promise with the returned error; and then terminate the algorithm.
859
860                // Step 8. Let result be the result of performing the generate key operation
861                // specified by normalizedAlgorithm using algorithm, extractable and usages.
862                let result = match normalized_algorithm.generate_key(
863                    cx,
864                    &*subtle.global_from_reflector(),
865                    extractable,
866                    key_usages,
867                ) {
868                    Ok(result) => result,
869                    Err(error) => {
870                        subtle.reject_promise_with_error(promise, error);
871                        return;
872                    }
873                };
874
875                // Step 9.
876                // If result is a CryptoKey object:
877                //     If the [[type]] internal slot of result is "secret" or "private" and usages
878                //     is empty, then throw a SyntaxError.
879                // If result is a CryptoKeyPair object:
880                //     If the [[usages]] internal slot of the privateKey attribute of result is the
881                //     empty sequence, then throw a SyntaxError.
882                match &result {
883                    CryptoKeyOrCryptoKeyPair::CryptoKey(crpyto_key) => {
884                        if matches!(crpyto_key.Type(), KeyType::Secret | KeyType::Private)
885                            && crpyto_key.usages().is_empty()
886                        {
887                            subtle.reject_promise_with_error(promise, Error::Syntax(Some(
888                                "Crypto key usages is empty".into()
889                            )));
890                            return;
891                        }
892                    },
893                    CryptoKeyOrCryptoKeyPair::CryptoKeyPair(crypto_key_pair) => {
894                        if crypto_key_pair
895                            .privateKey
896                            .as_deref()
897                            .is_none_or(|private_key: &CryptoKey<D>| {
898                                private_key.usages().is_empty()
899                            })
900                        {
901                            subtle.reject_promise_with_error(promise, Error::Syntax(Some(
902                                "Private key usages is an empty sequence".into()
903                            )));
904                            return;
905                        }
906                    }
907                };
908
909                // Step 10. Queue a global task on the crypto task source, given realm's global
910                // object, to perform the remaining steps.
911                // Step 11. Let result be the result of converting result to an ECMAScript Object
912                // in realm, as defined by [WebIDL].
913                // Step 12. Resolve promise with result.
914                match result {
915                    CryptoKeyOrCryptoKeyPair::CryptoKey(key) => {
916                        subtle.resolve_promise_with_key(promise, &key);
917                    },
918                    CryptoKeyOrCryptoKeyPair::CryptoKeyPair(key_pair) => {
919                        subtle.resolve_promise_with_key_pair(promise, &key_pair);
920                    },
921                }
922            }));
923
924        promise
925    }
926
927    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveKey>
928    fn DeriveKey(
929        &self,
930        cx: &mut CurrentRealm,
931        algorithm: AlgorithmIdentifier,
932        base_key: &CryptoKey<D>,
933        derived_key_type: AlgorithmIdentifier,
934        extractable: bool,
935        usages: Vec<KeyUsage>,
936    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
937        // Step 1. Let algorithm, baseKey, derivedKeyType, extractable and usages be the algorithm,
938        // baseKey, derivedKeyType, extractable and keyUsages parameters passed to the deriveKey()
939        // method, respectively.
940        // NOTE: We did that in method parameter.
941
942        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
943        // to algorithm and op set to "deriveBits".
944        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
945        let promise = D::Promise::new_in_realm(cx);
946        let normalized_algorithm =
947            match normalize_algorithm::<DeriveBitsOperation<D>>(cx, &algorithm) {
948                Ok(normalized_algorithm) => normalized_algorithm,
949                Err(error) => {
950                    promise.reject_error(cx, error);
951                    return promise;
952                },
953            };
954
955        // Step 4. Let normalizedDerivedKeyAlgorithmImport be the result of normalizing an
956        // algorithm, with alg set to derivedKeyType and op set to "importKey".
957        // Step 5. If an error occurred, return a Promise rejected with
958        // normalizedDerivedKeyAlgorithmImport.
959        let normalized_derived_key_algorithm_import =
960            match normalize_algorithm::<ImportKeyOperation>(cx, &derived_key_type) {
961                Ok(normalized_algorithm) => normalized_algorithm,
962                Err(error) => {
963                    promise.reject_error(cx, error);
964                    return promise;
965                },
966            };
967
968        // Step 6. Let normalizedDerivedKeyAlgorithmLength be the result of normalizing an
969        // algorithm, with alg set to derivedKeyType and op set to "get key length".
970        // Step 7. If an error occurred, return a Promise rejected with
971        // normalizedDerivedKeyAlgorithmLength.
972        let normalized_derived_key_algorithm_length =
973            match normalize_algorithm::<GetKeyLengthOperation>(cx, &derived_key_type) {
974                Ok(normalized_algorithm) => normalized_algorithm,
975                Err(error) => {
976                    promise.reject_error(cx, error);
977                    return promise;
978                },
979            };
980
981        // Step 8. Let realm be the relevant realm of this.
982        // Step 9. Let promise be a new Promise.
983        // NOTE: We did that in preparation of Step 3.
984
985        // Step 10. Return promise and perform the remaining steps in parallel.
986        let trusted_subtle = Trusted::new(self);
987        let trusted_base_key = Trusted::new(base_key);
988        let trusted_promise = promise.to_trusted();
989        self.global_from_reflector().queue_dom_manipulation_task_source(
990            task!(derive_key: move |cx| {
991                let subtle = trusted_subtle.root();
992                let base_key = trusted_base_key.root();
993                let promise = &trusted_promise.root(cx);
994
995                // Step 11. If the following steps or referenced procedures say to throw an error,
996                // queue a global task on the crypto task source, given realm's global object, to
997                // reject promise with the returned error; and then terminate the algorithm.
998
999                // Step 12. If the name member of normalizedAlgorithm is not equal to the name
1000                // attribute of the [[algorithm]] internal slot of baseKey then throw an
1001                // InvalidAccessError.
1002                if normalized_algorithm.name() != base_key.algorithm().name() {
1003                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1004                        "Normalized algorithm name does not equal name of base key algorithm".into()
1005                    )));
1006                    return;
1007                }
1008
1009                // Step 13. If the [[usages]] internal slot of baseKey does not contain an entry
1010                // that is "deriveKey", then throw an InvalidAccessError.
1011                if !base_key.usages().contains(&KeyUsage::DeriveKey) {
1012                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1013                        "Key usages does not contain 'deriveKey' entry".into()
1014                    )));
1015                    return;
1016                }
1017
1018                // Step 14. Let length be the result of performing the get key length algorithm
1019                // specified by normalizedDerivedKeyAlgorithmLength using derivedKeyType.
1020                let length = match normalized_derived_key_algorithm_length.get_key_length() {
1021                    Ok(length) => length,
1022                    Err(error) => {
1023                        subtle.reject_promise_with_error(promise, error);
1024                        return;
1025                    }
1026                };
1027
1028                // Step 15. Let secret be the result of performing the derive bits operation
1029                // specified by normalizedAlgorithm using key, algorithm and length.
1030                let secret = match normalized_algorithm.derive_bits(&base_key, length) {
1031                    Ok(secret) => Zeroizing::new(secret),
1032                    Err(error) => {
1033                        subtle.reject_promise_with_error(promise, error);
1034                        return;
1035                    }
1036                };
1037
1038                // Step 16. Let result be the result of performing the import key operation
1039                // specified by normalizedDerivedKeyAlgorithmImport using "raw" as format, secret
1040                // as keyData, derivedKeyType as algorithm and using extractable and usages.
1041                // NOTE: Use "raw-secret" instead, according to
1042                // <https://wicg.github.io/webcrypto-modern-algos/#subtlecrypto-interface-keyformat>.
1043                let result = match normalized_derived_key_algorithm_import.import_key(
1044                    cx,
1045                    &*subtle.global_from_reflector(),
1046                    KeyFormat::Raw_secret,
1047                    &secret,
1048                    extractable,
1049                    usages.clone(),
1050                ) {
1051                    Ok(algorithm) => algorithm,
1052                    Err(error) => {
1053                        subtle.reject_promise_with_error(promise, error);
1054                        return;
1055                    },
1056                };
1057
1058                // Step 17. If the [[type]] internal slot of result is "secret" or "private" and
1059                // usages is empty, then throw a SyntaxError.
1060                if matches!(result.Type(), KeyType::Secret | KeyType::Private) && usages.is_empty() {
1061                    subtle.reject_promise_with_error(promise, Error::Syntax(Some(
1062                        "Key usages is empty".into()
1063                    )));
1064                    return;
1065                }
1066
1067                // Step 18. Set the [[extractable]] internal slot of result to extractable.
1068                // Step 19. Set the [[usages]] internal slot of result to the normalized value of
1069                // usages.
1070                // NOTE: Done by the importKey operation in Step 16.
1071
1072                // Step 20. Queue a global task on the crypto task source, given realm's global
1073                // object, to perform the remaining steps.
1074                // Step 20. Let result be the result of converting result to an ECMAScript Object
1075                // in realm, as defined by [WebIDL].
1076                // Step 20. Resolve promise with result.
1077                subtle.resolve_promise_with_key(promise, &result);
1078            }),
1079        );
1080        promise
1081    }
1082
1083    /// <https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-deriveBits>
1084    fn DeriveBits(
1085        &self,
1086        cx: &mut CurrentRealm,
1087        algorithm: AlgorithmIdentifier,
1088        base_key: &CryptoKey<D>,
1089        length: Option<u32>,
1090    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
1091        // Step 1. Let algorithm, baseKey and length, be the algorithm, baseKey and length
1092        // parameters passed to the deriveBits() method, respectively.
1093        // NOTE: We did that in method parameter.
1094
1095        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
1096        // to algorithm and op set to "deriveBits".
1097        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
1098        let promise = D::Promise::new_in_realm(cx);
1099        let normalized_algorithm =
1100            match normalize_algorithm::<DeriveBitsOperation<D>>(cx, &algorithm) {
1101                Ok(normalized_algorithm) => normalized_algorithm,
1102                Err(error) => {
1103                    promise.reject_error(cx, error);
1104                    return promise;
1105                },
1106            };
1107
1108        // Step 4. Let realm be the relevant realm of this.
1109        // Step 5. Let promise be a new Promise.
1110        // NOTE: We did that in preparation of Step 3.
1111
1112        // Step 5. Return promise and perform the remaining steps in parallel.
1113        let trsuted_subtle = Trusted::new(self);
1114        let trusted_base_key = Trusted::new(base_key);
1115        let trusted_promise = promise.to_trusted();
1116        self.global_from_reflector()
1117            .queue_dom_manipulation_task_source(task!(import_key: move |cx| {
1118                let subtle = trsuted_subtle.root();
1119                let base_key = trusted_base_key.root();
1120                let promise = &trusted_promise.root(cx);
1121
1122                // Step 7. If the following steps or referenced procedures say to throw an error,
1123                // queue a global task on the crypto task source, given realm's global object, to
1124                // reject promise with the returned error; and then terminate the algorithm.
1125
1126                // Step 8. If the name member of normalizedAlgorithm is not equal to the name
1127                // attribute of the [[algorithm]] internal slot of baseKey then throw an
1128                // InvalidAccessError.
1129                if normalized_algorithm.name() != base_key.algorithm().name() {
1130                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1131                        "Normalized algorithm name does not equal name of base key algorithm".into()
1132                    )));
1133                    return;
1134                }
1135
1136                // Step 9. If the [[usages]] internal slot of baseKey does not contain an entry
1137                // that is "deriveBits", then throw an InvalidAccessError.
1138                if !base_key.usages().contains(&KeyUsage::DeriveBits) {
1139                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1140                        "Key usages does not contain 'deriveBits' entry".into()
1141                    )));
1142                    return;
1143                }
1144
1145                // Step 10. Let bits be the result of performing the derive bits operation
1146                // specified by normalizedAlgorithm using baseKey, algorithm and length.
1147                let bits = match normalized_algorithm.derive_bits(&base_key, length) {
1148                    Ok(bits) => Zeroizing::new(bits),
1149                    Err(error) => {
1150                        subtle.reject_promise_with_error(promise, error);
1151                        return;
1152                    }
1153                };
1154
1155                // Step 11. Queue a global task on the crypto task source, given realm's global
1156                // object, to perform the remaining steps.
1157                // Step 12. Let result be the result of creating an ArrayBuffer in realm,
1158                // containing bits.
1159                // Step 13. Resolve promise with result.
1160                subtle.resolve_promise_with_data(promise, bits);
1161            }));
1162        promise
1163    }
1164
1165    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey>
1166    fn ImportKey(
1167        &self,
1168        cx: &mut CurrentRealm,
1169        format: KeyFormat,
1170        key_data: ArrayBufferViewOrArrayBufferOrJsonWebKey,
1171        algorithm: AlgorithmIdentifier,
1172        extractable: bool,
1173        key_usages: Vec<KeyUsage>,
1174    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
1175        // Step 1. Let format, algorithm, extractable and usages, be the format, algorithm,
1176        // extractable and keyUsages parameters passed to the importKey() method, respectively.
1177
1178        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
1179        // to algorithm and op set to "importKey".
1180        // Step 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.
1181        let normalized_algorithm = match normalize_algorithm::<ImportKeyOperation>(cx, &algorithm) {
1182            Ok(algorithm) => algorithm,
1183            Err(error) => {
1184                let promise = D::Promise::new_in_realm(cx);
1185                promise.reject_error(cx, error);
1186                return promise;
1187            },
1188        };
1189
1190        // Step 4.
1191        let key_data = match format {
1192            // If format is equal to the string "jwk":
1193            KeyFormat::Jwk => {
1194                match key_data {
1195                    ArrayBufferViewOrArrayBufferOrJsonWebKey::ArrayBufferView(_) |
1196                    ArrayBufferViewOrArrayBufferOrJsonWebKey::ArrayBuffer(_) => {
1197                        // Step 4.1. If the keyData parameter passed to the importKey() method is
1198                        // not a JsonWebKey dictionary, throw a TypeError.
1199                        let promise = D::Promise::new_in_realm(cx);
1200                        promise.reject_error(
1201                            cx,
1202                            Error::Type(c"The keyData type does not match the format".to_owned()),
1203                        );
1204                        return promise;
1205                    },
1206
1207                    ArrayBufferViewOrArrayBufferOrJsonWebKey::JsonWebKey(jwk) => {
1208                        // Step 4.2. Let keyData be the keyData parameter passed to the importKey()
1209                        // method.
1210                        //
1211                        // NOTE: Serialize JsonWebKey throught stringifying it.
1212                        // JsonWebKey::stringify internally relies on ToJSON, so it will raise an
1213                        // exception when a JS error is thrown. When this happens, we report the
1214                        // error.
1215                        match jwk.stringify(cx) {
1216                            Ok(stringified) => {
1217                                Zeroizing::new(stringified.as_bytes(cx.no_gc()).to_vec())
1218                            },
1219                            Err(error) => {
1220                                let promise = D::Promise::new_in_realm(cx);
1221                                promise.reject_error(cx, error);
1222                                return promise;
1223                            },
1224                        }
1225                    },
1226                }
1227            },
1228            // Otherwise:
1229            _ => {
1230                match &key_data {
1231                    // Step 4.1. If the keyData parameter passed to the importKey() method is a
1232                    // JsonWebKey dictionary, throw a TypeError.
1233                    ArrayBufferViewOrArrayBufferOrJsonWebKey::JsonWebKey(_) => {
1234                        let promise = D::Promise::new_in_realm(cx);
1235                        promise.reject_error(
1236                            cx,
1237                            Error::Type(c"The keyData type does not match the format".to_owned()),
1238                        );
1239                        return promise;
1240                    },
1241
1242                    // Step 4.2. Let keyData be the result of getting a copy of the bytes held by
1243                    // the keyData parameter passed to the importKey() method.
1244                    ArrayBufferViewOrArrayBufferOrJsonWebKey::ArrayBufferView(view) => {
1245                        Zeroizing::new(get_buffer_source_copy(view.into()))
1246                    },
1247                    ArrayBufferViewOrArrayBufferOrJsonWebKey::ArrayBuffer(buffer) => {
1248                        Zeroizing::new(get_buffer_source_copy(buffer.into()))
1249                    },
1250                }
1251            },
1252        };
1253
1254        // Step 5. Let realm be the relevant realm of this.
1255        // Step 6. Let promise be a new Promise.
1256        let promise = D::Promise::new_in_realm(cx);
1257
1258        // Step 7. Return promise and perform the remaining steps in parallel.
1259        let this = Trusted::new(self);
1260        let trusted_promise = promise.to_trusted();
1261        self.global_from_reflector()
1262            .queue_dom_manipulation_task_source(task!(import_key: move |cx| {
1263                let subtle = this.root();
1264                let promise = &trusted_promise.root(cx);
1265
1266                // Step 8. If the following steps or referenced procedures say to throw an error,
1267                // queue a global task on the crypto task source, given realm's global object, to
1268                // reject promise with the returned error; and then terminate the algorithm.
1269
1270                // Step 9. Let result be the CryptoKey object that results from performing the
1271                // import key operation specified by normalizedAlgorithm using keyData, algorithm,
1272                // format, extractable and usages.
1273                let result = match normalized_algorithm.import_key(
1274                    cx,
1275                    &*subtle.global_from_reflector(),
1276                    format,
1277                    &key_data,
1278                    extractable,
1279                    key_usages.clone(),
1280                ) {
1281                    Ok(key) => key,
1282                    Err(error) => {
1283                        subtle.reject_promise_with_error(promise, error);
1284                        return;
1285                    },
1286                };
1287
1288                // Step 10. If the [[type]] internal slot of result is "secret" or "private" and
1289                // usages is empty, then throw a SyntaxError.
1290                if matches!(result.Type(), KeyType::Secret | KeyType::Private) &&
1291                    key_usages.is_empty()
1292                {
1293                    subtle.reject_promise_with_error(promise, Error::Syntax(Some(
1294                        "Key usages is empty".into()
1295                    )));
1296                    return;
1297                }
1298
1299                // Step 11. Set the [[extractable]] internal slot of result to extractable.
1300                // Step 12. Set the [[usages]] internal slot of result to the normalized value of
1301                // usages.
1302                // NOTE: Done by the importKey operation in Step 9.
1303
1304                // Step 13. Queue a global task on the crypto task source, given realm's global
1305                // object, to perform the remaining steps.
1306                // Step 14. Let result be the result of converting result to an ECMAScript Object
1307                // in realm, as defined by [WebIDL].
1308                // Step 15. Resolve promise with result.
1309                subtle.resolve_promise_with_key(promise, &result);
1310            }));
1311
1312        promise
1313    }
1314
1315    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-exportKey>
1316    fn ExportKey(
1317        &self,
1318        cx: &mut CurrentRealm,
1319        format: KeyFormat,
1320        key: &CryptoKey<D>,
1321    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
1322        // Step 1. Let format and key be the format and key parameters passed to the exportKey()
1323        // method, respectively.
1324        // NOTE: We did that in method parameter.
1325
1326        // Step 2. Let realm be the relevant realm of this.
1327        // Step 3. Let promise be a new Promise.
1328        let promise = D::Promise::new_in_realm(cx);
1329
1330        // Step 4. Return promise and perform the remaining steps in parallel.
1331        let trusted_subtle = Trusted::new(self);
1332        let trusted_promise = promise.to_trusted();
1333        let trusted_key = Trusted::new(key);
1334        self.global_from_reflector()
1335            .queue_dom_manipulation_task_source(task!(export_key: move |cx| {
1336                let subtle = trusted_subtle.root();
1337                let promise = &trusted_promise.root(cx);
1338                let key = trusted_key.root();
1339
1340                // Step 5. If the following steps or referenced procedures say to throw an error,
1341                // queue a global task on the crypto task source, given realm's global object, to
1342                // reject promise with the returned error; and then terminate the algorithm.
1343
1344                // Step 6. If the name member of the [[algorithm]] internal slot of key does not
1345                // identify a registered algorithm that supports the export key operation, then
1346                // throw a NotSupportedError.
1347                //
1348                // NOTE: We rely on [`normalize_algorithm`] to check whether the algorithm supports
1349                // the export key operation.
1350                let export_key_algorithm = match normalize_algorithm::<ExportKeyOperation>(
1351                    cx,
1352                    &AlgorithmIdentifier::String(DOMString::from(key.algorithm().name().as_str())),
1353                ) {
1354                    Ok(normalized_algorithm) => normalized_algorithm,
1355                    Err(error) => {
1356                        subtle.reject_promise_with_error(promise, error);
1357                        return;
1358                    },
1359                };
1360
1361                // Step 7. If the [[extractable]] internal slot of key is false, then throw an
1362                // InvalidAccessError.
1363                if !key.Extractable() {
1364                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1365                        "Key is not extractable".into()
1366                    )));
1367                    return;
1368                }
1369
1370                // Step 8. Let result be the result of performing the export key operation
1371                // specified by the [[algorithm]] internal slot of key using key and format.
1372                let result = match export_key_algorithm.export_key(format, &key) {
1373                    Ok(exported_key) => exported_key,
1374                    Err(error) => {
1375                        subtle.reject_promise_with_error(promise, error);
1376                        return;
1377                    },
1378                };
1379
1380                // Step 9. Queue a global task on the crypto task source, given realm's global
1381                // object, to perform the remaining steps.
1382                // Step 10.
1383                // If format is equal to the string "jwk":
1384                //     Let result be the result of converting result to an ECMAScript Object in
1385                //     realm, as defined by [WebIDL].
1386                // Otherwise:
1387                //     Let result be the result of creating an ArrayBuffer in realm, containing
1388                //     result.
1389                // Step 11. Resolve promise with result.
1390                // NOTE: We determine the format by pattern matching on result, which is an
1391                // ExportedKey enum.
1392                match result {
1393                    ExportedKey::Bytes(bytes) => {
1394                        subtle.resolve_promise_with_data(promise, bytes);
1395                    },
1396                    ExportedKey::Jwk(jwk) => {
1397                        subtle.resolve_promise_with_jwk(cx, promise, jwk);
1398                    },
1399                }
1400            }));
1401        promise
1402    }
1403
1404    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-wrapKey>
1405    fn WrapKey(
1406        &self,
1407        cx: &mut CurrentRealm,
1408        format: KeyFormat,
1409        key: &CryptoKey<D>,
1410        wrapping_key: &CryptoKey<D>,
1411        algorithm: AlgorithmIdentifier,
1412    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
1413        // Step 1. Let format, key, wrappingKey and algorithm be the format, key, wrappingKey and
1414        // wrapAlgorithm parameters passed to the wrapKey() method, respectively.
1415        // NOTE: We did that in method parameter.
1416
1417        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
1418        // to algorithm and op set to "wrapKey".
1419        // Step 3. If an error occurred, let normalizedAlgorithm be the result of normalizing an
1420        // algorithm, with alg set to algorithm and op set to "encrypt".
1421        // Step 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
1422        enum WrapKeyAlgorithmOrEncryptAlgorithm {
1423            WrapKeyAlgorithm(WrapKeyAlgorithm),
1424            EncryptAlgorithm(EncryptAlgorithm),
1425        }
1426        let normalized_algorithm = if let Ok(algorithm) =
1427            normalize_algorithm::<WrapKeyOperation>(cx, &algorithm)
1428        {
1429            WrapKeyAlgorithmOrEncryptAlgorithm::WrapKeyAlgorithm(algorithm)
1430        } else {
1431            match normalize_algorithm::<EncryptOperation>(cx, &algorithm) {
1432                Ok(algorithm) => WrapKeyAlgorithmOrEncryptAlgorithm::EncryptAlgorithm(algorithm),
1433                Err(error) => {
1434                    let promise = D::Promise::new_in_realm(cx);
1435                    promise.reject_error(cx, error);
1436                    return promise;
1437                },
1438            }
1439        };
1440
1441        // Step 5. Let realm be the relevant realm of this.
1442        // Step 6. Let promise be a new Promise.
1443        let promise = D::Promise::new_in_realm(cx);
1444
1445        // Step 7. Return promise and perform the remaining steps in parallel.
1446        let trusted_subtle = Trusted::new(self);
1447        let trusted_key = Trusted::new(key);
1448        let trusted_wrapping_key = Trusted::new(wrapping_key);
1449        let trusted_promise = promise.to_trusted();
1450        self.global_from_reflector()
1451            .queue_dom_manipulation_task_source(task!(wrap_key: move |cx| {
1452                let subtle = trusted_subtle.root();
1453                let key = trusted_key.root();
1454                let wrapping_key = trusted_wrapping_key.root();
1455                let promise = &trusted_promise.root(cx);
1456
1457                // Step 8. If the following steps or referenced procedures say to throw an error,
1458                // queue a global task on the crypto task source, given realm's global object, to
1459                // reject promise with the returned error; and then terminate the algorithm.
1460
1461                // Step 9. If the name member of normalizedAlgorithm is not equal to the name
1462                // attribute of the [[algorithm]] internal slot of wrappingKey then throw an
1463                // InvalidAccessError.
1464                let normalized_algorithm_name = match &normalized_algorithm {
1465                    WrapKeyAlgorithmOrEncryptAlgorithm::WrapKeyAlgorithm(algorithm) => {
1466                        algorithm.name()
1467                    },
1468                    WrapKeyAlgorithmOrEncryptAlgorithm::EncryptAlgorithm(algorithm) => {
1469                        algorithm.name()
1470                    },
1471                };
1472                if normalized_algorithm_name != wrapping_key.algorithm().name() {
1473                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1474                        "Normalized algorithm name does not equal name of wrapping key algorithm"
1475                            .into()
1476                    )));
1477                    return;
1478                }
1479
1480                // Step 10. If the [[usages]] internal slot of wrappingKey does not contain an
1481                // entry that is "wrapKey", then throw an InvalidAccessError.
1482                if !wrapping_key.usages().contains(&KeyUsage::WrapKey) {
1483                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1484                        "Wrapping key usages does not contain 'wrapKey' entry".into()
1485                    )));
1486                    return;
1487                }
1488
1489                // Step 11. If the algorithm identified by the [[algorithm]] internal slot of key
1490                // does not support the export key operation, then throw a NotSupportedError.
1491                //
1492                // NOTE: We rely on [`normalize_algorithm`] to check whether the algorithm supports
1493                // the export key operation.
1494                let export_key_algorithm = match normalize_algorithm::<ExportKeyOperation>(
1495                    cx,
1496                    &AlgorithmIdentifier::String(DOMString::from(key.algorithm().name().as_str())),
1497                ) {
1498                    Ok(normalized_algorithm) => normalized_algorithm,
1499                    Err(error) => {
1500                        subtle.reject_promise_with_error(promise, error);
1501                        return;
1502                    },
1503                };
1504
1505                // Step 12. If the [[extractable]] internal slot of key is false, then throw an
1506                // InvalidAccessError.
1507                if !key.Extractable() {
1508                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1509                        "Key is not extractable".into()
1510                    )));
1511                    return;
1512                }
1513
1514                // Step 13. Let exportedKey be the result of performing the export key operation
1515                // specified by the [[algorithm]] internal slot of key using key and format.
1516                let exported_key = match export_key_algorithm.export_key(format, &key) {
1517                    Ok(exported_key) => exported_key,
1518                    Err(error) => {
1519                        subtle.reject_promise_with_error(promise, error);
1520                        return;
1521                    },
1522                };
1523
1524                // Step 14.
1525                // If format is equal to the string "jwk":
1526                //     Step 14.1. Let json be the result of representing exportedKey as a UTF-16
1527                //     string conforming to the JSON grammar; for example, by executing the
1528                //     JSON.stringify algorithm specified in [ECMA-262] in the context of a new
1529                //     global object.
1530                //     Step 14.2. Let bytes be the result of UTF-8 encoding json.
1531                // Otherwise:
1532                //     Let bytes be exportedKey.
1533                // NOTE: We determine the format by pattern matching on result, which is an
1534                // ExportedKey enum.
1535                let bytes = match exported_key {
1536                    ExportedKey::Bytes(bytes) => bytes,
1537                    ExportedKey::Jwk(jwk) => match jwk.stringify(cx) {
1538                        Ok(stringified_jwk) => {
1539                            Zeroizing::new(stringified_jwk.as_bytes(cx.no_gc()).to_vec())
1540                        },
1541                        Err(error) => {
1542                            subtle.reject_promise_with_error(promise, error);
1543                            return;
1544                        },
1545                    },
1546                };
1547
1548                // Step 15.
1549                // If normalizedAlgorithm supports the wrap key operation:
1550                //     Let result be the result of performing the wrap key operation specified by
1551                //     normalizedAlgorithm using algorithm, wrappingKey as key and bytes as
1552                //     plaintext.
1553                // Otherwise, if normalizedAlgorithm supports the encrypt operation:
1554                //     Let result be the result of performing the encrypt operation specified by
1555                //     normalizedAlgorithm using algorithm, wrappingKey as key and bytes as
1556                //     plaintext.
1557                // Otherwise:
1558                //     throw a NotSupportedError.
1559                let result = match normalized_algorithm {
1560                    WrapKeyAlgorithmOrEncryptAlgorithm::WrapKeyAlgorithm(algorithm) => {
1561                        algorithm.wrap_key(&wrapping_key, &bytes)
1562                    },
1563                    WrapKeyAlgorithmOrEncryptAlgorithm::EncryptAlgorithm(algorithm) => {
1564                        algorithm.encrypt(&wrapping_key, &bytes)
1565                    },
1566                };
1567                let result = match result {
1568                    Ok(result) => result,
1569                    Err(error) => {
1570                        subtle.reject_promise_with_error(promise, error);
1571                        return;
1572                    },
1573                };
1574
1575                // Step 16. Queue a global task on the crypto task source, given realm's global
1576                // object, to perform the remaining steps.
1577                // Step 17. Let result be the result of creating an ArrayBuffer in realm,
1578                // containing result.
1579                // Step 18. Resolve promise with result.
1580                subtle.resolve_promise_with_data(promise, result.into());
1581            }));
1582        promise
1583    }
1584
1585    /// <https://w3c.github.io/webcrypto/#SubtleCrypto-method-unwrapKey>
1586    fn UnwrapKey(
1587        &self,
1588        cx: &mut CurrentRealm,
1589        format: KeyFormat,
1590        wrapped_key: ArrayBufferViewOrArrayBuffer,
1591        unwrapping_key: &CryptoKey<D>,
1592        algorithm: AlgorithmIdentifier,
1593        unwrapped_key_algorithm: AlgorithmIdentifier,
1594        extractable: bool,
1595        usages: Vec<KeyUsage>,
1596    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
1597        // Step 1. Let format, unwrappingKey, algorithm, unwrappedKeyAlgorithm, extractable and
1598        // usages, be the format, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm,
1599        // extractable and keyUsages parameters passed to the unwrapKey() method, respectively.
1600        // NOTE: We did that in method parameter.
1601
1602        // Step 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set
1603        // to algorithm and op set to "unwrapKey".
1604        // Step 3. If an error occurred, let normalizedAlgorithm be the result of normalizing an
1605        // algorithm, with alg set to algorithm and op set to "decrypt".
1606        // Step 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.
1607        enum UnwrapKeyAlgorithmOrDecryptAlgorithm {
1608            UnwrapKeyAlgorithm(UnwrapKeyAlgorithm),
1609            DecryptAlgorithm(DecryptAlgorithm),
1610        }
1611        let normalized_algorithm = if let Ok(algorithm) =
1612            normalize_algorithm::<UnwrapKeyOperation>(cx, &algorithm)
1613        {
1614            UnwrapKeyAlgorithmOrDecryptAlgorithm::UnwrapKeyAlgorithm(algorithm)
1615        } else {
1616            match normalize_algorithm::<DecryptOperation>(cx, &algorithm) {
1617                Ok(algorithm) => UnwrapKeyAlgorithmOrDecryptAlgorithm::DecryptAlgorithm(algorithm),
1618                Err(error) => {
1619                    let promise = D::Promise::new_in_realm(cx);
1620                    promise.reject_error(cx, error);
1621                    return promise;
1622                },
1623            }
1624        };
1625
1626        // Step 5. Let normalizedKeyAlgorithm be the result of normalizing an algorithm, with alg
1627        // set to unwrappedKeyAlgorithm and op set to "importKey".
1628        // Step 6. If an error occurred, return a Promise rejected with normalizedKeyAlgorithm.
1629        let normalized_key_algorithm =
1630            match normalize_algorithm::<ImportKeyOperation>(cx, &unwrapped_key_algorithm) {
1631                Ok(algorithm) => algorithm,
1632                Err(error) => {
1633                    let promise = D::Promise::new_in_realm(cx);
1634                    promise.reject_error(cx, error);
1635                    return promise;
1636                },
1637            };
1638
1639        // Step 7. Let wrappedKey be the result of getting a copy of the bytes held by the
1640        // wrappedKey parameter passed to the unwrapKey() method.
1641        let wrapped_key = get_buffer_source_copy((&wrapped_key).into());
1642
1643        // Step 8. Let realm be the relevant realm of this.
1644        // Step 9. Let promise be a new Promise.
1645        let promise = D::Promise::new_in_realm(cx);
1646
1647        // Step 10. Return promise and perform the remaining steps in parallel.
1648        let trusted_subtle = Trusted::new(self);
1649        let trusted_unwrapping_key = Trusted::new(unwrapping_key);
1650        let trusted_promise = promise.to_trusted();
1651        self.global_from_reflector()
1652            .queue_dom_manipulation_task_source(task!(unwrap_key: move |cx| {
1653                let subtle = trusted_subtle.root();
1654                let unwrapping_key = trusted_unwrapping_key.root();
1655                let promise = &trusted_promise.root(cx);
1656
1657                // Step 11. If the following steps or referenced procedures say to throw an error,
1658                // queue a global task on the crypto task source, given realm's global object, to
1659                // reject promise with the returned error; and then terminate the algorithm.
1660
1661                // Step 12. If the name member of normalizedAlgorithm is not equal to the name
1662                // attribute of the [[algorithm]] internal slot of unwrappingKey then throw an
1663                // InvalidAccessError.
1664                let normalized_algorithm_name = match &normalized_algorithm {
1665                    UnwrapKeyAlgorithmOrDecryptAlgorithm::UnwrapKeyAlgorithm(algorithm) => {
1666                        algorithm.name()
1667                    },
1668                    UnwrapKeyAlgorithmOrDecryptAlgorithm::DecryptAlgorithm(algorithm) => {
1669                        algorithm.name()
1670                    },
1671                };
1672                if normalized_algorithm_name != unwrapping_key.algorithm().name() {
1673                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1674                        "Normalized algorithm name does not equal name of unwrapping key algorithm"
1675                            .into()
1676                    )));
1677                    return;
1678                }
1679
1680                // Step 13. If the [[usages]] internal slot of unwrappingKey does not contain an
1681                // entry that is "unwrapKey", then throw an InvalidAccessError.
1682                if !unwrapping_key.usages().contains(&KeyUsage::UnwrapKey) {
1683                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1684                        "Unwrapping key usages does not contain 'unwrapKey' entry".into()
1685                    )));
1686                    return;
1687                }
1688
1689                // Step 14.
1690                // If normalizedAlgorithm supports an unwrap key operation:
1691                //     Let bytes be the result of performing the unwrap key operation specified by
1692                //     normalizedAlgorithm using algorithm, unwrappingKey as key and wrappedKey as
1693                //     ciphertext.
1694                // Otherwise, if normalizedAlgorithm supports a decrypt operation:
1695                //     Let bytes be the result of performing the decrypt operation specified by
1696                //     normalizedAlgorithm using algorithm, unwrappingKey as key and wrappedKey as
1697                //     ciphertext.
1698                // Otherwise:
1699                //     throw a NotSupportedError.
1700                let bytes = match normalized_algorithm {
1701                    UnwrapKeyAlgorithmOrDecryptAlgorithm::UnwrapKeyAlgorithm(algorithm) => {
1702                        algorithm.unwrap_key(&unwrapping_key, &wrapped_key)
1703                    },
1704                    UnwrapKeyAlgorithmOrDecryptAlgorithm::DecryptAlgorithm(algorithm) => {
1705                        algorithm.decrypt(&unwrapping_key, &wrapped_key)
1706                    },
1707                };
1708                let bytes = match bytes {
1709                    Ok(bytes) => Zeroizing::new(bytes),
1710                    Err(error) => {
1711                        subtle.reject_promise_with_error(promise, error);
1712                        return;
1713                    },
1714                };
1715
1716                // Step 15.
1717                // If format is equal to the string "jwk":
1718                //     Let key be the result of executing the parse a JWK algorithm, with bytes as
1719                //     the data to be parsed.
1720                //     NOTE: We only parse bytes by executing the parse a JWK algorithm, but keep
1721                //     it as raw bytes for later steps, instead of converting it to a JsonWebKey
1722                //     dictionary.
1723                //
1724                // Otherwise:
1725                //     Let key be bytes.
1726                if format == KeyFormat::Jwk
1727                    && let Err(error) = JsonWebKey::parse(cx, &bytes) {
1728                        subtle.reject_promise_with_error(promise, error);
1729                        return;
1730                    }
1731                let key = bytes;
1732
1733                // Step 16. Let result be the result of performing the import key operation
1734                // specified by normalizedKeyAlgorithm using unwrappedKeyAlgorithm as algorithm,
1735                // format, usages and extractable and with key as keyData.
1736                let result = match normalized_key_algorithm.import_key(
1737                    cx,
1738                    &*subtle.global_from_reflector(),
1739                    format,
1740                    &key,
1741                    extractable,
1742                    usages.clone(),
1743                ) {
1744                    Ok(result) => result,
1745                    Err(error) => {
1746                        subtle.reject_promise_with_error(promise, error);
1747                        return;
1748                    },
1749                };
1750
1751                // Step 17. If the [[type]] internal slot of result is "secret" or "private" and
1752                // usages is empty, then throw a SyntaxError.
1753                if matches!(result.Type(), KeyType::Secret | KeyType::Private) &&
1754                    usages.is_empty()
1755                {
1756                    subtle.reject_promise_with_error(promise, Error::Syntax(Some(
1757                        "Key usages is empty".into()
1758                    )));
1759                    return;
1760                }
1761
1762                // Step 18. Set the [[extractable]] internal slot of result to extractable.
1763                // Step 19. Set the [[usages]] internal slot of result to the normalized value of
1764                // usages.
1765                // NOTE: Done by the importKey operation in Step 16.
1766
1767                // Step 20. Queue a global task on the crypto task source, given realm's global
1768                // object, to perform the remaining steps.
1769                // Step 21. Let result be the result of converting result to an ECMAScript Object
1770                // in realm, as defined by [WebIDL].
1771                // Step 22. Resolve promise with result.
1772                subtle.resolve_promise_with_key(promise, &result);
1773            }));
1774        promise
1775    }
1776
1777    /// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-encapsulateKey>
1778    fn EncapsulateKey(
1779        &self,
1780        cx: &mut CurrentRealm,
1781        encapsulation_algorithm: AlgorithmIdentifier,
1782        encapsulation_key: &CryptoKey<D>,
1783        shared_key_algorithm: AlgorithmIdentifier,
1784        extractable: bool,
1785        usages: Vec<KeyUsage>,
1786    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
1787        // Step 1. Let encapsulationAlgorithm, encapsulationKey, sharedKeyAlgorithm, extractable
1788        // and usages be the encapsulationAlgorithm, encapsulationKey, sharedKeyAlgorithm,
1789        // extractable and keyUsages parameters passed to the encapsulateKey() method,
1790        // respectively.
1791
1792        // Step 2. Let normalizedEncapsulationAlgorithm be the result of normalizing an algorithm,
1793        // with alg set to encapsulationAlgorithm and op set to "encapsulate".
1794        // Step 3. If an error occurred, return a Promise rejected with
1795        // normalizedEncapsulationAlgorithm.
1796        let promise = D::Promise::new_in_realm(cx);
1797        let normalized_encapsulation_algorithm =
1798            match normalize_algorithm::<EncapsulateOperation>(cx, &encapsulation_algorithm) {
1799                Ok(algorithm) => algorithm,
1800                Err(error) => {
1801                    promise.reject_error(cx, error);
1802                    return promise;
1803                },
1804            };
1805
1806        // Step 4. Let normalizedSharedKeyAlgorithm be the result of normalizing an algorithm, with
1807        // alg set to sharedKeyAlgorithm and op set to "importKey".
1808        // Step 5. If an error occurred, return a Promise rejected with
1809        // normalizedSharedKeyAlgorithm.
1810        let normalized_shared_key_algorithm =
1811            match normalize_algorithm::<ImportKeyOperation>(cx, &shared_key_algorithm) {
1812                Ok(algorithm) => algorithm,
1813                Err(error) => {
1814                    promise.reject_error(cx, error);
1815                    return promise;
1816                },
1817            };
1818
1819        // Step 6. Let realm be the relevant realm of this.
1820        // Step 7. Let promise be a new Promise.
1821        // NOTE: We did that in preparation of Step 3.
1822
1823        // Step 8. Return promise and perform the remaining steps in parallel.
1824        let trusted_subtle = Trusted::new(self);
1825        let trusted_encapsulated_key = Trusted::new(encapsulation_key);
1826        let trusted_promise = promise.to_trusted();
1827        self.global_from_reflector().queue_dom_manipulation_task_source(
1828            task!(encapsulate_keys: move |cx| {
1829                let subtle = trusted_subtle.root();
1830                let encapsulation_key = trusted_encapsulated_key.root();
1831                let promise = &trusted_promise.root(cx);
1832
1833                // Step 9. If the following steps or referenced procedures say to throw an error,
1834                // queue a global task on the crypto task source, given realm's global object, to
1835                // reject promise with the returned error; and then terminate the algorithm.
1836
1837                // Step 10. If the name member of normalizedEncapsulationAlgorithm is not equal to
1838                // the name attribute of the [[algorithm]] internal slot of encapsulationKey then
1839                // throw an InvalidAccessError.
1840                if normalized_encapsulation_algorithm.name() != encapsulation_key.algorithm().name() {
1841                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1842                        "[[algorithm]] internal slot of encapsulationKey is not equal to \
1843                        normalizedEncapsulationAlgorithm".to_string(),
1844                    )));
1845                    return;
1846                }
1847
1848                // Step 11. If the [[usages]] internal slot of encapsulationKey does not contain an
1849                // entry that is "encapsulateKey", then throw an InvalidAccessError.
1850                if !encapsulation_key.usages().contains(&KeyUsage::EncapsulateKey) {
1851                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1852                        "[[usages]] internal slot of encapsulationKey does not contain an \
1853                        entry that is \"encapsulateBits\"".to_string(),
1854                    )));
1855                    return;
1856                }
1857
1858                // Step 12. Let encapsulatedBits be the result of performing the encapsulate
1859                // operation specified by the [[algorithm]] internal slot of encapsulationKey using
1860                // encapsulationKey.
1861                // NOTE: Step 10 guarantees normalizedEncapsulationAlgorithm specifies the same
1862                // algorithm as the [[algorithm]] internal slot of encapsulationKey.
1863                let encapsulated_bits_result =
1864                    normalized_encapsulation_algorithm.encapsulate(&encapsulation_key);
1865                let encapsulated_bits = match encapsulated_bits_result {
1866                    Ok(encapsulated_bits) => encapsulated_bits,
1867                    Err(error) => {
1868                        subtle.reject_promise_with_error(promise, error);
1869                        return;
1870                    },
1871                };
1872
1873                // Step 13. Let sharedKey be the result of performing the import key operation
1874                // specified by normalizedSharedKeyAlgorithm using "raw-secret" as format, the
1875                // sharedKey field of encapsulatedBits as keyData, sharedKeyAlgorithm as algorithm
1876                // and using extractable and usages.
1877                let encapsulated_shared_key = match &encapsulated_bits.shared_key {
1878                    Some(shared_key) => shared_key,
1879                    None => {
1880                        subtle.reject_promise_with_error(promise, Error::Operation(Some(
1881                            "Shared key is missing in the result of the encapsulate operation"
1882                                .to_string())));
1883                        return;
1884                    },
1885                };
1886                let shared_key_result = normalized_shared_key_algorithm.import_key(
1887                    cx,
1888                    &*subtle.global_from_reflector(),
1889                    KeyFormat::Raw_secret,
1890                    encapsulated_shared_key,
1891                    extractable,
1892                    usages.clone(),
1893                );
1894                let shared_key = match shared_key_result {
1895                    Ok(shared_key) => shared_key,
1896                    Err(error) => {
1897                        subtle.reject_promise_with_error(promise, error);
1898                        return;
1899                    },
1900                };
1901
1902                // Step 14. If usages is empty, then throw a SyntaxError.
1903                if usages.is_empty() {
1904                    subtle.reject_promise_with_error(promise, Error::Syntax(Some(
1905                        "Usages is empty".into())));
1906                    return;
1907                }
1908
1909                // Step 15. Set the [[extractable]] internal slot of sharedKey to extractable.
1910                // Step 16. Set the [[usages]] internal slot of sharedKey to the normalized value
1911                // of usages.
1912                // NOTE: Done by the importKey operation in Step 13.
1913
1914                // Step 17. Let encapsulatedKey be a new EncapsulatedKey dictionary with sharedKey
1915                // set to sharedKey and ciphertext set to the ciphertext field of encapsulatedBits.
1916                let encapsulated_key = EncapsulatedKey {
1917                    shared_key: Some(Trusted::new(&shared_key)),
1918                    ciphertext:encapsulated_bits.ciphertext,
1919                };
1920
1921                // Step 18. Queue a global task on the crypto task source, given realm's global
1922                // object, to perform the remaining steps.
1923                // Step 19. Let result be the result of converting encapsulatedKey to an ECMAScript
1924                // Object in realm, as defined by [WebIDL].
1925                // Step 20. Resolve promise with result.
1926                subtle.resolve_promise_with_encapsulated_key(promise, encapsulated_key);
1927            })
1928        );
1929        promise
1930    }
1931
1932    /// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-encapsulateBits>
1933    fn EncapsulateBits(
1934        &self,
1935        cx: &mut CurrentRealm,
1936        encapsulation_algorithm: AlgorithmIdentifier,
1937        encapsulation_key: &CryptoKey<D>,
1938    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
1939        // Step 1. Let encapsulationAlgorithm and encapsulationKey be the encapsulationAlgorithm
1940        // and encapsulationKey parameters passed to the encapsulateBits() method, respectively.
1941
1942        // Step 2. Let normalizedEncapsulationAlgorithm be the result of normalizing an algorithm,
1943        // with alg set to encapsulationAlgorithm and op set to "encapsulate".
1944        // Step 3. If an error occurred, return a Promise rejected with
1945        // normalizedEncapsulationAlgorithm.
1946        let promise = D::Promise::new_in_realm(cx);
1947        let normalized_encapsulation_algorithm =
1948            match normalize_algorithm::<EncapsulateOperation>(cx, &encapsulation_algorithm) {
1949                Ok(algorithm) => algorithm,
1950                Err(error) => {
1951                    promise.reject_error(cx, error);
1952                    return promise;
1953                },
1954            };
1955
1956        // Step 4. Let realm be the relevant realm of this.
1957        // Step 5. Let promise be a new Promise.
1958        // NOTE: We did that in preparation of Step 3.
1959
1960        // Step 6. Return promise and perform the remaining steps in parallel.
1961        let trusted_subtle = Trusted::new(self);
1962        let trusted_encapsulation_key = Trusted::new(encapsulation_key);
1963        let trusted_promise = promise.to_trusted();
1964        self.global_from_reflector().queue_dom_manipulation_task_source(
1965            task!(derive_key: move |cx| {
1966                let subtle = trusted_subtle.root();
1967                let encapsulation_key = trusted_encapsulation_key.root();
1968                let promise = &trusted_promise.root(cx);
1969
1970                // Step 7. If the following steps or referenced procedures say to throw an error,
1971                // queue a global task on the crypto task source, given realm's global object, to
1972                // reject promise with the returned error; and then terminate the algorithm.
1973
1974                // Step 8. If the name member of normalizedEncapsulationAlgorithm is not equal to
1975                // the name attribute of the [[algorithm]] internal slot of encapsulationKey then
1976                // throw an InvalidAccessError.
1977                if normalized_encapsulation_algorithm.name() != encapsulation_key.algorithm().name() {
1978                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1979                        "[[algorithm]] internal slot of encapsulationKey is not equal to \
1980                        normalizedEncapsulationAlgorithm".to_string(),
1981                    )));
1982                    return;
1983                }
1984
1985                // Step 9. If the [[usages]] internal slot of encapsulationKey does not contain an
1986                // entry that is "encapsulateBits", then throw an InvalidAccessError.
1987                if !encapsulation_key.usages().contains(&KeyUsage::EncapsulateBits) {
1988                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
1989                        "[[usages]] internal slot of encapsulationKey does not contain an \
1990                        entry that is \"encapsulateBits\"".to_string(),
1991                    )));
1992                    return;
1993                }
1994
1995                // Step 10. Let encapsulatedBits be the result of performing the encapsulate
1996                // operation specified by the [[algorithm]] internal slot of encapsulationKey using
1997                // encapsulationKey.
1998                // NOTE: Step 8 guarantees normalizedEncapsulationAlgorithm specifies the same
1999                // algorithm as the [[algorithm]] internal slot of encapsulationKey.
2000                let encapsulated_bits =
2001                    match normalized_encapsulation_algorithm.encapsulate(&encapsulation_key) {
2002                        Ok(encapsulated_bits) => encapsulated_bits,
2003                        Err(error) => {
2004                            subtle.reject_promise_with_error(promise, error);
2005                            return;
2006                        },
2007                    };
2008
2009                // Step 11. Queue a global task on the crypto task source, given realm's global
2010                // object, to perform the remaining steps.
2011                // Step 12. Let result be the result of converting encapsulatedBits to an
2012                // ECMAScript Object in realm, as defined by [WebIDL].
2013                // Step 13. Resolve promise with result.
2014                subtle.resolve_promise_with_encapsulated_bits(promise, encapsulated_bits);
2015            }),
2016        );
2017        promise
2018    }
2019
2020    /// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-decapsulateKey>
2021    fn DecapsulateKey(
2022        &self,
2023        cx: &mut CurrentRealm,
2024        decapsulation_algorithm: AlgorithmIdentifier,
2025        decapsulation_key: &CryptoKey<D>,
2026        ciphertext: ArrayBufferViewOrArrayBuffer,
2027        shared_key_algorithm: AlgorithmIdentifier,
2028        extractable: bool,
2029        usages: Vec<KeyUsage>,
2030    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
2031        // Step 1. Let decapsulationAlgorithm, decapsulationKey, sharedKeyAlgorithm, extractable
2032        // and usages be the decapsulationAlgorithm, decapsulationKey, sharedKeyAlgorithm,
2033        // extractable and keyUsages parameters passed to the decapsulateKey() method,
2034        // respectively.
2035
2036        // Step 2. Let normalizedDecapsulationAlgorithm be the result of normalizing an algorithm,
2037        // with alg set to decapsulationAlgorithm and op set to "decapsulate".
2038        // Step 3. If an error occurred, return a Promise rejected with
2039        // normalizedDecapsulationAlgorithm.
2040        let normalized_decapsulation_algorithm =
2041            match normalize_algorithm::<DecapsulateOperation>(cx, &decapsulation_algorithm) {
2042                Ok(normalized_algorithm) => normalized_algorithm,
2043                Err(error) => {
2044                    let promise = D::Promise::new_in_realm(cx);
2045                    promise.reject_error(cx, error);
2046                    return promise;
2047                },
2048            };
2049
2050        // Step 4. Let normalizedSharedKeyAlgorithm be the result of normalizing an algorithm, with
2051        // alg set to sharedKeyAlgorithm and op set to "importKey".
2052        // Step 5. If an error occurred, return a Promise rejected with
2053        // normalizedSharedKeyAlgorithm.
2054        let normalized_shared_key_algorithm =
2055            match normalize_algorithm::<ImportKeyOperation>(cx, &shared_key_algorithm) {
2056                Ok(normalized_algorithm) => normalized_algorithm,
2057                Err(error) => {
2058                    let promise = D::Promise::new_in_realm(cx);
2059                    promise.reject_error(cx, error);
2060                    return promise;
2061                },
2062            };
2063
2064        // Step 6. Let ciphertext be the result of getting a copy of the bytes held by the
2065        // ciphertext parameter passed to the decapsulateKey() method.
2066        let ciphertext = get_buffer_source_copy((&ciphertext).into());
2067
2068        // Step 7. Let realm be the relevant realm of this.
2069        // Step 8. Let promise be a new Promise.
2070        let promise = D::Promise::new_in_realm(cx);
2071
2072        // Step 9. Return promise and perform the remaining steps in parallel.
2073        let trusted_subtle = Trusted::new(self);
2074        let trusted_decapsulation_key = Trusted::new(decapsulation_key);
2075        let trusted_promise = promise.to_trusted();
2076        self.global_from_reflector()
2077            .queue_dom_manipulation_task_source(task!(decapsulate_key: move |cx| {
2078                let subtle = trusted_subtle.root();
2079                let promise = &trusted_promise.root(cx);
2080                let decapsulation_key = trusted_decapsulation_key.root();
2081
2082                // Step 10. If the following steps or referenced procedures say to throw an error,
2083                // queue a global task on the crypto task source, given realm's global object, to
2084                // reject promise with the returned error; and then terminate the algorithm.
2085
2086                // Step 11. If the name member of normalizedDecapsulationAlgorithm is not equal to
2087                // the name attribute of the [[algorithm]] internal slot of decapsulationKey then
2088                // throw an InvalidAccessError.
2089                if normalized_decapsulation_algorithm.name() != decapsulation_key.algorithm().name() {
2090                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
2091                        "[[algorithm]] internal slot of decapsulationKey is not equal to \
2092                        normalizedDecapsulationAlgorithm".to_string()
2093                    )));
2094                    return;
2095                }
2096
2097                // Step 12. If the [[usages]] internal slot of decapsulationKey does not contain an
2098                // entry that is "decapsulateKey", then throw an InvalidAccessError.
2099                if !decapsulation_key.usages().contains(&KeyUsage::DecapsulateKey) {
2100                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
2101                        "[[usages]] internal slot of decapsulationKey does not contain an \
2102                        entry that is \"decapsulateBits\"".to_string(),
2103                    )));
2104                    return;
2105                }
2106
2107                // Step 13. Let decapsulatedBits be the result of performing the decapsulate
2108                // operation specified by the [[algorithm]] internal slot of decapsulationKey using
2109                // decapsulationKey and ciphertext.
2110                // NOTE: Step 11 guarantees normalizedDecapsulationAlgorithm specifies the same
2111                // algorithm as the [[algorithm]] internal slot of decapsulationKey.
2112                let decapsulated_bits_result =
2113                    normalized_decapsulation_algorithm.decapsulate(&decapsulation_key, &ciphertext);
2114                let decapsulated_bits = match decapsulated_bits_result {
2115                    Ok(decapsulated_bits) => Zeroizing::new(decapsulated_bits),
2116                    Err(error) => {
2117                        subtle.reject_promise_with_error(promise, error);
2118                        return;
2119                    },
2120                };
2121
2122
2123                // Step 14. Let sharedKey be the result of performing the import key operation
2124                // specified by normalizedSharedKeyAlgorithm using "raw-secret" as format, the
2125                // decapsulatedBits as keyData, sharedKeyAlgorithm as algorithm and using
2126                // extractable and usages.
2127                let shared_key_result = normalized_shared_key_algorithm.import_key(
2128                    cx,
2129                    &*subtle.global_from_reflector(),
2130                    KeyFormat::Raw_secret,
2131                    &decapsulated_bits,
2132                    extractable,
2133                    usages.clone(),
2134                );
2135                let shared_key = match shared_key_result {
2136                    Ok(shared_key) => shared_key,
2137                    Err(error) => {
2138                        subtle.reject_promise_with_error(promise, error);
2139                        return;
2140                    },
2141                };
2142
2143                // Step 15. If usages is empty, then throw a SyntaxError.
2144                if usages.is_empty() {
2145                    subtle.reject_promise_with_error(promise, Error::Syntax(Some(
2146                        "Usages is empty".into())));
2147                    return;
2148                }
2149
2150                // Step 16. Set the [[extractable]] internal slot of sharedKey to extractable.
2151                // Step 17. Set the [[usages]] internal slot of sharedKey to the normalized value
2152                // of usages.
2153                // NOTE: Done by the importKey operation in Step 14.
2154
2155                // Step 18. Queue a global task on the crypto task source, given realm's global
2156                // object, to perform the remaining steps.
2157                // Step 19. Let result be the result of converting sharedKey to an ECMAScript
2158                // Object in realm, as defined by [WebIDL].
2159                // Step 20. Resolve promise with result.
2160                subtle.resolve_promise_with_key(promise, &shared_key);
2161            }));
2162        promise
2163    }
2164
2165    /// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-decapsulateBits>
2166    fn DecapsulateBits(
2167        &self,
2168        cx: &mut CurrentRealm,
2169        decapsulation_algorithm: AlgorithmIdentifier,
2170        decapsulation_key: &CryptoKey<D>,
2171        ciphertext: ArrayBufferViewOrArrayBuffer,
2172    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
2173        // Step 1. Let decapsulationAlgorithm and decapsulationKey be the decapsulationAlgorithm
2174        // and decapsulationKey parameters passed to the decapsulateBits() method, respectively.
2175
2176        // Step 2. Let normalizedDecapsulationAlgorithm be the result of normalizing an algorithm,
2177        // with alg set to decapsulationAlgorithm and op set to "decapsulate".
2178        // Step 3. If an error occurred, return a Promise rejected with
2179        // normalizedDecapsulationAlgorithm.
2180        let normalized_decapsulation_algorithm =
2181            match normalize_algorithm::<DecapsulateOperation>(cx, &decapsulation_algorithm) {
2182                Ok(normalized_algorithm) => normalized_algorithm,
2183                Err(error) => {
2184                    let promise = D::Promise::new_in_realm(cx);
2185                    promise.reject_error(cx, error);
2186                    return promise;
2187                },
2188            };
2189
2190        // Step 4. Let ciphertext be the result of getting a copy of the bytes held by the
2191        // ciphertext parameter passed to the decapsulateBits() method.
2192        let ciphertext = get_buffer_source_copy((&ciphertext).into());
2193
2194        // Step 5. Let realm be the relevant realm of this.
2195        // Step 6. Let promise be a new Promise.
2196        let promise = D::Promise::new_in_realm(cx);
2197
2198        // Step 7. Return promise and perform the remaining steps in parallel.
2199        let trusted_subtle = Trusted::new(self);
2200        let trusted_decapsulation_key = Trusted::new(decapsulation_key);
2201        let trusted_promise = promise.to_trusted();
2202        self.global_from_reflector()
2203            .queue_dom_manipulation_task_source(task!(decapsulate_bits: move |cx| {
2204                let subtle = trusted_subtle.root();
2205                let promise = &trusted_promise.root(cx);
2206                let decapsulation_key = trusted_decapsulation_key.root();
2207
2208                // Step 8. If the following steps or referenced procedures say to throw an error,
2209                // queue a global task on the crypto task source, given realm's global object, to
2210                // reject promise with the returned error; and then terminate the algorithm.
2211
2212                // Step 9. If the name member of normalizedDecapsulationAlgorithm is not equal to
2213                // the name attribute of the [[algorithm]] internal slot of decapsulationKey then
2214                // throw an InvalidAccessError.
2215                if normalized_decapsulation_algorithm.name() != decapsulation_key.algorithm().name() {
2216                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
2217                        "[[algorithm]] internal slot of decapsulationKey is not equal to \
2218                        normalizedDecapsulationAlgorithm".to_string()
2219                    )));
2220                    return;
2221                }
2222
2223                // Step 10. If the [[usages]] internal slot of decapsulationKey does not contain an
2224                // entry that is "decapsulateBits", then throw an InvalidAccessError.
2225                if !decapsulation_key.usages().contains(&KeyUsage::DecapsulateBits) {
2226                    subtle.reject_promise_with_error(promise, Error::InvalidAccess(Some(
2227                        "[[usages]] internal slot of decapsulationKey does not contain an \
2228                        entry that is \"decapsulateBits\"".to_string(),
2229                    )));
2230                    return;
2231                }
2232
2233                // Step 11. Let decapsulatedBits be the result of performing the decapsulate
2234                // operation specified by the [[algorithm]] internal slot of decapsulationKey using
2235                // decapsulationKey and ciphertext.
2236                // NOTE: Step 9 guarantees normalizedDecapsulationAlgorithm specifies the same
2237                // algorithm as the [[algorithm]] internal slot of decapsulationKey.
2238                let decapsulated_bits_result =
2239                    normalized_decapsulation_algorithm.decapsulate(&decapsulation_key, &ciphertext);
2240                let decapsulated_bits = match decapsulated_bits_result {
2241                    Ok(decapsulated_bits) => Zeroizing::new(decapsulated_bits),
2242                    Err(error) => {
2243                        subtle.reject_promise_with_error(promise, error);
2244                        return;
2245                    },
2246                };
2247
2248                // Step 12. Queue a global task on the crypto task source, given realm's global
2249                // object, to perform the remaining steps.
2250                // Step 13. Let result be the result of creating an ArrayBuffer in realm,
2251                // containing decapsulatedBits.
2252                // Step 14. Resolve promise with result.
2253                subtle.resolve_promise_with_data(promise, decapsulated_bits);
2254            }));
2255        promise
2256    }
2257
2258    /// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
2259    fn GetPublicKey(
2260        &self,
2261        cx: &mut CurrentRealm,
2262        key: &CryptoKey<D>,
2263        usages: Vec<KeyUsage>,
2264    ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
2265        // Step 1. Let key and usages be the key and keyUsages parameters passed to the
2266        // getPublicKey() method, respectively.
2267
2268        // Step 2. Let algorithm be the [[algorithm]] internal slot of key.
2269        let algorithm = key.algorithm();
2270
2271        // Step 3. If the cryptographic algorithm identified by algorithm does not support deriving
2272        // a public key from a private key, then return a Promise rejected with a
2273        // NotSupportedError.
2274        //
2275        // NOTE: We rely on [`normalize_algorithm`] to check whether the algorithm supports the
2276        // getPublicKey operation.
2277        let get_public_key_algorithm = match normalize_algorithm::<GetPublicKeyOperation>(
2278            cx,
2279            &AlgorithmIdentifier::String(DOMString::from_static(algorithm.name().as_str())),
2280        ) {
2281            Ok(normalized_algorithm) => normalized_algorithm,
2282            Err(error) => {
2283                let promise = D::Promise::new_in_realm(cx);
2284                promise.reject_error(cx, error);
2285                return promise;
2286            },
2287        };
2288
2289        // Step 4. Let realm be the relevant realm of this.
2290        // Step 5. Let promise be a new Promise.
2291        let promise = D::Promise::new_in_realm(cx);
2292
2293        // Step 6. Return promise and perform the remaining steps in parallel.
2294        let trusted_subtle = Trusted::new(self);
2295        let trusted_promise = promise.to_trusted();
2296        let trusted_key = Trusted::new(key);
2297        self.global_from_reflector()
2298            .queue_dom_manipulation_task_source(task!(get_public_key: move |cx| {
2299                let subtle = trusted_subtle.root();
2300                let promise = &trusted_promise.root(cx);
2301                let key = trusted_key.root();
2302
2303                // Step 7. If the following steps or referenced procedures say to throw an error,
2304                // queue a global task on the crypto task source, given realm's global object, to
2305                // reject promise with the returned error; and then terminate the algorithm.
2306
2307                // Step 8. If the [[type]] internal slot of key is not "private", then throw an
2308                // InvalidAccessError.
2309                if let Err(error) = key.ensure_type(KeyType::Private) {
2310                    subtle.reject_promise_with_error(promise, error);
2311                    return;
2312                }
2313
2314                // Step 9. If usages contains an entry which is not supported for a public key by
2315                // the algorithm identified by algorithm, then throw a SyntaxError.
2316                // Step 10. Let publicKey be a new CryptoKey representing the public key
2317                // corresponding to the private key represented by the [[handle]] internal slot of
2318                // key.
2319                // Step 11. If an error occurred, then throw a OperationError.
2320                // Step 12. Set the [[type]] internal slot of publicKey to "public".
2321                // Step 13. Set the [[algorithm]] internal slot of publicKey to algorithm.
2322                // Step 14. Set the [[extractable]] internal slot of publicKey to true.
2323                // Step 15. Set the [[usages]] internal slot of publicKey to usages.
2324                //
2325                // NOTE: We run these steps in the "getPublicKey" operations of the supported
2326                // cryptographic algorithms.
2327                let result = match get_public_key_algorithm.get_public_key(
2328                    cx,
2329                    &*subtle.global_from_reflector(),
2330                    &key,
2331                    key.algorithm(),
2332                    usages.clone(),
2333                ) {
2334                    Ok(public_key) => public_key,
2335                    Err(error) => {
2336                        subtle.reject_promise_with_error(promise, error);
2337                        return;
2338                    },
2339                };
2340
2341                // Step 16. Queue a global task on the crypto task source, given realm's global
2342                // object, to perform the remaining steps.
2343                // Step 17. Let result be the result of converting publicKey to an ECMAScript
2344                // Object in realm, as defined by [WebIDL].
2345                // Step 18. Resolve promise with result.
2346                subtle.resolve_promise_with_key(promise, &result);
2347            }));
2348        promise
2349    }
2350
2351    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-supports>
2352    fn Supports(
2353        cx: &mut JSContext,
2354        _global: &D::GlobalScope,
2355        operation: DOMString,
2356        algorithm: AlgorithmIdentifier,
2357        length: Option<u32>,
2358    ) -> bool {
2359        // Step 1. If operation is not one of "encrypt", "decrypt", "sign", "verify", "digest",
2360        // "generateKey", "deriveKey", "deriveBits", "importKey", "exportKey", "wrapKey",
2361        // "unwrapKey", "encapsulateKey", "encapsulateBits", "decapsulateKey", "decapsulateBits" or
2362        // "getPublicKey", return false.
2363        let operation = &*operation.str();
2364        if !matches!(
2365            operation,
2366            "encrypt" |
2367                "decrypt" |
2368                "sign" |
2369                "verify" |
2370                "digest" |
2371                "generateKey" |
2372                "deriveKey" |
2373                "deriveBits" |
2374                "importKey" |
2375                "exportKey" |
2376                "wrapKey" |
2377                "unwrapKey" |
2378                "encapsulateKey" |
2379                "encapsulateBits" |
2380                "decapsulateKey" |
2381                "decapsulateBits" |
2382                "getPublicKey"
2383        ) {
2384            return false;
2385        }
2386
2387        // Step 2. Return the result of checking support for an algorithm, with op set to
2388        // operation, alg set to algorithm, and length set to length.
2389        check_support_for_algorithm::<D>(cx, operation, &algorithm, length)
2390    }
2391
2392    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-supports-additionalAlgorithm>
2393    fn Supports_(
2394        cx: &mut JSContext,
2395        _global: &D::GlobalScope,
2396        operation: DOMString,
2397        algorithm: AlgorithmIdentifier,
2398        additional_algorithm: AlgorithmIdentifier,
2399    ) -> bool {
2400        // Step 1. If operation is not one of "encrypt", "decrypt", "sign", "verify", "digest",
2401        // "generateKey", "deriveKey", "deriveBits", "importKey", "exportKey", "wrapKey",
2402        // "unwrapKey", "encapsulateKey", "encapsulateBits", "decapsulateKey", "decapsulateBits" or
2403        // "getPublicKey", return false.
2404        let mut operation = &*operation.str();
2405        if !matches!(
2406            operation,
2407            "encrypt" |
2408                "decrypt" |
2409                "sign" |
2410                "verify" |
2411                "digest" |
2412                "generateKey" |
2413                "deriveKey" |
2414                "deriveBits" |
2415                "importKey" |
2416                "exportKey" |
2417                "wrapKey" |
2418                "unwrapKey" |
2419                "encapsulateKey" |
2420                "encapsulateBits" |
2421                "decapsulateKey" |
2422                "decapsulateBits" |
2423                "getPublicKey"
2424        ) {
2425            return false;
2426        }
2427
2428        // Step 2.
2429        // If operation is "deriveKey" or "unwrapKey":
2430        //     If the result of checking support for an algorithm with op set to "importKey" and
2431        //     alg set to additionalAlgorithm is false, return false.
2432        // If operation is "wrapKey":
2433        //     If the result of checking support for an algorithm with op set to "exportKey" and
2434        //     alg set to additionalAlgorithm is false, return false.
2435        if matches!(operation, "deriveKey" | "unwrapKey") &&
2436            !check_support_for_algorithm::<D>(cx, "importKey", &additional_algorithm, None)
2437        {
2438            return false;
2439        }
2440        if operation == "wrapKey" &&
2441            !check_support_for_algorithm::<D>(cx, "exportKey", &additional_algorithm, None)
2442        {
2443            return false;
2444        }
2445
2446        // Step 3. If operation is "encapsulateKey" or "decapsulateKey":
2447        if matches!(operation, "encapsulateKey" | "decapsulateKey") {
2448            // Step 3.1. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg
2449            // set to algorithm and op set to "get shared key length".
2450            // Step 3.2. If an error occurred, return false.
2451            let Ok(normalized_algorithm) =
2452                normalize_algorithm::<GetSharedKeyLengthOperation>(cx, &algorithm)
2453            else {
2454                return false;
2455            };
2456
2457            // Step 3.3. Let sharedKeyLength be the result of performing the get shared key length
2458            // algorithm specified by normalizedAlgorithm using algorithm.
2459            let shared_key_length = normalized_algorithm.get_shared_key_length();
2460
2461            // Step 3.4. Let normalizedAdditionalAlgorithm be the result of normalizing an
2462            // algorithm, with alg set to additionalAlgorithm and op set to "importKey".
2463            // Step 3.5. If an error occurred, return false.
2464            let Ok(normalized_additional_algorithm) =
2465                normalize_algorithm::<ImportKeyOperation>(cx, &additional_algorithm)
2466            else {
2467                return false;
2468            };
2469
2470            // Step 3.6. If the result of determining support from operation steps with op set to
2471            // "importKey" and normalizedAlgorithm set to normalizedAdditionalAlgorithm, and length
2472            // set to null is false, return false.
2473            //
2474            // NOTE: normalized_additional_algorithm is an ImportKeyAlgorithm value, so we don't
2475            // need to explicitly set op to "importKey" when we call the
2476            // determine_support_from_operation_steps method.
2477            if !normalized_additional_algorithm.determine_support_from_operation_steps(None) {
2478                return false;
2479            }
2480
2481            // Step 3.7. If the import key operation specified by normalizedAdditionalAlgorithm
2482            // would throw an error for every value of keyData that is a byte sequence whose length
2483            // in bits is sharedKeyLength when format is "raw-secret", return false.
2484            if normalized_additional_algorithm.will_throw_for_key_data_length(shared_key_length) {
2485                return false;
2486            }
2487        }
2488
2489        // Step 4. Let length be null.
2490        let mut length = None;
2491
2492        // Step 5. If operation is "deriveKey":
2493        if operation == "deriveKey" {
2494            // Step 5.1. If the result of checking support for an algorithm with op set to "get key
2495            // length" and alg set to additionalAlgorithm is false, return false.
2496            if !check_support_for_algorithm::<D>(cx, "get key length", &additional_algorithm, None)
2497            {
2498                return false;
2499            }
2500
2501            // Step 5.2. Let normalizedAdditionalAlgorithm be the result of normalizing an
2502            // algorithm, with alg set to additionalAlgorithm and op set to "get key length".
2503            let Ok(normalized_additional_algorithm) =
2504                normalize_algorithm::<GetKeyLengthOperation>(cx, &additional_algorithm)
2505            else {
2506                return false;
2507            };
2508
2509            // Step 5.3. Let length be the result of performing the get key length algorithm
2510            // specified by additionalAlgorithm using normalizedAdditionalAlgorithm.'
2511            match normalized_additional_algorithm.get_key_length() {
2512                Ok(key_length) => {
2513                    length = key_length;
2514                },
2515                Err(_) => return false,
2516            };
2517
2518            // Step 5.4. Set operation to "deriveBits".
2519            operation = "deriveBits";
2520        }
2521
2522        // Step 6. Return the result of checking support for an algorithm, with op set to
2523        // operation, alg set to algorithm, and length set to length.
2524        check_support_for_algorithm::<D>(cx, operation, &algorithm, length)
2525    }
2526}
2527
2528/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-check-support-for-algorithm>
2529fn check_support_for_algorithm<D: Equivalence>(
2530    cx: &mut JSContext,
2531    mut operation: &str,
2532    algorithm: &AlgorithmIdentifier,
2533    length: Option<u32>,
2534) -> bool {
2535    // Step 1. If op is "encapsulateKey" or "encapsulateBits", set op to "encapsulate".
2536    if operation == "encapsulateKey" || operation == "encapsulateBits" {
2537        operation = "encapsulate";
2538    }
2539
2540    // Step 2. If op is "decapsulateKey" or "decapsulateBits", set op to "decapsulate".
2541    if operation == "decapsulateKey" || operation == "decapsulateBits" {
2542        operation = "decapsulate";
2543    }
2544
2545    // Step 3. If op is "getPublicKey":
2546    if operation == "getPublicKey" {
2547        // Step 3.1. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg
2548        // set to alg and op set to "exportKey".
2549        // Step 3.2. If an error occurred, return false.
2550        let Ok(normalized_algorithm) = normalize_algorithm::<ExportKeyOperation>(cx, algorithm)
2551        else {
2552            return false;
2553        };
2554
2555        // Step 3.3. If the cryptographic algorithm identified by normalizedAlgorithm does not
2556        // support deriving a public key from a private key, then return false.
2557        // Step 3.4. Otherwise, return true.
2558        //
2559        // NOTE: We rely on [`normalize_algorithm`] to check whether the algorithm supports the
2560        // getPublicKey operation.
2561        return normalize_algorithm::<GetPublicKeyOperation>(
2562            cx,
2563            &AlgorithmIdentifier::String(DOMString::from_static(
2564                normalized_algorithm.name().as_str(),
2565            )),
2566        )
2567        .is_ok();
2568    }
2569
2570    // Step 4. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to
2571    // alg and op set to op.
2572    // Step 5. If an error occurred:
2573    //     Step 5.1. If op is "wrapKey", return the result of checking support for an algorithm
2574    //     with op set to "encrypt" and alg set to alg.
2575    //     Step 5.2. If op is "unwrapKey", return the result of checking support for an algorithm
2576    //     with op set to "decrypt" and alg set to alg.
2577    //     Step 5.3. Otherwise, return false.
2578    // Step 6. Return the result of determining support from operation steps, with op set to op,
2579    // normalizedAlgorithm set to normalizedAlgorithm, and length set to length.
2580    match operation {
2581        "encrypt" => {
2582            normalize_and_determine_support::<EncryptOperation, D>(cx, operation, algorithm, length)
2583        },
2584        "decrypt" => {
2585            normalize_and_determine_support::<DecryptOperation, D>(cx, operation, algorithm, length)
2586        },
2587        "sign" => {
2588            normalize_and_determine_support::<SignOperation, D>(cx, operation, algorithm, length)
2589        },
2590        "verify" => {
2591            normalize_and_determine_support::<VerifyOperation, D>(cx, operation, algorithm, length)
2592        },
2593        "digest" => {
2594            normalize_and_determine_support::<DigestOperation, D>(cx, operation, algorithm, length)
2595        },
2596        "deriveBits" => normalize_and_determine_support::<DeriveBitsOperation<D>, D>(
2597            cx, operation, algorithm, length,
2598        ),
2599        "wrapKey" => {
2600            normalize_and_determine_support::<WrapKeyOperation, D>(cx, operation, algorithm, length)
2601        },
2602        "unwrapKey" => normalize_and_determine_support::<UnwrapKeyOperation, D>(
2603            cx, operation, algorithm, length,
2604        ),
2605        "generateKey" => normalize_and_determine_support::<GenerateKeyOperation, D>(
2606            cx, operation, algorithm, length,
2607        ),
2608        "importKey" => normalize_and_determine_support::<ImportKeyOperation, D>(
2609            cx, operation, algorithm, length,
2610        ),
2611        "exportKey" => normalize_and_determine_support::<ExportKeyOperation, D>(
2612            cx, operation, algorithm, length,
2613        ),
2614        "get key length" => normalize_and_determine_support::<GetKeyLengthOperation, D>(
2615            cx, operation, algorithm, length,
2616        ),
2617        "encapsulate" => normalize_and_determine_support::<EncapsulateOperation, D>(
2618            cx, operation, algorithm, length,
2619        ),
2620        "decapsulate" => normalize_and_determine_support::<DecapsulateOperation, D>(
2621            cx, operation, algorithm, length,
2622        ),
2623        _ => false,
2624    }
2625}
2626
2627/// Helper function for Step 4 - 6 of
2628/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-check-support-for-algorithm>
2629fn normalize_and_determine_support<T: Operation, D: Equivalence>(
2630    cx: &mut JSContext,
2631    op: &str,
2632    algorithm: &AlgorithmIdentifier,
2633    length: Option<u32>,
2634) -> bool {
2635    if let Ok(normalized_algorithm) = normalize_algorithm::<T>(cx, algorithm) {
2636        normalized_algorithm.determine_support_from_operation_steps(length)
2637    } else {
2638        match op {
2639            "wrapKey" => check_support_for_algorithm::<D>(cx, "encrypt", algorithm, length),
2640            "unwrapKey" => check_support_for_algorithm::<D>(cx, "decrypt", algorithm, length),
2641            _ => false,
2642        }
2643    }
2644}
2645
2646/// Alternative to std::convert::TryFrom, with `&mut js::context::JSContext`
2647trait TryFromWithCxAndName<T>: Sized {
2648    type Error;
2649
2650    fn try_from_with_cx_and_name(
2651        cx: &mut JSContext,
2652        algorithm_name: CryptoAlgorithm,
2653        value: T,
2654    ) -> Result<Self, Self::Error>;
2655}
2656
2657/// Alternative to std::convert::TryInto, with `&mut js::context::JSContext`
2658trait TryIntoWithCxAndName<T>: Sized {
2659    type Error;
2660
2661    fn try_into_with_cx_and_name(
2662        self,
2663        cx: &mut JSContext,
2664        algorithm_name: CryptoAlgorithm,
2665    ) -> Result<T, Self::Error>;
2666}
2667
2668impl<T, U> TryIntoWithCxAndName<U> for T
2669where
2670    U: TryFromWithCxAndName<T>,
2671{
2672    type Error = U::Error;
2673
2674    fn try_into_with_cx_and_name(
2675        self,
2676        cx: &mut JSContext,
2677        algorithm_name: CryptoAlgorithm,
2678    ) -> Result<U, Self::Error> {
2679        U::try_from_with_cx_and_name(cx, algorithm_name, self)
2680    }
2681}
2682
2683// Custom binding types of WebIDL dictionary for WebCrypto
2684//
2685// In our implementation of WebCrypto API, we use custom binding types for the following WebIDL
2686// dictionaries, instead of the binding types generated by `script_bindings`:
2687//
2688// - `KeyAlgorithm` and their derivatives
2689// - `Algorithm` and their derivatives
2690// - `EncapsulatedKey`
2691// - `DecapsulatedKey`
2692//
2693// Based on the design of WebCrypto API, they frequently need to cross thread boundaries, but the
2694// generated binding types for these dictionaries are not thread-safe. Therefore, we implement the
2695// following thread-safe custom binding type for these dictionaries.
2696//
2697// There is one exception. The [`normalize_algorithm`] function still uses the generated binding
2698// type for the `Algorithm` dictionary, as the custom binding type for `Algorithm` currently does
2699// not accept arbitrary string in its `name` field.
2700
2701/// <https://w3c.github.io/webcrypto/#dfn-Algorithm>
2702#[derive(Clone, MallocSizeOf)]
2703struct Algorithm {
2704    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
2705    name: CryptoAlgorithm,
2706}
2707
2708impl<'a> TryFromWithCxAndName<HandleObject<'a>> for Algorithm {
2709    type Error = Error;
2710
2711    fn try_from_with_cx_and_name(
2712        _cx: &mut JSContext,
2713        algorithm_name: CryptoAlgorithm,
2714        _object: HandleObject<'a>,
2715    ) -> Result<Self, Self::Error> {
2716        Ok(Algorithm {
2717            name: algorithm_name,
2718        })
2719    }
2720}
2721
2722impl TryFrom<SerializableAlgorithm> for Algorithm {
2723    type Error = ();
2724
2725    fn try_from(value: SerializableAlgorithm) -> Result<Self, Self::Error> {
2726        Ok(Algorithm {
2727            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
2728        })
2729    }
2730}
2731
2732impl From<&Algorithm> for SerializableAlgorithm {
2733    fn from(value: &Algorithm) -> Self {
2734        SerializableAlgorithm {
2735            name: value.name.as_str().into(),
2736        }
2737    }
2738}
2739
2740/// <https://w3c.github.io/webcrypto/#dfn-KeyAlgorithm>
2741#[derive(Clone, MallocSizeOf)]
2742pub(crate) struct KeyAlgorithm {
2743    /// <https://w3c.github.io/webcrypto/#dom-keyalgorithm-name>
2744    name: CryptoAlgorithm,
2745}
2746
2747impl ToJSValConvertible for KeyAlgorithm {
2748    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
2749        rooted!(&in(cx) let mut object = JS_NewObject(cx, None));
2750
2751        rooted!(&in(cx) let mut name_js = UndefinedValue());
2752        self.name.as_str().to_jsval(cx, name_js.handle_mut());
2753        set_dictionary_property(cx, object.handle(), c"name", name_js.handle())
2754            .expect("Failed to set name property of KeyAlgorithm");
2755
2756        rval.set(ObjectOrNullValue(object.get()));
2757    }
2758}
2759
2760impl TryFrom<SerializableKeyAlgorithm> for KeyAlgorithm {
2761    type Error = ();
2762
2763    fn try_from(value: SerializableKeyAlgorithm) -> Result<Self, Self::Error> {
2764        Ok(KeyAlgorithm {
2765            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
2766        })
2767    }
2768}
2769
2770impl From<&KeyAlgorithm> for SerializableKeyAlgorithm {
2771    fn from(value: &KeyAlgorithm) -> Self {
2772        SerializableKeyAlgorithm {
2773            name: value.name.as_str().into(),
2774        }
2775    }
2776}
2777
2778/// <https://w3c.github.io/webcrypto/#dfn-RsaHashedKeyGenParams>
2779#[derive(Clone, MallocSizeOf)]
2780pub(crate) struct RsaHashedKeyGenParams {
2781    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
2782    name: CryptoAlgorithm,
2783
2784    /// <https://w3c.github.io/webcrypto/#dfn-RsaKeyGenParams-modulusLength>
2785    modulus_length: u32,
2786
2787    /// <https://w3c.github.io/webcrypto/#dfn-RsaKeyGenParams-publicExponent>
2788    public_exponent: Vec<u8>,
2789
2790    /// <https://w3c.github.io/webcrypto/#dfn-RsaHashedKeyGenParams-hash>
2791    hash: DigestAlgorithm,
2792}
2793
2794impl<'a> TryFromWithCxAndName<HandleObject<'a>> for RsaHashedKeyGenParams {
2795    type Error = Error;
2796
2797    fn try_from_with_cx_and_name(
2798        cx: &mut JSContext,
2799        algorithm_name: CryptoAlgorithm,
2800        object: HandleObject,
2801    ) -> Result<Self, Self::Error> {
2802        let hash = get_required_parameter(cx, object, c"hash", ())?;
2803
2804        Ok(RsaHashedKeyGenParams {
2805            name: algorithm_name,
2806            modulus_length: get_required_parameter(
2807                cx,
2808                object,
2809                c"modulusLength",
2810                ConversionBehavior::EnforceRange,
2811            )?,
2812            public_exponent: get_required_parameter_in_box::<HeapUint8Array>(
2813                cx,
2814                object,
2815                c"publicExponent",
2816                (),
2817            )?
2818            .to_vec()
2819            .unwrap_or_default(),
2820            hash: normalize_algorithm::<DigestOperation>(cx, &hash)?,
2821        })
2822    }
2823}
2824
2825impl RsaHashedKeyGenParams {
2826    /// <https://w3c.github.io/webcrypto/#dfn-validate-rsa-key-generation-parameters>
2827    fn validate_parameters(&self) -> Result<(), Error> {
2828        // Step 1. Let modulusLength be the modulusLength member of normalizedAlgorithm.
2829        let modulus_length = self.modulus_length;
2830
2831        // Step 2. Let publicExponent be the result of converting the publicExponent member of
2832        // normalizedAlgorithm to a non-negative integer.
2833        let public_exponent = &self.public_exponent;
2834
2835        // Step 3. If modulusLength is less than 4, or if publicExponent is less than 3, is even, or
2836        // is greater than or equal to 2^modulusLength - 1, then throw an OperationError.
2837        let is_less_than_3 = |public_exponent: &[u8]| {
2838            let mut byte_iterator = public_exponent.iter().skip_while(|byte| **byte == 0);
2839            byte_iterator.next().is_none_or(|byte| *byte < 3) && byte_iterator.count() == 0
2840        };
2841        let is_even =
2842            |public_exponent: &[u8]| public_exponent.last().is_none_or(|byte| byte % 2 == 0);
2843        let upper_bound_first_byte = (1u8 << (modulus_length % 8)).wrapping_sub(1);
2844        let upper_bound_length_in_bytes = modulus_length.div_ceil(8) as usize;
2845        let is_greater_than_upper_bound = |public_exponent: &[u8]| {
2846            let mut byte_iterator = public_exponent.iter().skip_while(|byte| **byte == 0);
2847            byte_iterator
2848                .next()
2849                .is_some_and(|byte| *byte > upper_bound_first_byte) &&
2850                byte_iterator.count() + 1 >= upper_bound_length_in_bytes
2851        };
2852        let is_equal_to_upper_bound = |public_exponent: &[u8]| {
2853            let mut byte_iterator = public_exponent.iter().skip_while(|byte| **byte == 0);
2854            byte_iterator
2855                .next()
2856                .is_some_and(|byte| *byte == upper_bound_first_byte) &&
2857                byte_iterator.clone().all(|byte| *byte == 255) &&
2858                byte_iterator.count() + 1 == upper_bound_length_in_bytes
2859        };
2860        if modulus_length < 4 ||
2861            is_less_than_3(public_exponent) ||
2862            is_even(public_exponent) ||
2863            is_greater_than_upper_bound(public_exponent) ||
2864            is_equal_to_upper_bound(public_exponent)
2865        {
2866            return Err(Error::Operation(Some(
2867                "Invalid RsaHashedKeyGenParams".into(),
2868            )));
2869        }
2870
2871        Ok(())
2872    }
2873}
2874
2875/// <https://w3c.github.io/webcrypto/#dfn-RsaHashedKeyAlgorithm>
2876#[derive(Clone, MallocSizeOf)]
2877pub(crate) struct RsaHashedKeyAlgorithm {
2878    /// <https://w3c.github.io/webcrypto/#dom-keyalgorithm-name>
2879    name: CryptoAlgorithm,
2880
2881    /// <https://w3c.github.io/webcrypto/#dfn-RsaKeyAlgorithm-modulusLength>
2882    modulus_length: u32,
2883
2884    /// <https://w3c.github.io/webcrypto/#dfn-RsaKeyAlgorithm-publicExponent>
2885    public_exponent: Vec<u8>,
2886
2887    /// <https://w3c.github.io/webcrypto/#dfn-RsaHashedKeyAlgorithm-hash>
2888    hash: DigestAlgorithm,
2889}
2890
2891impl ToJSValConvertible for RsaHashedKeyAlgorithm {
2892    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
2893        rooted!(&in(cx) let mut object = JS_NewObject(cx, None));
2894
2895        rooted!(&in(cx) let mut name_js = UndefinedValue());
2896        self.name.as_str().to_jsval(cx, name_js.handle_mut());
2897        set_dictionary_property(cx, object.handle(), c"name", name_js.handle())
2898            .expect("Failed to set name property of RsaHashedKeyAlgorithm");
2899
2900        rooted!(&in(cx) let mut modulus_length_js = UndefinedValue());
2901        self.modulus_length
2902            .to_jsval(cx, modulus_length_js.handle_mut());
2903        set_dictionary_property(
2904            cx,
2905            object.handle(),
2906            c"modulusLength",
2907            modulus_length_js.handle(),
2908        )
2909        .expect("Failed to set modulusLength property of RsaHashedKeyAlgorithm");
2910
2911        rooted!(&in(cx) let mut public_exponent_js = UndefinedValue());
2912        rooted!(&in(cx) let mut public_exponent_js_object = ptr::null_mut::<JSObject>());
2913        let public_exponent = create_buffer_source::<ArrayBufferU8>(
2914            cx,
2915            &self.public_exponent,
2916            public_exponent_js_object.handle_mut(),
2917        )
2918        .expect("Failed to convert publicExponent to Uint8Array");
2919        public_exponent.to_jsval(cx, public_exponent_js.handle_mut());
2920        set_dictionary_property(
2921            cx,
2922            object.handle(),
2923            c"publicExponent",
2924            public_exponent_js.handle(),
2925        )
2926        .expect("Failed to set publicExponent property of RsaHashedKeyAlgorithm");
2927
2928        rooted!(&in(cx) let mut hash_js = UndefinedValue());
2929        let hash = KeyAlgorithm {
2930            name: self.hash.name(),
2931        };
2932        hash.to_jsval(cx, hash_js.handle_mut());
2933        set_dictionary_property(cx, object.handle(), c"hash", hash_js.handle())
2934            .expect("Failed to set hash property of RsaHashedKeyAlgorithm");
2935
2936        rval.set(ObjectOrNullValue(object.get()));
2937    }
2938}
2939
2940impl TryFrom<SerializableRsaHashedKeyAlgorithm> for RsaHashedKeyAlgorithm {
2941    type Error = ();
2942
2943    fn try_from(value: SerializableRsaHashedKeyAlgorithm) -> Result<Self, Self::Error> {
2944        Ok(RsaHashedKeyAlgorithm {
2945            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
2946            modulus_length: value.modulus_length,
2947            public_exponent: value.public_exponent,
2948            hash: value.hash.try_into()?,
2949        })
2950    }
2951}
2952
2953impl From<&RsaHashedKeyAlgorithm> for SerializableRsaHashedKeyAlgorithm {
2954    fn from(value: &RsaHashedKeyAlgorithm) -> Self {
2955        SerializableRsaHashedKeyAlgorithm {
2956            name: value.name.as_str().into(),
2957            modulus_length: value.modulus_length,
2958            public_exponent: value.public_exponent.clone(),
2959            hash: (&value.hash).into(),
2960        }
2961    }
2962}
2963
2964/// <https://w3c.github.io/webcrypto/#dfn-RsaHashedImportParams>
2965#[derive(Clone, MallocSizeOf)]
2966struct RsaHashedImportParams {
2967    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
2968    name: CryptoAlgorithm,
2969
2970    /// <https://w3c.github.io/webcrypto/#dfn-RsaHashedImportParams-hash>
2971    hash: DigestAlgorithm,
2972}
2973
2974impl<'a> TryFromWithCxAndName<HandleObject<'a>> for RsaHashedImportParams {
2975    type Error = Error;
2976
2977    fn try_from_with_cx_and_name(
2978        cx: &mut JSContext,
2979        algorithm_name: CryptoAlgorithm,
2980        object: HandleObject,
2981    ) -> Result<Self, Self::Error> {
2982        let hash = get_required_parameter(cx, object, c"hash", ())?;
2983
2984        Ok(RsaHashedImportParams {
2985            name: algorithm_name,
2986            hash: normalize_algorithm::<DigestOperation>(cx, &hash)?,
2987        })
2988    }
2989}
2990
2991/// <https://w3c.github.io/webcrypto/#dfn-RsaPssParams>
2992#[derive(Clone, MallocSizeOf)]
2993struct RsaPssParams {
2994    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
2995    name: CryptoAlgorithm,
2996
2997    /// <https://w3c.github.io/webcrypto/#dfn-RsaPssParams-saltLength>
2998    salt_length: u32,
2999}
3000
3001impl<'a> TryFromWithCxAndName<HandleObject<'a>> for RsaPssParams {
3002    type Error = Error;
3003
3004    fn try_from_with_cx_and_name(
3005        cx: &mut JSContext,
3006        algorithm_name: CryptoAlgorithm,
3007        object: HandleObject,
3008    ) -> Result<Self, Self::Error> {
3009        Ok(RsaPssParams {
3010            name: algorithm_name,
3011            salt_length: get_required_parameter(
3012                cx,
3013                object,
3014                c"saltLength",
3015                ConversionBehavior::EnforceRange,
3016            )?,
3017        })
3018    }
3019}
3020
3021/// <https://w3c.github.io/webcrypto/#dfn-RsaOaepParams>
3022#[derive(Clone, MallocSizeOf)]
3023struct RsaOaepParams {
3024    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3025    name: CryptoAlgorithm,
3026
3027    /// <https://w3c.github.io/webcrypto/#dfn-RsaOaepParams-label>
3028    label: Option<Vec<u8>>,
3029}
3030
3031impl<'a> TryFromWithCxAndName<HandleObject<'a>> for RsaOaepParams {
3032    type Error = Error;
3033
3034    fn try_from_with_cx_and_name(
3035        cx: &mut JSContext,
3036        algorithm_name: CryptoAlgorithm,
3037        object: HandleObject<'a>,
3038    ) -> Result<Self, Self::Error> {
3039        Ok(RsaOaepParams {
3040            name: algorithm_name,
3041            label: get_optional_buffer_source(cx, object, c"label")?,
3042        })
3043    }
3044}
3045
3046/// <https://w3c.github.io/webcrypto/#dfn-EcdsaParams>
3047#[derive(Clone, MallocSizeOf)]
3048struct EcdsaParams {
3049    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3050    name: CryptoAlgorithm,
3051
3052    /// <https://w3c.github.io/webcrypto/#dfn-EcdsaParams-hash>
3053    hash: DigestAlgorithm,
3054}
3055
3056impl<'a> TryFromWithCxAndName<HandleObject<'a>> for EcdsaParams {
3057    type Error = Error;
3058
3059    fn try_from_with_cx_and_name(
3060        cx: &mut JSContext,
3061        algorithm_name: CryptoAlgorithm,
3062        object: HandleObject<'a>,
3063    ) -> Result<Self, Self::Error> {
3064        let hash = get_required_parameter(cx, object, c"hash", ())?;
3065
3066        Ok(EcdsaParams {
3067            name: algorithm_name,
3068            hash: normalize_algorithm::<DigestOperation>(cx, &hash)?,
3069        })
3070    }
3071}
3072
3073/// <https://w3c.github.io/webcrypto/#dfn-EcKeyGenParams>
3074#[derive(Clone, MallocSizeOf)]
3075struct EcKeyGenParams {
3076    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3077    name: CryptoAlgorithm,
3078
3079    /// <https://w3c.github.io/webcrypto/#dfn-EcKeyGenParams-namedCurve>
3080    named_curve: String,
3081}
3082
3083impl<'a> TryFromWithCxAndName<HandleObject<'a>> for EcKeyGenParams {
3084    type Error = Error;
3085
3086    fn try_from_with_cx_and_name(
3087        cx: &mut JSContext,
3088        algorithm_name: CryptoAlgorithm,
3089        object: HandleObject<'a>,
3090    ) -> Result<Self, Self::Error> {
3091        Ok(EcKeyGenParams {
3092            name: algorithm_name,
3093            named_curve: String::from(get_required_parameter::<DOMString>(
3094                cx,
3095                object,
3096                c"namedCurve",
3097                StringificationBehavior::Default,
3098            )?),
3099        })
3100    }
3101}
3102
3103/// <https://w3c.github.io/webcrypto/#dfn-EcKeyAlgorithm>
3104#[derive(Clone, MallocSizeOf)]
3105pub(crate) struct EcKeyAlgorithm {
3106    /// <https://w3c.github.io/webcrypto/#dom-keyalgorithm-name>
3107    name: CryptoAlgorithm,
3108
3109    /// <https://w3c.github.io/webcrypto/#dfn-EcKeyAlgorithm-namedCurve>
3110    named_curve: String,
3111}
3112
3113impl ToJSValConvertible for EcKeyAlgorithm {
3114    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
3115        rooted!(&in(cx) let mut object = JS_NewObject(cx, None));
3116
3117        rooted!(&in(cx) let mut name_js = UndefinedValue());
3118        self.name.as_str().to_jsval(cx, name_js.handle_mut());
3119        set_dictionary_property(cx, object.handle(), c"name", name_js.handle())
3120            .expect("Failed to set name property of EcKeyAlgorithm");
3121
3122        rooted!(&in(cx) let mut named_curve_js = UndefinedValue());
3123        self.named_curve.to_jsval(cx, named_curve_js.handle_mut());
3124        set_dictionary_property(cx, object.handle(), c"namedCurve", named_curve_js.handle())
3125            .expect("Failed to set namedCurve property of EcKeyAlgorithm");
3126
3127        rval.set(ObjectOrNullValue(object.get()));
3128    }
3129}
3130
3131impl TryFrom<SerializableEcKeyAlgorithm> for EcKeyAlgorithm {
3132    type Error = ();
3133
3134    fn try_from(value: SerializableEcKeyAlgorithm) -> Result<Self, Self::Error> {
3135        Ok(EcKeyAlgorithm {
3136            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
3137            named_curve: value.named_curve,
3138        })
3139    }
3140}
3141
3142impl From<&EcKeyAlgorithm> for SerializableEcKeyAlgorithm {
3143    fn from(value: &EcKeyAlgorithm) -> Self {
3144        SerializableEcKeyAlgorithm {
3145            name: value.name.as_str().into(),
3146            named_curve: value.named_curve.clone(),
3147        }
3148    }
3149}
3150
3151/// <https://w3c.github.io/webcrypto/#dfn-EcKeyImportParams>
3152#[derive(Clone, MallocSizeOf)]
3153struct EcKeyImportParams {
3154    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3155    name: CryptoAlgorithm,
3156
3157    /// <https://w3c.github.io/webcrypto/#dfn-EcKeyImportParams-namedCurve>
3158    named_curve: String,
3159}
3160
3161impl<'a> TryFromWithCxAndName<HandleObject<'a>> for EcKeyImportParams {
3162    type Error = Error;
3163
3164    fn try_from_with_cx_and_name(
3165        cx: &mut JSContext,
3166        algorithm_name: CryptoAlgorithm,
3167        object: HandleObject<'a>,
3168    ) -> Result<Self, Self::Error> {
3169        Ok(EcKeyImportParams {
3170            name: algorithm_name,
3171            named_curve: String::from(get_required_parameter::<DOMString>(
3172                cx,
3173                object,
3174                c"namedCurve",
3175                StringificationBehavior::Default,
3176            )?),
3177        })
3178    }
3179}
3180
3181/// <https://w3c.github.io/webcrypto/#dfn-EcdhKeyDeriveParams>
3182#[derive(Clone, MallocSizeOf)]
3183struct EcdhKeyDeriveParams<D: DomTypes> {
3184    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3185    name: CryptoAlgorithm,
3186
3187    /// <https://w3c.github.io/webcrypto/#dfn-EcdhKeyDeriveParams-public>
3188    public: Trusted<CryptoKey<D>>,
3189}
3190
3191impl<'a, D: DomTypes> TryFromWithCxAndName<HandleObject<'a>> for EcdhKeyDeriveParams<D> {
3192    type Error = Error;
3193
3194    fn try_from_with_cx_and_name(
3195        cx: &mut JSContext,
3196        algorithm_name: CryptoAlgorithm,
3197        object: HandleObject<'a>,
3198    ) -> Result<Self, Self::Error> {
3199        let public = get_required_parameter::<DomRoot<CryptoKey<D>>>(cx, object, c"public", ())?;
3200
3201        Ok(EcdhKeyDeriveParams {
3202            name: algorithm_name,
3203            public: Trusted::new(&public),
3204        })
3205    }
3206}
3207
3208/// <https://w3c.github.io/webcrypto/#dfn-AesCtrParams>
3209#[derive(Clone, MallocSizeOf)]
3210struct AesCtrParams {
3211    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3212    name: CryptoAlgorithm,
3213
3214    /// <https://w3c.github.io/webcrypto/#dfn-AesCtrParams-counter>
3215    counter: Vec<u8>,
3216
3217    /// <https://w3c.github.io/webcrypto/#dfn-AesCtrParams-length>
3218    length: u8,
3219}
3220
3221impl<'a> TryFromWithCxAndName<HandleObject<'a>> for AesCtrParams {
3222    type Error = Error;
3223
3224    fn try_from_with_cx_and_name(
3225        cx: &mut JSContext,
3226        algorithm_name: CryptoAlgorithm,
3227        object: HandleObject<'a>,
3228    ) -> Result<Self, Self::Error> {
3229        Ok(AesCtrParams {
3230            name: algorithm_name,
3231            counter: get_required_buffer_source(cx, object, c"counter")?,
3232            length: get_required_parameter(
3233                cx,
3234                object,
3235                c"length",
3236                ConversionBehavior::EnforceRange,
3237            )?,
3238        })
3239    }
3240}
3241
3242/// <https://w3c.github.io/webcrypto/#dfn-AesKeyAlgorithm>
3243#[derive(Clone, MallocSizeOf)]
3244pub(crate) struct AesKeyAlgorithm {
3245    /// <https://w3c.github.io/webcrypto/#dom-keyalgorithm-name>
3246    name: CryptoAlgorithm,
3247
3248    /// <https://w3c.github.io/webcrypto/#dfn-AesKeyAlgorithm-length>
3249    length: u16,
3250}
3251
3252impl ToJSValConvertible for AesKeyAlgorithm {
3253    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
3254        rooted!(&in(cx) let mut object = JS_NewObject(cx, None));
3255
3256        rooted!(&in(cx) let mut name_js = UndefinedValue());
3257        self.name.as_str().to_jsval(cx, name_js.handle_mut());
3258        set_dictionary_property(cx, object.handle(), c"name", name_js.handle())
3259            .expect("Failed to set name property of AesKeyAlgorithm");
3260
3261        rooted!(&in(cx) let mut length_js = UndefinedValue());
3262        self.length.to_jsval(cx, length_js.handle_mut());
3263        set_dictionary_property(cx, object.handle(), c"length", length_js.handle())
3264            .expect("Failed to set length property of AesKeyAlgorithm");
3265
3266        rval.set(ObjectOrNullValue(object.get()));
3267    }
3268}
3269
3270impl TryFrom<SerializableAesKeyAlgorithm> for AesKeyAlgorithm {
3271    type Error = ();
3272
3273    fn try_from(value: SerializableAesKeyAlgorithm) -> Result<Self, Self::Error> {
3274        Ok(AesKeyAlgorithm {
3275            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
3276            length: value.length,
3277        })
3278    }
3279}
3280
3281impl From<&AesKeyAlgorithm> for SerializableAesKeyAlgorithm {
3282    fn from(value: &AesKeyAlgorithm) -> Self {
3283        SerializableAesKeyAlgorithm {
3284            name: value.name.as_str().into(),
3285            length: value.length,
3286        }
3287    }
3288}
3289
3290/// <https://w3c.github.io/webcrypto/#dfn-AesKeyGenParams>
3291#[derive(Clone, MallocSizeOf)]
3292struct AesKeyGenParams {
3293    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3294    name: CryptoAlgorithm,
3295
3296    /// <https://w3c.github.io/webcrypto/#dfn-AesKeyGenParams-length>
3297    length: u16,
3298}
3299
3300impl<'a> TryFromWithCxAndName<HandleObject<'a>> for AesKeyGenParams {
3301    type Error = Error;
3302
3303    fn try_from_with_cx_and_name(
3304        cx: &mut JSContext,
3305        algorithm_name: CryptoAlgorithm,
3306        object: HandleObject<'a>,
3307    ) -> Result<Self, Self::Error> {
3308        Ok(AesKeyGenParams {
3309            name: algorithm_name,
3310            length: get_required_parameter(
3311                cx,
3312                object,
3313                c"length",
3314                ConversionBehavior::EnforceRange,
3315            )?,
3316        })
3317    }
3318}
3319
3320/// <https://w3c.github.io/webcrypto/#dfn-AesDerivedKeyParams>
3321#[derive(Clone, MallocSizeOf)]
3322struct AesDerivedKeyParams {
3323    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3324    name: CryptoAlgorithm,
3325
3326    /// <https://w3c.github.io/webcrypto/#dfn-AesDerivedKeyParams-length>
3327    length: u16,
3328}
3329
3330impl<'a> TryFromWithCxAndName<HandleObject<'a>> for AesDerivedKeyParams {
3331    type Error = Error;
3332
3333    fn try_from_with_cx_and_name(
3334        cx: &mut JSContext,
3335        algorithm_name: CryptoAlgorithm,
3336        object: HandleObject<'a>,
3337    ) -> Result<Self, Self::Error> {
3338        Ok(AesDerivedKeyParams {
3339            name: algorithm_name,
3340            length: get_required_parameter(
3341                cx,
3342                object,
3343                c"length",
3344                ConversionBehavior::EnforceRange,
3345            )?,
3346        })
3347    }
3348}
3349
3350/// <https://w3c.github.io/webcrypto/#dfn-AesCbcParams>
3351#[derive(Clone, MallocSizeOf)]
3352struct AesCbcParams {
3353    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3354    name: CryptoAlgorithm,
3355
3356    /// <https://w3c.github.io/webcrypto/#dfn-AesCbcParams-iv>
3357    iv: Vec<u8>,
3358}
3359
3360impl<'a> TryFromWithCxAndName<HandleObject<'a>> for AesCbcParams {
3361    type Error = Error;
3362
3363    fn try_from_with_cx_and_name(
3364        cx: &mut JSContext,
3365        algorithm_name: CryptoAlgorithm,
3366        object: HandleObject<'a>,
3367    ) -> Result<Self, Self::Error> {
3368        Ok(AesCbcParams {
3369            name: algorithm_name,
3370            iv: get_required_buffer_source(cx, object, c"iv")?,
3371        })
3372    }
3373}
3374
3375/// <https://w3c.github.io/webcrypto/#dfn-AesGcmParams>
3376#[derive(Clone, MallocSizeOf)]
3377struct AesGcmParams {
3378    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3379    name: CryptoAlgorithm,
3380
3381    /// <https://w3c.github.io/webcrypto/#dfn-AesGcmParams-iv>
3382    iv: Vec<u8>,
3383
3384    /// <https://w3c.github.io/webcrypto/#dfn-AesGcmParams-additionalData>
3385    additional_data: Option<Vec<u8>>,
3386
3387    /// <https://w3c.github.io/webcrypto/#dfn-AesGcmParams-tagLength>
3388    tag_length: Option<u8>,
3389}
3390
3391impl<'a> TryFromWithCxAndName<HandleObject<'a>> for AesGcmParams {
3392    type Error = Error;
3393
3394    fn try_from_with_cx_and_name(
3395        cx: &mut JSContext,
3396        algorithm_name: CryptoAlgorithm,
3397        object: HandleObject<'a>,
3398    ) -> Result<Self, Self::Error> {
3399        Ok(AesGcmParams {
3400            name: algorithm_name,
3401            iv: get_required_buffer_source(cx, object, c"iv")?,
3402            additional_data: get_optional_buffer_source(cx, object, c"additionalData")?,
3403            tag_length: get_property(cx, object, c"tagLength", ConversionBehavior::EnforceRange)?,
3404        })
3405    }
3406}
3407
3408/// <https://w3c.github.io/webcrypto/#dfn-HmacImportParams>
3409#[derive(Clone, MallocSizeOf)]
3410struct HmacImportParams {
3411    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3412    name: CryptoAlgorithm,
3413
3414    /// <https://w3c.github.io/webcrypto/#dfn-HmacImportParams-hash>
3415    hash: DigestAlgorithm,
3416
3417    /// <https://w3c.github.io/webcrypto/#dfn-HmacImportParams-length>
3418    length: Option<u32>,
3419}
3420
3421impl<'a> TryFromWithCxAndName<HandleObject<'a>> for HmacImportParams {
3422    type Error = Error;
3423
3424    fn try_from_with_cx_and_name(
3425        cx: &mut JSContext,
3426        algorithm_name: CryptoAlgorithm,
3427        object: HandleObject<'a>,
3428    ) -> Result<Self, Self::Error> {
3429        let hash = get_required_parameter(cx, object, c"hash", ())?;
3430
3431        Ok(HmacImportParams {
3432            name: algorithm_name,
3433            hash: normalize_algorithm::<DigestOperation>(cx, &hash)?,
3434            length: get_property(cx, object, c"length", ConversionBehavior::EnforceRange)?,
3435        })
3436    }
3437}
3438
3439/// <https://w3c.github.io/webcrypto/#dfn-HmacKeyAlgorithm>
3440#[derive(Clone, MallocSizeOf)]
3441pub(crate) struct HmacKeyAlgorithm {
3442    /// <https://w3c.github.io/webcrypto/#dom-keyalgorithm-name>
3443    name: CryptoAlgorithm,
3444
3445    /// <https://w3c.github.io/webcrypto/#dfn-HmacKeyAlgorithm-hash>
3446    hash: DigestAlgorithm,
3447
3448    /// <https://w3c.github.io/webcrypto/#dfn-HmacKeyGenParams-length>
3449    length: u32,
3450}
3451
3452impl ToJSValConvertible for HmacKeyAlgorithm {
3453    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
3454        rooted!(&in(cx) let mut object = JS_NewObject(cx, None));
3455
3456        rooted!(&in(cx) let mut name_js = UndefinedValue());
3457        self.name.as_str().to_jsval(cx, name_js.handle_mut());
3458        set_dictionary_property(cx, object.handle(), c"name", name_js.handle())
3459            .expect("Failed to set name property of HmacKeyAlgorithm");
3460
3461        rooted!(&in(cx) let mut hash_js = UndefinedValue());
3462        let hash = KeyAlgorithm {
3463            name: self.hash.name(),
3464        };
3465        hash.to_jsval(cx, hash_js.handle_mut());
3466        set_dictionary_property(cx, object.handle(), c"hash", hash_js.handle())
3467            .expect("Failed to set hash property of HmacKeyAlgorithm");
3468
3469        rooted!(&in(cx) let mut length_js = UndefinedValue());
3470        self.length.to_jsval(cx, length_js.handle_mut());
3471        set_dictionary_property(cx, object.handle(), c"length", length_js.handle())
3472            .expect("Failed to set length property of HmacKeyAlgorithm");
3473
3474        rval.set(ObjectOrNullValue(object.get()));
3475    }
3476}
3477
3478impl TryFrom<SerializableHmacKeyAlgorithm> for HmacKeyAlgorithm {
3479    type Error = ();
3480
3481    fn try_from(value: SerializableHmacKeyAlgorithm) -> Result<Self, Self::Error> {
3482        Ok(HmacKeyAlgorithm {
3483            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
3484            hash: value.hash.try_into()?,
3485            length: value.length,
3486        })
3487    }
3488}
3489
3490impl From<&HmacKeyAlgorithm> for SerializableHmacKeyAlgorithm {
3491    fn from(value: &HmacKeyAlgorithm) -> Self {
3492        SerializableHmacKeyAlgorithm {
3493            name: value.name.as_str().into(),
3494            hash: (&value.hash).into(),
3495            length: value.length,
3496        }
3497    }
3498}
3499
3500/// <https://w3c.github.io/webcrypto/#dfn-HmacKeyGenParams>
3501#[derive(Clone, MallocSizeOf)]
3502struct HmacKeyGenParams {
3503    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3504    name: CryptoAlgorithm,
3505
3506    /// <https://w3c.github.io/webcrypto/#dfn-HmacKeyGenParams-hash>
3507    hash: DigestAlgorithm,
3508
3509    /// <https://w3c.github.io/webcrypto/#dfn-HmacKeyGenParams-length>
3510    length: Option<u32>,
3511}
3512
3513impl<'a> TryFromWithCxAndName<HandleObject<'a>> for HmacKeyGenParams {
3514    type Error = Error;
3515
3516    fn try_from_with_cx_and_name(
3517        cx: &mut JSContext,
3518        algorithm_name: CryptoAlgorithm,
3519        object: HandleObject<'a>,
3520    ) -> Result<Self, Self::Error> {
3521        let hash = get_required_parameter(cx, object, c"hash", ())?;
3522
3523        Ok(HmacKeyGenParams {
3524            name: algorithm_name,
3525            hash: normalize_algorithm::<DigestOperation>(cx, &hash)?,
3526            length: get_property(cx, object, c"length", ConversionBehavior::EnforceRange)?,
3527        })
3528    }
3529}
3530
3531/// <https://w3c.github.io/webcrypto/#dfn-HkdfParams>
3532#[derive(Clone, MallocSizeOf)]
3533pub(crate) struct HkdfParams {
3534    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3535    name: CryptoAlgorithm,
3536
3537    /// <https://w3c.github.io/webcrypto/#dfn-HkdfParams-hash>
3538    hash: DigestAlgorithm,
3539
3540    /// <https://w3c.github.io/webcrypto/#dfn-HkdfParams-salt>
3541    salt: Vec<u8>,
3542
3543    /// <https://w3c.github.io/webcrypto/#dfn-HkdfParams-info>
3544    info: Vec<u8>,
3545}
3546
3547impl<'a> TryFromWithCxAndName<HandleObject<'a>> for HkdfParams {
3548    type Error = Error;
3549
3550    fn try_from_with_cx_and_name(
3551        cx: &mut JSContext,
3552        algorithm_name: CryptoAlgorithm,
3553        object: HandleObject<'a>,
3554    ) -> Result<Self, Self::Error> {
3555        let hash = get_required_parameter(cx, object, c"hash", ())?;
3556
3557        Ok(HkdfParams {
3558            name: algorithm_name,
3559            hash: normalize_algorithm::<DigestOperation>(cx, &hash)?,
3560            salt: get_required_buffer_source(cx, object, c"salt")?,
3561            info: get_required_buffer_source(cx, object, c"info")?,
3562        })
3563    }
3564}
3565
3566/// <https://w3c.github.io/webcrypto/#dfn-Pbkdf2Params>
3567#[derive(Clone, MallocSizeOf)]
3568pub(crate) struct Pbkdf2Params {
3569    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3570    name: CryptoAlgorithm,
3571
3572    /// <https://w3c.github.io/webcrypto/#dfn-Pbkdf2Params-salt>
3573    salt: Vec<u8>,
3574
3575    /// <https://w3c.github.io/webcrypto/#dfn-Pbkdf2Params-iterations>
3576    iterations: u32,
3577
3578    /// <https://w3c.github.io/webcrypto/#dfn-Pbkdf2Params-hash>
3579    hash: DigestAlgorithm,
3580}
3581
3582impl<'a> TryFromWithCxAndName<HandleObject<'a>> for Pbkdf2Params {
3583    type Error = Error;
3584
3585    fn try_from_with_cx_and_name(
3586        cx: &mut JSContext,
3587        algorithm_name: CryptoAlgorithm,
3588        object: HandleObject<'a>,
3589    ) -> Result<Self, Self::Error> {
3590        let hash = get_required_parameter(cx, object, c"hash", ())?;
3591
3592        Ok(Pbkdf2Params {
3593            name: algorithm_name,
3594            salt: get_required_buffer_source(cx, object, c"salt")?,
3595            iterations: get_required_parameter(
3596                cx,
3597                object,
3598                c"iterations",
3599                ConversionBehavior::EnforceRange,
3600            )?,
3601            hash: normalize_algorithm::<DigestOperation>(cx, &hash)?,
3602        })
3603    }
3604}
3605
3606/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-ContextParams>
3607#[derive(Clone, MallocSizeOf)]
3608struct ContextParams {
3609    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3610    name: CryptoAlgorithm,
3611
3612    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-ContextParams-context>
3613    context: Option<Vec<u8>>,
3614}
3615
3616impl<'a> TryFromWithCxAndName<HandleObject<'a>> for ContextParams {
3617    type Error = Error;
3618
3619    fn try_from_with_cx_and_name(
3620        cx: &mut JSContext,
3621        algorithm_name: CryptoAlgorithm,
3622        object: HandleObject<'a>,
3623    ) -> Result<Self, Self::Error> {
3624        Ok(ContextParams {
3625            name: algorithm_name,
3626            context: get_optional_buffer_source(cx, object, c"context")?,
3627        })
3628    }
3629}
3630
3631/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-AeadParams>
3632#[derive(Clone, MallocSizeOf)]
3633struct AeadParams {
3634    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3635    name: CryptoAlgorithm,
3636
3637    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-AeadParams-iv>
3638    iv: Vec<u8>,
3639
3640    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-AeadParams-additionalData>
3641    additional_data: Option<Vec<u8>>,
3642
3643    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-AeadParams-tagLength>
3644    tag_length: Option<u8>,
3645}
3646
3647impl<'a> TryFromWithCxAndName<HandleObject<'a>> for AeadParams {
3648    type Error = Error;
3649
3650    fn try_from_with_cx_and_name(
3651        cx: &mut JSContext,
3652        algorithm_name: CryptoAlgorithm,
3653        object: HandleObject<'a>,
3654    ) -> Result<Self, Self::Error> {
3655        Ok(AeadParams {
3656            name: algorithm_name,
3657            iv: get_required_buffer_source(cx, object, c"iv")?,
3658            additional_data: get_optional_buffer_source(cx, object, c"additionalData")?,
3659            tag_length: get_property(cx, object, c"tagLength", ConversionBehavior::EnforceRange)?,
3660        })
3661    }
3662}
3663
3664/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-CShakeParams>
3665#[derive(Clone, MallocSizeOf)]
3666struct CShakeParams {
3667    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3668    name: CryptoAlgorithm,
3669
3670    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-CShakeParams-outputLength>
3671    output_length: u32,
3672
3673    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-CShakeParams-functionName>
3674    function_name: Option<Vec<u8>>,
3675
3676    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-CShakeParams-customization>
3677    customization: Option<Vec<u8>>,
3678}
3679
3680impl<'a> TryFromWithCxAndName<HandleObject<'a>> for CShakeParams {
3681    type Error = Error;
3682
3683    fn try_from_with_cx_and_name(
3684        cx: &mut JSContext,
3685        algorithm_name: CryptoAlgorithm,
3686        object: HandleObject<'a>,
3687    ) -> Result<Self, Self::Error> {
3688        Ok(CShakeParams {
3689            name: algorithm_name,
3690            output_length: get_required_parameter(
3691                cx,
3692                object,
3693                c"outputLength",
3694                ConversionBehavior::EnforceRange,
3695            )?,
3696            function_name: get_optional_buffer_source(cx, object, c"functionName")?,
3697            customization: get_optional_buffer_source(cx, object, c"customization")?,
3698        })
3699    }
3700}
3701
3702impl TryFrom<SerializableCShakeParams> for CShakeParams {
3703    type Error = ();
3704
3705    fn try_from(value: SerializableCShakeParams) -> Result<Self, Self::Error> {
3706        Ok(CShakeParams {
3707            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
3708            output_length: value.output_length,
3709            function_name: value.function_name,
3710            customization: value.customization,
3711        })
3712    }
3713}
3714
3715impl From<&CShakeParams> for SerializableCShakeParams {
3716    fn from(value: &CShakeParams) -> Self {
3717        SerializableCShakeParams {
3718            name: value.name.as_str().into(),
3719            output_length: value.output_length,
3720            function_name: value.function_name.clone(),
3721            customization: value.customization.clone(),
3722        }
3723    }
3724}
3725
3726/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-TurboShakeParams>
3727#[derive(Clone, MallocSizeOf)]
3728struct TurboShakeParams {
3729    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3730    name: CryptoAlgorithm,
3731
3732    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-TurboShakeParams-outputLength>
3733    output_length: u32,
3734
3735    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-TurboShakeParams-domainSeparation>
3736    domain_separation: Option<u8>,
3737}
3738
3739impl<'a> TryFromWithCxAndName<HandleObject<'a>> for TurboShakeParams {
3740    type Error = Error;
3741
3742    fn try_from_with_cx_and_name(
3743        cx: &mut JSContext,
3744        algorithm_name: CryptoAlgorithm,
3745        object: HandleObject<'a>,
3746    ) -> Result<Self, Self::Error> {
3747        Ok(TurboShakeParams {
3748            name: algorithm_name,
3749            output_length: get_required_parameter(
3750                cx,
3751                object,
3752                c"outputLength",
3753                ConversionBehavior::EnforceRange,
3754            )?,
3755            domain_separation: get_property(
3756                cx,
3757                object,
3758                c"domainSeparation",
3759                ConversionBehavior::EnforceRange,
3760            )?,
3761        })
3762    }
3763}
3764
3765impl TryFrom<SerializableTurboShakeParams> for TurboShakeParams {
3766    type Error = ();
3767
3768    fn try_from(value: SerializableTurboShakeParams) -> Result<Self, Self::Error> {
3769        Ok(TurboShakeParams {
3770            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
3771            output_length: value.output_length,
3772            domain_separation: value.domain_separation,
3773        })
3774    }
3775}
3776
3777impl From<&TurboShakeParams> for SerializableTurboShakeParams {
3778    fn from(value: &TurboShakeParams) -> Self {
3779        SerializableTurboShakeParams {
3780            name: value.name.as_str().into(),
3781            output_length: value.output_length,
3782            domain_separation: value.domain_separation,
3783        }
3784    }
3785}
3786
3787/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KangarooTwelveParams>
3788#[derive(Clone, MallocSizeOf)]
3789struct KangarooTwelveParams {
3790    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3791    name: CryptoAlgorithm,
3792
3793    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KangarooTwelveParams-outputLength>
3794    output_length: u32,
3795
3796    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KangarooTwelveParams-customization>
3797    customization: Option<Vec<u8>>,
3798}
3799
3800impl<'a> TryFromWithCxAndName<HandleObject<'a>> for KangarooTwelveParams {
3801    type Error = Error;
3802
3803    fn try_from_with_cx_and_name(
3804        cx: &mut JSContext,
3805        algorithm_name: CryptoAlgorithm,
3806        object: HandleObject<'a>,
3807    ) -> Result<Self, Self::Error> {
3808        Ok(KangarooTwelveParams {
3809            name: algorithm_name,
3810            output_length: get_required_parameter(
3811                cx,
3812                object,
3813                c"outputLength",
3814                ConversionBehavior::EnforceRange,
3815            )?,
3816            customization: get_optional_buffer_source(cx, object, c"customization")?,
3817        })
3818    }
3819}
3820
3821impl TryFrom<SerializableKangarooTwelveParams> for KangarooTwelveParams {
3822    type Error = ();
3823
3824    fn try_from(value: SerializableKangarooTwelveParams) -> Result<Self, Self::Error> {
3825        Ok(KangarooTwelveParams {
3826            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
3827            output_length: value.output_length,
3828            customization: value.customization,
3829        })
3830    }
3831}
3832
3833impl From<&KangarooTwelveParams> for SerializableKangarooTwelveParams {
3834    fn from(value: &KangarooTwelveParams) -> Self {
3835        SerializableKangarooTwelveParams {
3836            name: value.name.as_str().into(),
3837            output_length: value.output_length,
3838            customization: value.customization.clone(),
3839        }
3840    }
3841}
3842
3843/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacKeyGenParams>
3844#[derive(Clone, MallocSizeOf)]
3845struct KmacKeyGenParams {
3846    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3847    name: CryptoAlgorithm,
3848
3849    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacKeyGenParams-length>
3850    length: Option<u32>,
3851}
3852
3853impl<'a> TryFromWithCxAndName<HandleObject<'a>> for KmacKeyGenParams {
3854    type Error = Error;
3855
3856    fn try_from_with_cx_and_name(
3857        cx: &mut JSContext,
3858        algorithm_name: CryptoAlgorithm,
3859        object: HandleObject,
3860    ) -> Result<Self, Self::Error> {
3861        Ok(KmacKeyGenParams {
3862            name: algorithm_name,
3863            length: get_property(cx, object, c"length", ConversionBehavior::EnforceRange)?,
3864        })
3865    }
3866}
3867
3868/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacImportParams>
3869#[derive(Clone, MallocSizeOf)]
3870struct KmacImportParams {
3871    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3872    name: CryptoAlgorithm,
3873
3874    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacImportParams-length>
3875    length: Option<u32>,
3876}
3877
3878impl<'a> TryFromWithCxAndName<HandleObject<'a>> for KmacImportParams {
3879    type Error = Error;
3880
3881    fn try_from_with_cx_and_name(
3882        cx: &mut JSContext,
3883        algorithm_name: CryptoAlgorithm,
3884        object: HandleObject,
3885    ) -> Result<Self, Self::Error> {
3886        Ok(KmacImportParams {
3887            name: algorithm_name,
3888            length: get_property(cx, object, c"length", ConversionBehavior::EnforceRange)?,
3889        })
3890    }
3891}
3892
3893/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacKeyAlgorithm>
3894#[derive(Clone, MallocSizeOf)]
3895pub(crate) struct KmacKeyAlgorithm {
3896    /// <https://w3c.github.io/webcrypto/#dom-keyalgorithm-name>
3897    name: CryptoAlgorithm,
3898
3899    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacKeyAlgorithm-length>
3900    length: u32,
3901}
3902
3903impl ToJSValConvertible for KmacKeyAlgorithm {
3904    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
3905        rooted!(&in(cx) let mut object = JS_NewObject(cx, None));
3906
3907        rooted!(&in(cx) let mut name_js = UndefinedValue());
3908        self.name.as_str().to_jsval(cx, name_js.handle_mut());
3909        set_dictionary_property(cx, object.handle(), c"name", name_js.handle())
3910            .expect("Failed to set name property of KmacKeyAlgorithm");
3911
3912        rooted!(&in(cx) let mut length_js = UndefinedValue());
3913        self.length.to_jsval(cx, length_js.handle_mut());
3914        set_dictionary_property(cx, object.handle(), c"length", length_js.handle())
3915            .expect("Failed to set length property of KmacKeyAlgorithm");
3916
3917        rval.set(ObjectOrNullValue(object.get()));
3918    }
3919}
3920
3921impl TryFrom<SerializableKmacKeyAlgorithm> for KmacKeyAlgorithm {
3922    type Error = ();
3923
3924    fn try_from(value: SerializableKmacKeyAlgorithm) -> Result<Self, Self::Error> {
3925        Ok(KmacKeyAlgorithm {
3926            name: CryptoAlgorithm::from_str(&value.name).map_err(|_| ())?,
3927            length: value.length,
3928        })
3929    }
3930}
3931
3932impl From<&KmacKeyAlgorithm> for SerializableKmacKeyAlgorithm {
3933    fn from(value: &KmacKeyAlgorithm) -> Self {
3934        SerializableKmacKeyAlgorithm {
3935            name: value.name.as_str().into(),
3936            length: value.length,
3937        }
3938    }
3939}
3940
3941/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacParams>
3942struct KmacParams {
3943    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3944    name: CryptoAlgorithm,
3945
3946    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacParams-outputLength>
3947    output_length: u32,
3948
3949    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-KmacParams-customization>
3950    customization: Option<Vec<u8>>,
3951}
3952
3953impl<'a> TryFromWithCxAndName<HandleObject<'a>> for KmacParams {
3954    type Error = Error;
3955
3956    fn try_from_with_cx_and_name(
3957        cx: &mut JSContext,
3958        algorithm_name: CryptoAlgorithm,
3959        object: HandleObject<'a>,
3960    ) -> Result<Self, Self::Error> {
3961        Ok(KmacParams {
3962            name: algorithm_name,
3963            output_length: get_required_parameter(
3964                cx,
3965                object,
3966                c"outputLength",
3967                ConversionBehavior::EnforceRange,
3968            )?,
3969            customization: get_optional_buffer_source(cx, object, c"customization")?,
3970        })
3971    }
3972}
3973
3974/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-Argon2Params>
3975#[derive(Clone, MallocSizeOf)]
3976struct Argon2Params {
3977    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
3978    name: CryptoAlgorithm,
3979
3980    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-Argon2Params-nonce>
3981    nonce: Vec<u8>,
3982
3983    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-Argon2Params-parallelism>
3984    parallelism: u32,
3985
3986    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-Argon2Params-memory>
3987    memory: u32,
3988
3989    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-Argon2Params-passes>
3990    passes: u32,
3991
3992    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-Argon2Params-version>
3993    version: Option<u8>,
3994
3995    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-Argon2Params-secretValue>
3996    secret_value: Option<Vec<u8>>,
3997
3998    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-Argon2Params-associatedData>
3999    associated_data: Option<Vec<u8>>,
4000}
4001
4002impl<'a> TryFromWithCxAndName<HandleObject<'a>> for Argon2Params {
4003    type Error = Error;
4004
4005    fn try_from_with_cx_and_name(
4006        cx: &mut JSContext,
4007        algorithm_name: CryptoAlgorithm,
4008        object: HandleObject<'a>,
4009    ) -> Result<Self, Self::Error> {
4010        Ok(Argon2Params {
4011            name: algorithm_name,
4012            nonce: get_required_buffer_source(cx, object, c"nonce")?,
4013            parallelism: get_required_parameter(
4014                cx,
4015                object,
4016                c"parallelism",
4017                ConversionBehavior::EnforceRange,
4018            )?,
4019            memory: get_required_parameter(
4020                cx,
4021                object,
4022                c"memory",
4023                ConversionBehavior::EnforceRange,
4024            )?,
4025            passes: get_required_parameter(
4026                cx,
4027                object,
4028                c"passes",
4029                ConversionBehavior::EnforceRange,
4030            )?,
4031            version: get_property(cx, object, c"version", ConversionBehavior::EnforceRange)?,
4032            secret_value: get_optional_buffer_source(cx, object, c"secretValue")?,
4033            associated_data: get_optional_buffer_source(cx, object, c"associatedData")?,
4034        })
4035    }
4036}
4037
4038/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-EncapsulatedKey>
4039struct EncapsulatedKey<D: DomTypes> {
4040    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-EncapsulatedKey-sharedKey>
4041    shared_key: Option<Trusted<CryptoKey<D>>>,
4042
4043    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-EncapsulatedKey-ciphertext>
4044    ciphertext: Option<Vec<u8>>,
4045}
4046
4047impl<D: DomTypes> ToJSValConvertible for EncapsulatedKey<D> {
4048    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
4049        rooted!(&in(cx) let mut object = JS_NewObject(cx, None));
4050
4051        rooted!(&in(cx) let mut shared_key_js = UndefinedValue());
4052        self.shared_key
4053            .as_ref()
4054            .map(|shared_key| shared_key.root())
4055            .to_jsval(cx, shared_key_js.handle_mut());
4056        set_dictionary_property(cx, object.handle(), c"sharedKey", shared_key_js.handle())
4057            .expect("Failed to set sharedKey property of EncapsulatedKey");
4058
4059        rooted!(&in(cx) let mut ciphertext_js = UndefinedValue());
4060        self.ciphertext
4061            .as_ref()
4062            .map(|ciphertext| {
4063                rooted!(&in(cx) let mut ciphertext_js_object = ptr::null_mut::<JSObject>());
4064                create_buffer_source::<ArrayBufferU8>(
4065                    cx,
4066                    ciphertext,
4067                    ciphertext_js_object.handle_mut(),
4068                )
4069                .expect("Failed to convert ciphertext to ArrayBufferU8")
4070            })
4071            .to_jsval(cx, ciphertext_js.handle_mut());
4072        set_dictionary_property(cx, object.handle(), c"ciphertext", ciphertext_js.handle())
4073            .expect("Failed to set ciphertext property of EncapsulatedKey");
4074
4075        rval.set(ObjectOrNullValue(object.get()));
4076    }
4077}
4078
4079/// <https://wicg.github.io/webcrypto-modern-algos/#dfn-EncapsulatedBits>
4080struct EncapsulatedBits {
4081    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-EncapsulatedBits-sharedKey>
4082    shared_key: Option<Zeroizing<Vec<u8>>>,
4083
4084    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-EncapsulatedBits-ciphertext>
4085    ciphertext: Option<Vec<u8>>,
4086}
4087
4088impl ToJSValConvertible for EncapsulatedBits {
4089    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
4090        rooted!(&in(cx) let mut object = JS_NewObject(cx, None));
4091
4092        rooted!(&in(cx) let mut shared_key_js = UndefinedValue());
4093        self.shared_key
4094            .as_ref()
4095            .map(|shared_key| {
4096                rooted!(&in(cx) let mut shared_key_js_object = ptr::null_mut::<JSObject>());
4097                create_buffer_source::<ArrayBufferU8>(
4098                    cx,
4099                    shared_key,
4100                    shared_key_js_object.handle_mut(),
4101                )
4102                .expect("Failed to convert shared_key to ArrayBufferU8")
4103            })
4104            .to_jsval(cx, shared_key_js.handle_mut());
4105        set_dictionary_property(cx, object.handle(), c"sharedKey", shared_key_js.handle())
4106            .expect("Failed to set sharedKey property of EncapsulatedBits");
4107
4108        rooted!(&in(cx) let mut ciphertext_js = UndefinedValue());
4109        self.ciphertext
4110            .as_ref()
4111            .map(|ciphertext| {
4112                rooted!(&in(cx) let mut ciphertext_js_object = ptr::null_mut::<JSObject>());
4113                create_buffer_source::<ArrayBufferU8>(
4114                    cx,
4115                    ciphertext,
4116                    ciphertext_js_object.handle_mut(),
4117                )
4118                .expect("Failed to convert ciphertext to ArrayBufferU8")
4119            })
4120            .to_jsval(cx, ciphertext_js.handle_mut());
4121        set_dictionary_property(cx, object.handle(), c"ciphertext", ciphertext_js.handle())
4122            .expect("Failed to set ciphertext property of EncapsulatedBits");
4123
4124        rval.set(ObjectOrNullValue(object.get()));
4125    }
4126}
4127
4128/// <https://wicg.github.io/webcrypto-secure-curves/#dfn-Ed448Params>
4129#[derive(Clone, MallocSizeOf)]
4130struct SubtleEd448Params {
4131    /// <https://w3c.github.io/webcrypto/#dom-algorithm-name>
4132    name: CryptoAlgorithm,
4133
4134    /// <https://wicg.github.io/webcrypto-secure-curves/#dfn-Ed448Params-context>
4135    context: Option<Vec<u8>>,
4136}
4137
4138impl<'a> TryFromWithCxAndName<HandleObject<'a>> for SubtleEd448Params {
4139    type Error = Error;
4140
4141    fn try_from_with_cx_and_name(
4142        cx: &mut JSContext,
4143        algorithm_name: CryptoAlgorithm,
4144        object: HandleObject<'a>,
4145    ) -> Result<Self, Self::Error> {
4146        Ok(SubtleEd448Params {
4147            name: algorithm_name,
4148            context: get_optional_buffer_source(cx, object, c"context")?,
4149        })
4150    }
4151}
4152
4153/// Helper to retrieve a required paramter from WebIDL dictionary.
4154fn get_required_parameter<T: FromJSValConvertible>(
4155    cx: &mut JSContext,
4156    object: HandleObject,
4157    parameter: &std::ffi::CStr,
4158    option: T::Config,
4159) -> Fallible<T> {
4160    get_property::<T>(cx, object, parameter, option)?
4161        .ok_or(Error::Type(c"Missing required parameter".into()))
4162}
4163
4164/// Helper to retrieve a required paramter, in RootedTraceableBox, from WebIDL dictionary.
4165fn get_required_parameter_in_box<T: FromJSValConvertible + Trace>(
4166    cx: &mut JSContext,
4167    object: HandleObject,
4168    parameter: &std::ffi::CStr,
4169    option: T::Config,
4170) -> Fallible<RootedTraceableBox<T>> {
4171    get_property::<T>(cx, object, parameter, option)?
4172        .map(RootedTraceableBox::new)
4173        .ok_or(Error::Type(c"Missing required parameter".into()))
4174}
4175
4176/// Helper to retrieve an optional paramter in BufferSource from WebIDL dictionary, and get a copy
4177/// of the bytes held by the buffer source according to
4178/// <https://webidl.spec.whatwg.org/#dfn-get-buffer-source-copy>
4179fn get_optional_buffer_source(
4180    cx: &mut JSContext,
4181    object: HandleObject,
4182    parameter: &std::ffi::CStr,
4183) -> Fallible<Option<Vec<u8>>> {
4184    let buffer_source = get_property::<ArrayBufferViewOrArrayBuffer>(cx, object, parameter, ())?;
4185    Ok(buffer_source
4186        .as_ref()
4187        .map(|buffer| get_buffer_source_copy(buffer.into())))
4188}
4189
4190/// Helper to retrieve a required paramter in BufferSource from WebIDL dictionary, and get a copy
4191/// of the bytes held by the buffer source according to
4192/// <https://webidl.spec.whatwg.org/#dfn-get-buffer-source-copy>
4193fn get_required_buffer_source(
4194    cx: &mut JSContext,
4195    object: HandleObject,
4196    parameter: &std::ffi::CStr,
4197) -> Fallible<Vec<u8>> {
4198    get_optional_buffer_source(cx, object, parameter)?
4199        .ok_or(Error::Type(c"Missing required parameter".into()))
4200}
4201
4202/// The returned type of the successful export key operation. `Bytes` should be used when the key
4203/// is exported in "raw", "spki" or "pkcs8" format. `Jwk` should be used when the key is exported
4204/// in "jwk" format.
4205enum ExportedKey {
4206    Bytes(Zeroizing<Vec<u8>>),
4207    Jwk(Box<JsonWebKey>),
4208}
4209
4210impl ExportedKey {
4211    fn new_bytes(bytes: Vec<u8>) -> ExportedKey {
4212        ExportedKey::Bytes(Zeroizing::new(bytes))
4213    }
4214
4215    fn new_jwk(jwk: JsonWebKey) -> ExportedKey {
4216        ExportedKey::Jwk(Box::new(jwk))
4217    }
4218}
4219
4220/// Given a byte sequence containing a bit sequence, truncate the bit sequence, keeping the first
4221/// `length` bits.
4222///
4223/// If `length` is greater or equal to `bit_sequqnce.len() * 8`, this function has no effect.
4224fn truncate_bit_sequence(bit_sequence: &mut Vec<u8>, length: usize) {
4225    bit_sequence.truncate(length.div_ceil(8));
4226
4227    // Set the excess bits in the last byte to zero.
4228    if length < bit_sequence.len() * 8 &&
4229        let Some(last_byte) = bit_sequence.last_mut()
4230    {
4231        *last_byte &= u8::MAX << (8 - length % 8);
4232    }
4233}
4234
4235/// Given a Keccak encoding of a bit string, truncate the bit string, keeping the first `length`
4236/// bits.
4237///
4238/// If `length` is greater or equal to `bit_string.len() * 8`, this function has no effect.
4239fn truncate_keccak_bit_string(bit_string: &mut Vec<u8>, length: usize) {
4240    bit_string.truncate(length.div_ceil(8));
4241
4242    // Set the excess bits in the last byte to zero.
4243    if length < bit_string.len() * 8 &&
4244        let Some(last_byte) = bit_string.last_mut()
4245    {
4246        *last_byte &= u8::MAX >> (8 - length % 8);
4247    }
4248}
4249
4250/// Union type of KeyAlgorithm and IDL dictionary types derived from it. Note that we actually use
4251/// our "subtle" structs of the corresponding IDL dictionary types so that they can be easily
4252/// passed to another threads.
4253#[derive(Clone, MallocSizeOf)]
4254#[expect(clippy::enum_variant_names)]
4255pub(crate) enum KeyAlgorithmAndDerivatives {
4256    KeyAlgorithm(KeyAlgorithm),
4257    RsaHashedKeyAlgorithm(RsaHashedKeyAlgorithm),
4258    EcKeyAlgorithm(EcKeyAlgorithm),
4259    AesKeyAlgorithm(AesKeyAlgorithm),
4260    HmacKeyAlgorithm(HmacKeyAlgorithm),
4261    KmacKeyAlgorithm(KmacKeyAlgorithm),
4262}
4263
4264impl KeyAlgorithmAndDerivatives {
4265    fn name(&self) -> CryptoAlgorithm {
4266        match self {
4267            KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm) => algorithm.name,
4268            KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm) => algorithm.name,
4269            KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) => algorithm.name,
4270            KeyAlgorithmAndDerivatives::AesKeyAlgorithm(algorithm) => algorithm.name,
4271            KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm) => algorithm.name,
4272            KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm) => algorithm.name,
4273        }
4274    }
4275}
4276
4277impl ToJSValConvertible for KeyAlgorithmAndDerivatives {
4278    fn to_jsval(&self, cx: &mut JSContext, rval: MutableHandleValue) {
4279        match self {
4280            KeyAlgorithmAndDerivatives::KeyAlgorithm(algo) => algo.to_jsval(cx, rval),
4281            KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algo) => algo.to_jsval(cx, rval),
4282            KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algo) => algo.to_jsval(cx, rval),
4283            KeyAlgorithmAndDerivatives::AesKeyAlgorithm(algo) => algo.to_jsval(cx, rval),
4284            KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algo) => algo.to_jsval(cx, rval),
4285            KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algo) => algo.to_jsval(cx, rval),
4286        }
4287    }
4288}
4289
4290impl TryFrom<SerializableKeyAlgorithmAndDerivatives> for KeyAlgorithmAndDerivatives {
4291    type Error = ();
4292
4293    fn try_from(value: SerializableKeyAlgorithmAndDerivatives) -> Result<Self, Self::Error> {
4294        match value {
4295            SerializableKeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm) => Ok(
4296                KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm.try_into()?),
4297            ),
4298            SerializableKeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm) => Ok(
4299                KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm.try_into()?),
4300            ),
4301            SerializableKeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) => Ok(
4302                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm.try_into()?),
4303            ),
4304            SerializableKeyAlgorithmAndDerivatives::AesKeyAlgorithm(algorithm) => Ok(
4305                KeyAlgorithmAndDerivatives::AesKeyAlgorithm(algorithm.try_into()?),
4306            ),
4307            SerializableKeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm) => Ok(
4308                KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm.try_into()?),
4309            ),
4310            SerializableKeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm) => Ok(
4311                KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm.try_into()?),
4312            ),
4313        }
4314    }
4315}
4316
4317impl From<&KeyAlgorithmAndDerivatives> for SerializableKeyAlgorithmAndDerivatives {
4318    fn from(value: &KeyAlgorithmAndDerivatives) -> Self {
4319        match value {
4320            KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm) => {
4321                SerializableKeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm.into())
4322            },
4323            KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm) => {
4324                SerializableKeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm.into())
4325            },
4326            KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) => {
4327                SerializableKeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm.into())
4328            },
4329            KeyAlgorithmAndDerivatives::AesKeyAlgorithm(algorithm) => {
4330                SerializableKeyAlgorithmAndDerivatives::AesKeyAlgorithm(algorithm.into())
4331            },
4332            KeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm) => {
4333                SerializableKeyAlgorithmAndDerivatives::HmacKeyAlgorithm(algorithm.into())
4334            },
4335            KeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm) => {
4336                SerializableKeyAlgorithmAndDerivatives::KmacKeyAlgorithm(algorithm.into())
4337            },
4338        }
4339    }
4340}
4341
4342/// [`JsonWebKey`] fields that are [`DOMString`].
4343#[derive(Clone, Copy)]
4344enum JwkStringField {
4345    X,
4346    Y,
4347    D,
4348    N,
4349    E,
4350    P,
4351    Q,
4352    DP,
4353    DQ,
4354    QI,
4355    K,
4356    Priv,
4357    Pub,
4358}
4359
4360impl Display for JwkStringField {
4361    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4362        let field_name = match self {
4363            JwkStringField::X => "x",
4364            JwkStringField::Y => "y",
4365            JwkStringField::D => "d",
4366            JwkStringField::N => "n",
4367            JwkStringField::E => "e",
4368            JwkStringField::P => "q",
4369            JwkStringField::Q => "q",
4370            JwkStringField::DP => "dp",
4371            JwkStringField::DQ => "dq",
4372            JwkStringField::QI => "qi",
4373            JwkStringField::K => "k",
4374            JwkStringField::Priv => "priv",
4375            JwkStringField::Pub => "pub",
4376        };
4377        write!(f, "{}", field_name)
4378    }
4379}
4380
4381/// Helper functions for [`JsonWebKey`].
4382trait JsonWebKeyHelper {
4383    /// <https://w3c.github.io/webcrypto/#concept-parse-a-jwk>
4384    fn parse(cx: &mut JSContext, data: &[u8]) -> Result<JsonWebKey, Error>;
4385
4386    /// Convert a JsonWebKey value to DOMString. We first convert the JsonWebKey value to
4387    /// JavaScript value, and then serialize it by performing steps in
4388    /// <https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string>. This acts
4389    /// like the opposite of JsonWebKey::parse if you further convert the stringified result to
4390    /// bytes.
4391    fn stringify(&self, cx: &mut JSContext) -> Result<Zeroizing<DOMString>, Error>;
4392
4393    /// Get key usages from "key_ops" JWK members.
4394    fn get_usages_from_key_ops(&self) -> Result<Vec<KeyUsage>, Error>;
4395
4396    /// If the key_ops field of jwk is present, and is invalid according to the requirements of
4397    /// JSON Web Key (JWK) or does not contain all of the specified usages values, then throw a
4398    /// `DataError`.
4399    fn check_key_ops(&self, specified_usages: &[KeyUsage]) -> Result<(), Error>;
4400
4401    /// Set the key_ops attribute of jwk to equal the given usages.
4402    fn set_key_ops(&mut self, usages: &[KeyUsage]);
4403
4404    /// Encode a byte sequence to a Base64URL-encoded string, and set the field to the encoded
4405    /// string.
4406    fn encode_string_field(&mut self, field: JwkStringField, data: &[u8]);
4407
4408    /// Decode a field from a Base64URL-encoded string to a byte sequence. If the field is not a
4409    /// valid base64url-encoded string, then throw a `DataError`.
4410    fn decode_optional_string_field(
4411        &self,
4412        field: JwkStringField,
4413    ) -> Result<Option<Zeroizing<Vec<u8>>>, Error>;
4414
4415    /// Decode a field from a Base64URL-encoded string to a byte sequence. If the field is not
4416    /// present or it is not a valid Base64URL-encoded string, then throw a `DataError`.
4417    fn decode_required_string_field(
4418        &self,
4419        field: JwkStringField,
4420    ) -> Result<Zeroizing<Vec<u8>>, Error>;
4421
4422    /// Decode the "r", "d" and "t" field of each entry in the "oth" array, from a Base64URL-encoded
4423    /// string to a byte sequence, and append the decoded "r" field to the `primes` list, in the
4424    /// order of presence in the "oth" array.
4425    ///
4426    /// If the "oth" field is present and any of the "p", "q", "dp", "dq" or "qi" field is not
4427    /// present, then throw a `DataError`. For each entry in the "oth" array, if any of the "r", "d"
4428    /// and "t" field is not present or it is not a valid Base64URL-encoded string, then throw a
4429    /// `DataError`.
4430    fn decode_primes_from_oth_field(
4431        &self,
4432        primes: &mut Vec<Zeroizing<Vec<u8>>>,
4433    ) -> Result<(), Error>;
4434}
4435
4436impl JsonWebKeyHelper for JsonWebKey {
4437    /// <https://w3c.github.io/webcrypto/#concept-parse-a-jwk>
4438    #[expect(unsafe_code)]
4439    fn parse(cx: &mut JSContext, data: &[u8]) -> Result<JsonWebKey, Error> {
4440        // Step 1. Let data be the sequence of bytes to be parsed.
4441        // (It is given as a method paramter.)
4442
4443        // Step 2. Let json be the Unicode string that results from interpreting data according to UTF-8.
4444        let json = String::from_utf8_lossy(data);
4445
4446        // Step 3. Convert json to UTF-16.
4447        let json: Vec<_> = json.encode_utf16().collect();
4448
4449        // Step 4. Let result be the object literal that results from executing the JSON.parse
4450        // internal function in the context of a new global object, with text argument set to a
4451        // JavaScript String containing json.
4452        rooted!(&in(cx) let mut result = UndefinedValue());
4453        unsafe {
4454            if !JS_ParseJSON(cx, json.as_ptr(), json.len() as u32, result.handle_mut()) {
4455                return Err(Error::JSFailed);
4456            }
4457        }
4458
4459        // Step 5. Let key be the result of converting result to the IDL dictionary type of JsonWebKey.
4460        let key = match JsonWebKey::new(cx, result.handle()) {
4461            Ok(ConversionResult::Success(key)) => key,
4462            Ok(ConversionResult::Failure(error)) => {
4463                return Err(Error::Type(error.into_owned()));
4464            },
4465            Err(()) => {
4466                return Err(Error::JSFailed);
4467            },
4468        };
4469
4470        // Step 6. If the kty field of key is not defined, then throw a DataError.
4471        if key.kty.is_none() {
4472            return Err(Error::Data(Some(
4473                "'kty' field of key is not defined".into(),
4474            )));
4475        }
4476
4477        // Step 7. Result key.
4478        Ok(key)
4479    }
4480
4481    fn stringify(&self, cx: &mut JSContext) -> Result<Zeroizing<DOMString>, Error> {
4482        rooted!(&in(cx) let mut data = UndefinedValue());
4483        self.to_jsval(cx, data.handle_mut());
4484        serialize_jsval_to_json_utf8(cx, data.handle()).map(Zeroizing::new)
4485    }
4486
4487    fn get_usages_from_key_ops(&self) -> Result<Vec<KeyUsage>, Error> {
4488        let mut usages = vec![];
4489        for op in self.key_ops.as_ref().ok_or(Error::Data(Some(
4490            "'key_ops' member is not present in the JSON Web Key".into(),
4491        )))? {
4492            usages.push(
4493                KeyUsage::from_str(&op.str())
4494                    .map_err(|_| Error::Data(Some("Unknown key usage".into())))?,
4495            );
4496        }
4497        Ok(usages)
4498    }
4499
4500    fn check_key_ops(&self, specified_usages: &[KeyUsage]) -> Result<(), Error> {
4501        // If the key_ops field of jwk is present,
4502        if let Some(ref key_ops) = self.key_ops {
4503            // and is invalid according to the requirements of JSON Web Key [JWK]:
4504            //
4505            // <https://www.rfc-editor.org/info/rfc7517/#section-4.3>
4506            // 1. Duplicate key operation values MUST NOT be present in the array.
4507            if key_ops.iter().collect::<HashSet<_>>().len() < key_ops.len() {
4508                return Err(Error::Data(Some(
4509                    "Duplicate key operation values are present in array".into(),
4510                )));
4511            }
4512            // 2. The "use" and "key_ops" JWK members SHOULD NOT be used together; however, if both
4513            //    are used, the information they convey MUST be consistent.
4514            if let Some(ref use_) = self.use_ &&
4515                key_ops.iter().any(|op| op != use_)
4516            {
4517                return Err(Error::Data(Some(
4518                    "Key operations are not consistent with intended use for Json Web Key".into(),
4519                )));
4520            }
4521
4522            // or does not contain all of the specified usages values
4523            let key_ops_as_usages = self.get_usages_from_key_ops()?;
4524            if !specified_usages
4525                .iter()
4526                .all(|specified_usage| key_ops_as_usages.contains(specified_usage))
4527            {
4528                return Err(Error::Data(Some(
4529                    "Key operations do not contain all of the specified usage values".into(),
4530                )));
4531            }
4532        }
4533
4534        Ok(())
4535    }
4536
4537    fn set_key_ops(&mut self, usages: &[KeyUsage]) {
4538        self.key_ops = Some(
4539            usages
4540                .iter()
4541                .map(|usage| DOMString::from(usage.as_str()))
4542                .collect(),
4543        );
4544    }
4545
4546    fn encode_string_field(&mut self, field: JwkStringField, data: &[u8]) {
4547        let encoded_data = DOMString::from(Base64UrlUnpadded::encode_string(data));
4548        match field {
4549            JwkStringField::X => self.x = Some(encoded_data),
4550            JwkStringField::Y => self.y = Some(encoded_data),
4551            JwkStringField::D => self.d = Some(encoded_data),
4552            JwkStringField::N => self.n = Some(encoded_data),
4553            JwkStringField::E => self.e = Some(encoded_data),
4554            JwkStringField::P => self.p = Some(encoded_data),
4555            JwkStringField::Q => self.q = Some(encoded_data),
4556            JwkStringField::DP => self.dp = Some(encoded_data),
4557            JwkStringField::DQ => self.dq = Some(encoded_data),
4558            JwkStringField::QI => self.qi = Some(encoded_data),
4559            JwkStringField::K => self.k = Some(encoded_data),
4560            JwkStringField::Priv => self.priv_ = Some(encoded_data),
4561            JwkStringField::Pub => self.pub_ = Some(encoded_data),
4562        }
4563    }
4564
4565    fn decode_optional_string_field(
4566        &self,
4567        field: JwkStringField,
4568    ) -> Result<Option<Zeroizing<Vec<u8>>>, Error> {
4569        let field_string = match field {
4570            JwkStringField::X => &self.x,
4571            JwkStringField::Y => &self.y,
4572            JwkStringField::D => &self.d,
4573            JwkStringField::N => &self.n,
4574            JwkStringField::E => &self.e,
4575            JwkStringField::P => &self.p,
4576            JwkStringField::Q => &self.q,
4577            JwkStringField::DP => &self.dp,
4578            JwkStringField::DQ => &self.dq,
4579            JwkStringField::QI => &self.qi,
4580            JwkStringField::K => &self.k,
4581            JwkStringField::Priv => &self.priv_,
4582            JwkStringField::Pub => &self.pub_,
4583        };
4584
4585        field_string
4586            .as_ref()
4587            .map(|field_string| {
4588                Base64UrlUnpadded::decode_vec(&field_string.str()).map(Zeroizing::new)
4589            })
4590            .transpose()
4591            .map_err(|_| Error::Data(Some(format!("Failed to decode {} field in jwk", field))))
4592    }
4593
4594    fn decode_required_string_field(
4595        &self,
4596        field: JwkStringField,
4597    ) -> Result<Zeroizing<Vec<u8>>, Error> {
4598        self.decode_optional_string_field(field)?
4599            .ok_or(Error::Data(Some(format!(
4600                "The {} field is not present in jwk",
4601                field
4602            ))))
4603    }
4604
4605    fn decode_primes_from_oth_field(
4606        &self,
4607        primes: &mut Vec<Zeroizing<Vec<u8>>>,
4608    ) -> Result<(), Error> {
4609        if self.oth.is_some() &&
4610            (self.p.is_none() ||
4611                self.q.is_none() ||
4612                self.dp.is_none() ||
4613                self.dq.is_none() ||
4614                self.qi.is_none())
4615        {
4616            return Err(Error::Data(Some(
4617                "The oth field is present while at least one of p, q, dp, dq, qi is missing".into(),
4618            )));
4619        }
4620
4621        for rsa_other_prime_info in self.oth.as_ref().unwrap_or(&Vec::new()) {
4622            let r = Base64UrlUnpadded::decode_vec(
4623                &rsa_other_prime_info
4624                    .r
4625                    .as_ref()
4626                    .ok_or(Error::Data(Some(
4627                        "The r field is not present in one of the entry of oth field in jwk".into(),
4628                    )))?
4629                    .str(),
4630            )
4631            .map_err(|_| {
4632                Error::Data(Some(
4633                    "Fail to decode r field in one of the entry of oth field in jwk".into(),
4634                ))
4635            })?;
4636            primes.push(Zeroizing::new(r));
4637
4638            let _d = Base64UrlUnpadded::decode_vec(
4639                &rsa_other_prime_info
4640                    .d
4641                    .as_ref()
4642                    .ok_or(Error::Data(Some(
4643                        "The d field is not present in one of the entry of oth field in jwk".into(),
4644                    )))?
4645                    .str(),
4646            )
4647            .map_err(|_| {
4648                Error::Data(Some(
4649                    "Fail to decode d field in one of the entry of oth field in jwk".into(),
4650                ))
4651            })?;
4652
4653            let _t = Base64UrlUnpadded::decode_vec(
4654                &rsa_other_prime_info
4655                    .t
4656                    .as_ref()
4657                    .ok_or(Error::Data(Some(
4658                        "The t field is not present in one of the entry of oth field in jwk".into(),
4659                    )))?
4660                    .str(),
4661            )
4662            .map_err(|_| {
4663                Error::Data(Some(
4664                    "Fail to decode t field in one of the entry of oth field in jwk".into(),
4665                ))
4666            })?;
4667        }
4668
4669        Ok(())
4670    }
4671}
4672
4673/// <https://w3c.github.io/webcrypto/#algorithm-normalization-normalize-an-algorithm>
4674fn normalize_algorithm<Op: Operation>(
4675    cx: &mut JSContext,
4676    algorithm: &AlgorithmIdentifier,
4677) -> Result<Op::RegisteredAlgorithm, Error> {
4678    match algorithm {
4679        // If alg is an instance of a DOMString:
4680        AlgorithmIdentifier::String(name) => {
4681            // Return the result of running the normalize an algorithm algorithm, with the alg set
4682            // to a new Algorithm dictionary whose name attribute is alg, and with the op set to
4683            // op.
4684            //
4685            // NOTE: We use the Algorithm dictionary generated by script_bindings since the
4686            // WebCrypto custom binding struct does not accept unnormalized name in its name member.
4687            let algorithm = AlgorithmWithDOMString {
4688                name: name.to_owned(),
4689            };
4690            rooted!(&in(cx) let mut algorithm_value = UndefinedValue());
4691            algorithm.to_jsval(cx, algorithm_value.handle_mut());
4692            let algorithm_object = RootedTraceableBox::new(Heap::default());
4693            algorithm_object.set(algorithm_value.to_object());
4694            normalize_algorithm::<Op>(cx, &AlgorithmIdentifier::Object(algorithm_object))
4695        },
4696        // If alg is an object:
4697        AlgorithmIdentifier::Object(object) => {
4698            // Step 1. Let registeredAlgorithms be the associative container stored at the op key
4699            // of supportedAlgorithms.
4700
4701            // Stpe 2. Let initialAlg be the result of converting the ECMAScript object represented
4702            // by alg to the IDL dictionary type Algorithm, as defined by [WebIDL].
4703            // Step 3. If an error occurred, return the error and terminate this algorithm.
4704            // Step 4. Let algName be the value of the name attribute of initialAlg.
4705            let algorithm_name = get_required_parameter::<DOMString>(
4706                cx,
4707                object.handle(),
4708                c"name",
4709                StringificationBehavior::Default,
4710            )?;
4711
4712            // Step 5.
4713            //     If registeredAlgorithms contains a key that is a case-insensitive string match
4714            //     for algName:
4715            //         Step 5.1. Set algName to the value of the matching key.
4716            //         Step 5.2. Let desiredType be the IDL dictionary type stored at algName in
4717            //         registeredAlgorithms.
4718            //     Otherwise:
4719            //         Return a new NotSupportedError and terminate this algorithm.
4720            // Step 6. Let normalizedAlgorithm be the result of converting the ECMAScript object
4721            // represented by alg to the IDL dictionary type desiredType, as defined by [WebIDL].
4722            // Step 7. Set the name attribute of normalizedAlgorithm to algName.
4723            // Step 8. If an error occurred, return the error and terminate this algorithm.
4724            // Step 9. Let dictionaries be a list consisting of the IDL dictionary type desiredType
4725            // and all of desiredType's inherited dictionaries, in order from least to most
4726            // derived.
4727            // Step 10. For each dictionary dictionary in dictionaries:
4728            //     Step 10.1. For each dictionary member member declared on dictionary, in order:
4729            //         Step 10.1.1. Let key be the identifier of member.
4730            //         Step 10.1.2. Let idlValue be the value of the dictionary member with key
4731            //         name of key on normalizedAlgorithm.
4732            //         Step 10.1.3.
4733            //             If member is of the type BufferSource and is present:
4734            //                 Set the dictionary member on normalizedAlgorithm with key name key
4735            //                 to the result of getting a copy of the bytes held by idlValue,
4736            //                 replacing the current value.
4737            //             If member is of the type HashAlgorithmIdentifier:
4738            //                 Set the dictionary member on normalizedAlgorithm with key name key
4739            //                 to the result of normalizing an algorithm, with the alg set to
4740            //                 idlValue and the op set to "digest".
4741            //             If member is of the type AlgorithmIdentifier:
4742            //                 Set the dictionary member on normalizedAlgorithm with key name key
4743            //                 to the result of normalizing an algorithm, with the alg set to
4744            //                 idlValue and the op set to the operation defined by the
4745            //                 specification that defines the algorithm identified by algName.
4746            //
4747            // NOTE:
4748            // - The desiredTypes in Step 5.2 are determined by the inner type of
4749            //   `Op::RegisteredAlgorithm`.
4750            // - Step 9 and 10 are done by the calling `try_into_with_cx_and_name` within the trait
4751            //   implementation of `Op::RegisteredAlgorithm::from_object`.
4752            let algorithm_name = CryptoAlgorithm::from_str_ignore_case(&algorithm_name.str())?;
4753            let normalized_algorithm =
4754                Op::RegisteredAlgorithm::from_object(cx, algorithm_name, object.handle())?;
4755
4756            // Step 11. Return normalizedAlgorithm.
4757            Ok(normalized_algorithm)
4758        },
4759    }
4760}
4761
4762// <https://w3c.github.io/webcrypto/#dfn-supportedAlgorithms>
4763//
4764// We implement the internal object
4765// [supportedAlgorithms](https://w3c.github.io/webcrypto/#dfn-supportedAlgorithms) for algorithm
4766// registration, in the following way.
4767//
4768// For each operation v in the list of [supported
4769// operations](https://w3c.github.io/webcrypto/#supported-operation), we define a struct to
4770// represent it, which acts a key of the internal object supportedAlgorithms.
4771//
4772// We then implement the [`Operation`] trait for these structs. When implementing the trait for
4773// each of these structs, we set the associated type [`RegisteredAlgorithm`] of [`Operation`] to an
4774// enum as the value of the operation v in supportedAlgorithms. The enum lists all algorithhms
4775// supporting the operation v as its variants.
4776//
4777// To [define an algorithm](https://w3c.github.io/webcrypto/#concept-define-an-algorithm), each
4778// variant in the enum has an inner type corresponding to the desired input IDL dictionary type for
4779// the supported algorithm represented by the variant. Moreover, the enum also need to implement
4780// the [`NormalizedAlgorithm`] trait since it is used as the output of
4781// [`normalize_algorithm`].
4782//
4783// For example, we define the [`EncryptOperation`] struct to represent the "encrypt" operation, and
4784// implement the [`Operation`] trait for it. The associated type [`RegisteredAlgorithm`] of
4785// [`Operation`]  is set to the [`EncryptAlgorithm`] enum, whose variants are cryptographic
4786// algorithms that support the "encrypt" operation. The variant [`EncryptAlgorithm::AesCtr`] has an
4787// inner type [`AesCtrParams`] since the desired input IDL dictionary type for "encrypt" operation
4788// of AES-CTR algorithm is the `AesCtrParams` dictionary. The [`EncryptAlgorithm`] enum also
4789// implements the [`NormalizedAlgorithm`] trait accordingly.
4790//
4791// The algorithm registrations are specified in:
4792// RSASSA-PKCS1-v1_5: <https://w3c.github.io/webcrypto/#rsassa-pkcs1-registration>
4793// RSA-PSS:           <https://w3c.github.io/webcrypto/#rsa-pss-registration>
4794// RSA-OAEP:          <https://w3c.github.io/webcrypto/#rsa-oaep-registration>
4795// ECDSA:             <https://w3c.github.io/webcrypto/#ecdsa-registration>
4796// ECDH:              <https://w3c.github.io/webcrypto/#ecdh-registration>
4797// Ed25519:           <https://w3c.github.io/webcrypto/#ed25519-registration>
4798// X25519:            <https://w3c.github.io/webcrypto/#x25519-registration>
4799// Ed448:             <https://wicg.github.io/webcrypto-secure-curves/#ed448-registration>
4800// X448:              <https://wicg.github.io/webcrypto-secure-curves/#x448-registration>
4801// AES-CTR:           <https://w3c.github.io/webcrypto/#aes-ctr-registration>
4802// AES-CBC:           <https://w3c.github.io/webcrypto/#aes-cbc-registration>
4803// AES-GCM:           <https://w3c.github.io/webcrypto/#aes-gcm-registration>
4804// AES-KW:            <https://w3c.github.io/webcrypto/#aes-kw-registration>
4805// HMAC:              <https://w3c.github.io/webcrypto/#hmac-registration>
4806// SHA:               <https://w3c.github.io/webcrypto/#sha-registration>
4807// HKDF:              <https://w3c.github.io/webcrypto/#hkdf-registration>
4808// PBKDF2:            <https://w3c.github.io/webcrypto/#pbkdf2-registration>
4809// ML-KEM:            <https://wicg.github.io/webcrypto-modern-algos/#ml-kem-registration>
4810// ML-DSA:            <https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-registration>
4811// AES-OCB:           <https://wicg.github.io/webcrypto-modern-algos/#aes-ocb-registration>
4812// ChaCha20-Poly1305: <https://wicg.github.io/webcrypto-modern-algos/#chacha20-poly1305-registration>
4813// SHA-3:             <https://wicg.github.io/webcrypto-modern-algos/#sha3-registration>
4814// cSHAKE:            <https://wicg.github.io/webcrypto-modern-algos/#cshake-registration>
4815// TurboSHAKE:        <https://wicg.github.io/webcrypto-modern-algos/#turboshake-registration>
4816// KangarooTwelve:    <https://wicg.github.io/webcrypto-modern-algos/#kangarootwelve-registration>
4817// KMAC:              <https://wicg.github.io/webcrypto-modern-algos/#kmac-registration>
4818// Argon2:            <https://wicg.github.io/webcrypto-modern-algos/#argon2-registration>
4819
4820trait Operation {
4821    type RegisteredAlgorithm: NormalizedAlgorithm;
4822}
4823
4824trait NormalizedAlgorithm: Sized {
4825    /// Step 4 - 10 of <https://w3c.github.io/webcrypto/#algorithm-normalization-normalize-an-algorithm>
4826    fn from_object(
4827        cx: &mut JSContext,
4828        algorithm_name: CryptoAlgorithm,
4829        object: HandleObject,
4830    ) -> Fallible<Self>;
4831
4832    /// Return the name of the normalized algorithm.
4833    fn name(&self) -> CryptoAlgorithm;
4834
4835    /// <https://wicg.github.io/webcrypto-modern-algos/#dfn-determine-support-from-operation-steps>
4836    ///
4837    /// The default implemenation is to return false, as placeholder. The actual implementation
4838    /// depends on the operation represented by the trait implementor.
4839    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
4840        // Step 1. If the specified operation or algorithm (or one of its parameter values) is
4841        // expected to fail (for any key and/or data) for an implementation-specific reason (e.g.
4842        // known nonconformance to the specification), return false.
4843        // Step 2. If op is "generateKey" or "importKey", let usages be the empty list.
4844        // Step 3. For each of the steps of the operation specified by op of the algorithm specified
4845        // by normalizedAlgorithm:
4846        //     If the step says to throw an error:
4847        //         Return false.
4848        //     If the step says to generate a key:
4849        //         Return true.
4850        //     If the step relies on an unavailable parameter, such as key, plaintext or ciphertext:
4851        //         Return true.
4852        //     If the step says to return a value:
4853        //         Return true.
4854        //     Otherwise:
4855        //         Execute the step.
4856        // Step 4. Assert: this step is never reached, because one of the steps of the operation
4857        // will have said to return a value or throw an error, causing us to return true or false,
4858        // respectively.
4859        //
4860        // NOTE:
4861        // - Step 3 can be interpreted as executing the specified operation of the specified
4862        //   algorithm in "dry-run" mode in which it validates the normalizedAlgorithm, length and
4863        //   usages but does not execute the computation-demanding cryptographic calculation.
4864        //
4865        // - Usually, the parameter validations are executed at the beginning of the operation.
4866        //   Therefore, Step 3 can be done by running the operation with the following changes:
4867        //   - Replace "throw an DataError/OperationError/NotSupportedError" with "return false".
4868        //   - When we reach any step that requires unavailable parameters or does the cryptographic
4869        //     calculation, return true, instead of running the step, and skip the remaining steps
4870        //     as well.
4871        //
4872        // - Since usages is an empty list, it should pass the validation described in the specified
4873        //   operation of the specified algorithm. So, we simply ignore it here.
4874        //
4875        // - The implementer of this trait is expected to be an `enum` listing possible
4876        //   cryptographic algorithms. In the implementation of this trait, recommend writing a
4877        //   `match` block on `self` that explicitly lists all patterns so that the Rust compiler
4878        //   can remind you to add the necessary parameter validation here when a new operation of
4879        //   an algorithm is added.
4880        debug_assert!(
4881            false,
4882            "determine_support_from_operation_steps() is not implemented \
4883                for this normalized algorithm."
4884        );
4885        false
4886    }
4887}
4888
4889/// The value of the key "encrypt" in the internal object supportedAlgorithms
4890struct EncryptOperation {}
4891
4892impl Operation for EncryptOperation {
4893    type RegisteredAlgorithm = EncryptAlgorithm;
4894}
4895
4896/// Normalized algorithm for the "encrypt" operation, used as output of
4897/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
4898enum EncryptAlgorithm {
4899    RsaOaep(RsaOaepParams),
4900    AesCtr(AesCtrParams),
4901    AesCbc(AesCbcParams),
4902    AesGcm(AesGcmParams),
4903    AesOcb(AeadParams),
4904    ChaCha20Poly1305(AeadParams),
4905}
4906
4907impl NormalizedAlgorithm for EncryptAlgorithm {
4908    fn from_object(
4909        cx: &mut JSContext,
4910        algorithm_name: CryptoAlgorithm,
4911        object: HandleObject,
4912    ) -> Fallible<Self> {
4913        match algorithm_name {
4914            CryptoAlgorithm::RsaOaep => Ok(EncryptAlgorithm::RsaOaep(
4915                object.try_into_with_cx_and_name(cx, algorithm_name)?,
4916            )),
4917            CryptoAlgorithm::AesCtr => Ok(EncryptAlgorithm::AesCtr(
4918                object.try_into_with_cx_and_name(cx, algorithm_name)?,
4919            )),
4920            CryptoAlgorithm::AesCbc => Ok(EncryptAlgorithm::AesCbc(
4921                object.try_into_with_cx_and_name(cx, algorithm_name)?,
4922            )),
4923            CryptoAlgorithm::AesGcm => Ok(EncryptAlgorithm::AesGcm(
4924                object.try_into_with_cx_and_name(cx, algorithm_name)?,
4925            )),
4926            CryptoAlgorithm::AesOcb => Ok(EncryptAlgorithm::AesOcb(
4927                object.try_into_with_cx_and_name(cx, algorithm_name)?,
4928            )),
4929            CryptoAlgorithm::ChaCha20Poly1305 => Ok(EncryptAlgorithm::ChaCha20Poly1305(
4930                object.try_into_with_cx_and_name(cx, algorithm_name)?,
4931            )),
4932            _ => Err(Error::NotSupported(Some(format!(
4933                "{} does not support \"encrypt\" operation",
4934                algorithm_name.as_str()
4935            )))),
4936        }
4937    }
4938
4939    fn name(&self) -> CryptoAlgorithm {
4940        match self {
4941            EncryptAlgorithm::RsaOaep(algorithm) => algorithm.name,
4942            EncryptAlgorithm::AesCtr(algorithm) => algorithm.name,
4943            EncryptAlgorithm::AesCbc(algorithm) => algorithm.name,
4944            EncryptAlgorithm::AesGcm(algorithm) => algorithm.name,
4945            EncryptAlgorithm::AesOcb(algorithm) => algorithm.name,
4946            EncryptAlgorithm::ChaCha20Poly1305(algorithm) => algorithm.name,
4947        }
4948    }
4949
4950    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
4951        match self {
4952            EncryptAlgorithm::RsaOaep(_) => true,
4953            EncryptAlgorithm::AesCtr(normalized_algorithm) => {
4954                normalized_algorithm.counter.len() == 16 &&
4955                    normalized_algorithm.length != 0 &&
4956                    normalized_algorithm.length <= 128
4957            },
4958            EncryptAlgorithm::AesCbc(normalized_algorithm) => normalized_algorithm.iv.len() == 16,
4959            EncryptAlgorithm::AesGcm(normalized_algorithm) => {
4960                normalized_algorithm.iv.len() <= u64::MAX as usize &&
4961                    normalized_algorithm
4962                        .additional_data
4963                        .as_ref()
4964                        .is_none_or(|additional_data| additional_data.len() <= u64::MAX as usize) &&
4965                    normalized_algorithm.tag_length.is_none_or(|length| {
4966                        matches!(length, 32 | 64 | 96 | 104 | 112 | 120 | 128)
4967                    })
4968            },
4969            EncryptAlgorithm::AesOcb(normalized_algorithm) => {
4970                normalized_algorithm.iv.len() <= 15 &&
4971                    normalized_algorithm
4972                        .tag_length
4973                        .is_none_or(|length| matches!(length, 64 | 96 | 128))
4974            },
4975            EncryptAlgorithm::ChaCha20Poly1305(normalized_algorithm) => {
4976                normalized_algorithm.iv.len() == 12 &&
4977                    normalized_algorithm
4978                        .tag_length
4979                        .is_none_or(|length| length == 128)
4980            },
4981        }
4982    }
4983}
4984
4985impl EncryptAlgorithm {
4986    fn encrypt<D: Equivalence>(
4987        &self,
4988        key: &CryptoKey<D>,
4989        plaintext: &[u8],
4990    ) -> Result<Vec<u8>, Error> {
4991        match self {
4992            EncryptAlgorithm::RsaOaep(algorithm) => {
4993                rsa_oaep_operation::encrypt(algorithm, key, plaintext)
4994            },
4995            EncryptAlgorithm::AesCtr(algorithm) => {
4996                aes_ctr_operation::encrypt(algorithm, key, plaintext)
4997            },
4998            EncryptAlgorithm::AesCbc(algorithm) => {
4999                aes_cbc_operation::encrypt(algorithm, key, plaintext)
5000            },
5001            EncryptAlgorithm::AesGcm(algorithm) => {
5002                aes_gcm_operation::encrypt(algorithm, key, plaintext)
5003            },
5004            EncryptAlgorithm::AesOcb(algorithm) => {
5005                aes_ocb_operation::encrypt(algorithm, key, plaintext)
5006            },
5007            EncryptAlgorithm::ChaCha20Poly1305(algorithm) => {
5008                chacha20_poly1305_operation::encrypt(algorithm, key, plaintext)
5009            },
5010        }
5011    }
5012}
5013
5014/// The value of the key "decrypt" in the internal object supportedAlgorithms
5015struct DecryptOperation {}
5016
5017impl Operation for DecryptOperation {
5018    type RegisteredAlgorithm = DecryptAlgorithm;
5019}
5020
5021/// Normalized algorithm for the "decrypt" operation, used as output of
5022/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
5023enum DecryptAlgorithm {
5024    RsaOaep(RsaOaepParams),
5025    AesCtr(AesCtrParams),
5026    AesCbc(AesCbcParams),
5027    AesGcm(AesGcmParams),
5028    AesOcb(AeadParams),
5029    ChaCha20Poly1305(AeadParams),
5030}
5031
5032impl NormalizedAlgorithm for DecryptAlgorithm {
5033    fn from_object(
5034        cx: &mut JSContext,
5035        algorithm_name: CryptoAlgorithm,
5036        object: HandleObject,
5037    ) -> Fallible<Self> {
5038        match algorithm_name {
5039            CryptoAlgorithm::RsaOaep => Ok(DecryptAlgorithm::RsaOaep(
5040                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5041            )),
5042            CryptoAlgorithm::AesCtr => Ok(DecryptAlgorithm::AesCtr(
5043                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5044            )),
5045            CryptoAlgorithm::AesCbc => Ok(DecryptAlgorithm::AesCbc(
5046                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5047            )),
5048            CryptoAlgorithm::AesGcm => Ok(DecryptAlgorithm::AesGcm(
5049                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5050            )),
5051            CryptoAlgorithm::AesOcb => Ok(DecryptAlgorithm::AesOcb(
5052                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5053            )),
5054            CryptoAlgorithm::ChaCha20Poly1305 => Ok(DecryptAlgorithm::ChaCha20Poly1305(
5055                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5056            )),
5057            _ => Err(Error::NotSupported(Some(format!(
5058                "{} does not support \"decrypt\" operation",
5059                algorithm_name.as_str()
5060            )))),
5061        }
5062    }
5063
5064    fn name(&self) -> CryptoAlgorithm {
5065        match self {
5066            DecryptAlgorithm::RsaOaep(algorithm) => algorithm.name,
5067            DecryptAlgorithm::AesCtr(algorithm) => algorithm.name,
5068            DecryptAlgorithm::AesCbc(algorithm) => algorithm.name,
5069            DecryptAlgorithm::AesGcm(algorithm) => algorithm.name,
5070            DecryptAlgorithm::AesOcb(algorithm) => algorithm.name,
5071            DecryptAlgorithm::ChaCha20Poly1305(algorithm) => algorithm.name,
5072        }
5073    }
5074
5075    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
5076        match self {
5077            DecryptAlgorithm::RsaOaep(_) => true,
5078            DecryptAlgorithm::AesCtr(normalized_algorithm) => {
5079                normalized_algorithm.counter.len() == 16 &&
5080                    normalized_algorithm.length != 0 &&
5081                    normalized_algorithm.length <= 128
5082            },
5083            DecryptAlgorithm::AesCbc(normalized_algorithm) => normalized_algorithm.iv.len() == 16,
5084            DecryptAlgorithm::AesGcm(normalized_algorithm) => {
5085                normalized_algorithm
5086                    .tag_length
5087                    .as_ref()
5088                    .is_none_or(|length| matches!(length, 32 | 64 | 96 | 104 | 112 | 120 | 128)) &&
5089                    normalized_algorithm.iv.len() <= u64::MAX as usize &&
5090                    normalized_algorithm
5091                        .additional_data
5092                        .as_ref()
5093                        .is_none_or(|additional_data| additional_data.len() <= u64::MAX as usize)
5094            },
5095            DecryptAlgorithm::AesOcb(normalized_algorithm) => {
5096                normalized_algorithm.iv.len() <= 15 &&
5097                    normalized_algorithm
5098                        .tag_length
5099                        .as_ref()
5100                        .is_none_or(|length| matches!(length, 64 | 96 | 128))
5101            },
5102            DecryptAlgorithm::ChaCha20Poly1305(normalized_algorithm) => {
5103                normalized_algorithm.iv.len() == 12 &&
5104                    normalized_algorithm
5105                        .tag_length
5106                        .as_ref()
5107                        .is_none_or(|length| *length == 128)
5108            },
5109        }
5110    }
5111}
5112
5113impl DecryptAlgorithm {
5114    fn decrypt<D: Equivalence>(
5115        &self,
5116        key: &CryptoKey<D>,
5117        ciphertext: &[u8],
5118    ) -> Result<Vec<u8>, Error> {
5119        match self {
5120            DecryptAlgorithm::RsaOaep(algorithm) => {
5121                rsa_oaep_operation::decrypt(algorithm, key, ciphertext)
5122            },
5123            DecryptAlgorithm::AesCtr(algorithm) => {
5124                aes_ctr_operation::decrypt(algorithm, key, ciphertext)
5125            },
5126            DecryptAlgorithm::AesCbc(algorithm) => {
5127                aes_cbc_operation::decrypt(algorithm, key, ciphertext)
5128            },
5129            DecryptAlgorithm::AesGcm(algorithm) => {
5130                aes_gcm_operation::decrypt(algorithm, key, ciphertext)
5131            },
5132            DecryptAlgorithm::AesOcb(algorithm) => {
5133                aes_ocb_operation::decrypt(algorithm, key, ciphertext)
5134            },
5135            DecryptAlgorithm::ChaCha20Poly1305(algorithm) => {
5136                chacha20_poly1305_operation::decrypt(algorithm, key, ciphertext)
5137            },
5138        }
5139    }
5140}
5141
5142/// The value of the key "sign" in the internal object supportedAlgorithms
5143struct SignOperation {}
5144
5145impl Operation for SignOperation {
5146    type RegisteredAlgorithm = SignAlgorithm;
5147}
5148
5149/// Normalized algorithm for the "sign" operation, used as output of
5150/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
5151enum SignAlgorithm {
5152    RsassaPkcs1V1_5(Algorithm),
5153    RsaPss(RsaPssParams),
5154    Ecdsa(EcdsaParams),
5155    Ed25519(Algorithm),
5156    Ed448(SubtleEd448Params),
5157    Hmac(Algorithm),
5158    MlDsa(ContextParams),
5159    Kmac(KmacParams),
5160}
5161
5162impl NormalizedAlgorithm for SignAlgorithm {
5163    fn from_object(
5164        cx: &mut JSContext,
5165        algorithm_name: CryptoAlgorithm,
5166        object: HandleObject,
5167    ) -> Fallible<Self> {
5168        match algorithm_name {
5169            CryptoAlgorithm::RsassaPkcs1V1_5 => Ok(SignAlgorithm::RsassaPkcs1V1_5(
5170                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5171            )),
5172            CryptoAlgorithm::RsaPss => Ok(SignAlgorithm::RsaPss(
5173                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5174            )),
5175            CryptoAlgorithm::Ecdsa => Ok(SignAlgorithm::Ecdsa(
5176                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5177            )),
5178            CryptoAlgorithm::Ed25519 => Ok(SignAlgorithm::Ed25519(
5179                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5180            )),
5181            CryptoAlgorithm::Ed448 => Ok(SignAlgorithm::Ed448(
5182                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5183            )),
5184            CryptoAlgorithm::Hmac => Ok(SignAlgorithm::Hmac(
5185                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5186            )),
5187            CryptoAlgorithm::MlDsa44 | CryptoAlgorithm::MlDsa65 | CryptoAlgorithm::MlDsa87 => Ok(
5188                SignAlgorithm::MlDsa(object.try_into_with_cx_and_name(cx, algorithm_name)?),
5189            ),
5190            CryptoAlgorithm::Kmac128 | CryptoAlgorithm::Kmac256 => Ok(SignAlgorithm::Kmac(
5191                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5192            )),
5193            _ => Err(Error::NotSupported(Some(format!(
5194                "{} does not support \"sign\" operation",
5195                algorithm_name.as_str()
5196            )))),
5197        }
5198    }
5199
5200    fn name(&self) -> CryptoAlgorithm {
5201        match self {
5202            SignAlgorithm::RsassaPkcs1V1_5(algorithm) => algorithm.name,
5203            SignAlgorithm::RsaPss(algorithm) => algorithm.name,
5204            SignAlgorithm::Ecdsa(algorithm) => algorithm.name,
5205            SignAlgorithm::Ed25519(algorithm) => algorithm.name,
5206            SignAlgorithm::Ed448(algorithm) => algorithm.name,
5207            SignAlgorithm::Hmac(algorithm) => algorithm.name,
5208            SignAlgorithm::MlDsa(algorithm) => algorithm.name,
5209            SignAlgorithm::Kmac(algorithm) => algorithm.name,
5210        }
5211    }
5212
5213    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
5214        match self {
5215            SignAlgorithm::RsassaPkcs1V1_5(_) |
5216            SignAlgorithm::RsaPss(_) |
5217            SignAlgorithm::Ecdsa(_) |
5218            SignAlgorithm::Ed25519(_) => true,
5219            SignAlgorithm::Ed448(normalized_algorithm) => normalized_algorithm
5220                .context
5221                .as_ref()
5222                .is_none_or(|context| context.len() <= 255),
5223            SignAlgorithm::Hmac(_) => true,
5224            SignAlgorithm::MlDsa(normalized_algorithm) => normalized_algorithm
5225                .context
5226                .as_ref()
5227                .is_none_or(|context| context.len() <= 255),
5228            SignAlgorithm::Kmac(_) => true,
5229        }
5230    }
5231}
5232
5233impl SignAlgorithm {
5234    fn sign<D: Equivalence>(&self, key: &CryptoKey<D>, message: &[u8]) -> Result<Vec<u8>, Error> {
5235        match self {
5236            SignAlgorithm::RsassaPkcs1V1_5(_algorithm) => {
5237                rsassa_pkcs1_v1_5_operation::sign(key, message)
5238            },
5239            SignAlgorithm::RsaPss(algorithm) => rsa_pss_operation::sign(algorithm, key, message),
5240            SignAlgorithm::Ecdsa(algorithm) => ecdsa_operation::sign(algorithm, key, message),
5241            SignAlgorithm::Ed25519(_algorithm) => ed25519_operation::sign(key, message),
5242            SignAlgorithm::Ed448(algorithm) => ed448_operation::sign(algorithm, key, message),
5243            SignAlgorithm::Hmac(_algorithm) => hmac_operation::sign(key, message),
5244            SignAlgorithm::MlDsa(algorithm) => ml_dsa_operation::sign(algorithm, key, message),
5245            SignAlgorithm::Kmac(algorithm) => kmac_operation::sign(algorithm, key, message),
5246        }
5247    }
5248}
5249
5250/// The value of the key "verify" in the internal object supportedAlgorithms
5251struct VerifyOperation {}
5252
5253impl Operation for VerifyOperation {
5254    type RegisteredAlgorithm = VerifyAlgorithm;
5255}
5256
5257/// Normalized algorithm for the "verify" operation, used as output of
5258/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
5259enum VerifyAlgorithm {
5260    RsassaPkcs1V1_5(Algorithm),
5261    RsaPss(RsaPssParams),
5262    Ecdsa(EcdsaParams),
5263    Ed25519(Algorithm),
5264    Ed448(SubtleEd448Params),
5265    Hmac(Algorithm),
5266    MlDsa(ContextParams),
5267    Kmac(KmacParams),
5268}
5269
5270impl NormalizedAlgorithm for VerifyAlgorithm {
5271    fn from_object(
5272        cx: &mut JSContext,
5273        algorithm_name: CryptoAlgorithm,
5274        object: HandleObject,
5275    ) -> Fallible<Self> {
5276        match algorithm_name {
5277            CryptoAlgorithm::RsassaPkcs1V1_5 => Ok(VerifyAlgorithm::RsassaPkcs1V1_5(
5278                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5279            )),
5280            CryptoAlgorithm::RsaPss => Ok(VerifyAlgorithm::RsaPss(
5281                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5282            )),
5283            CryptoAlgorithm::Ecdsa => Ok(VerifyAlgorithm::Ecdsa(
5284                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5285            )),
5286            CryptoAlgorithm::Ed25519 => Ok(VerifyAlgorithm::Ed25519(
5287                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5288            )),
5289            CryptoAlgorithm::Ed448 => Ok(VerifyAlgorithm::Ed448(
5290                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5291            )),
5292            CryptoAlgorithm::Hmac => Ok(VerifyAlgorithm::Hmac(
5293                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5294            )),
5295            CryptoAlgorithm::MlDsa44 | CryptoAlgorithm::MlDsa65 | CryptoAlgorithm::MlDsa87 => Ok(
5296                VerifyAlgorithm::MlDsa(object.try_into_with_cx_and_name(cx, algorithm_name)?),
5297            ),
5298            CryptoAlgorithm::Kmac128 | CryptoAlgorithm::Kmac256 => Ok(VerifyAlgorithm::Kmac(
5299                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5300            )),
5301            _ => Err(Error::NotSupported(Some(format!(
5302                "{} does not support \"verify\" operation",
5303                algorithm_name.as_str()
5304            )))),
5305        }
5306    }
5307
5308    fn name(&self) -> CryptoAlgorithm {
5309        match self {
5310            VerifyAlgorithm::RsassaPkcs1V1_5(algorithm) => algorithm.name,
5311            VerifyAlgorithm::RsaPss(algorithm) => algorithm.name,
5312            VerifyAlgorithm::Ecdsa(algorithm) => algorithm.name,
5313            VerifyAlgorithm::Ed25519(algorithm) => algorithm.name,
5314            VerifyAlgorithm::Ed448(algorithm) => algorithm.name,
5315            VerifyAlgorithm::Hmac(algorithm) => algorithm.name,
5316            VerifyAlgorithm::MlDsa(algorithm) => algorithm.name,
5317            VerifyAlgorithm::Kmac(algorithm) => algorithm.name,
5318        }
5319    }
5320
5321    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
5322        match self {
5323            VerifyAlgorithm::RsassaPkcs1V1_5(_) |
5324            VerifyAlgorithm::RsaPss(_) |
5325            VerifyAlgorithm::Ecdsa(_) |
5326            VerifyAlgorithm::Ed25519(_) => true,
5327            VerifyAlgorithm::Ed448(normalized_algorithm) => normalized_algorithm
5328                .context
5329                .as_ref()
5330                .is_none_or(|context| context.len() <= 255),
5331            VerifyAlgorithm::Hmac(_) => true,
5332            VerifyAlgorithm::MlDsa(normalized_algorithm) => normalized_algorithm
5333                .context
5334                .as_ref()
5335                .is_none_or(|context| context.len() <= 255),
5336            VerifyAlgorithm::Kmac(_) => true,
5337        }
5338    }
5339}
5340
5341impl VerifyAlgorithm {
5342    fn verify<D: Equivalence>(
5343        &self,
5344        key: &CryptoKey<D>,
5345        message: &[u8],
5346        signature: &[u8],
5347    ) -> Result<bool, Error> {
5348        match self {
5349            VerifyAlgorithm::RsassaPkcs1V1_5(_algorithm) => {
5350                rsassa_pkcs1_v1_5_operation::verify(key, message, signature)
5351            },
5352            VerifyAlgorithm::RsaPss(algorithm) => {
5353                rsa_pss_operation::verify(algorithm, key, message, signature)
5354            },
5355            VerifyAlgorithm::Ecdsa(algorithm) => {
5356                ecdsa_operation::verify(algorithm, key, message, signature)
5357            },
5358            VerifyAlgorithm::Ed25519(_algorithm) => {
5359                ed25519_operation::verify(key, message, signature)
5360            },
5361            VerifyAlgorithm::Ed448(algorithm) => {
5362                ed448_operation::verify(algorithm, key, message, signature)
5363            },
5364            VerifyAlgorithm::Hmac(_algorithm) => hmac_operation::verify(key, message, signature),
5365            VerifyAlgorithm::MlDsa(algorithm) => {
5366                ml_dsa_operation::verify(algorithm, key, message, signature)
5367            },
5368            VerifyAlgorithm::Kmac(algorithm) => {
5369                kmac_operation::verify(algorithm, key, message, signature)
5370            },
5371        }
5372    }
5373}
5374
5375/// The value of the key "digest" in the internal object supportedAlgorithms
5376struct DigestOperation {}
5377
5378impl Operation for DigestOperation {
5379    type RegisteredAlgorithm = DigestAlgorithm;
5380}
5381
5382/// Normalized algorithm for the "digest" operation, used as output of
5383/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
5384#[derive(Clone, MallocSizeOf)]
5385enum DigestAlgorithm {
5386    Sha(Algorithm),
5387    Sha3(Algorithm),
5388    CShake(CShakeParams),
5389    TurboShake(TurboShakeParams),
5390    KangarooTwelve(KangarooTwelveParams),
5391}
5392
5393impl NormalizedAlgorithm for DigestAlgorithm {
5394    fn from_object(
5395        cx: &mut JSContext,
5396        algorithm_name: CryptoAlgorithm,
5397        object: HandleObject,
5398    ) -> Fallible<Self> {
5399        match algorithm_name {
5400            CryptoAlgorithm::Sha1 |
5401            CryptoAlgorithm::Sha256 |
5402            CryptoAlgorithm::Sha384 |
5403            CryptoAlgorithm::Sha512 => Ok(DigestAlgorithm::Sha(
5404                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5405            )),
5406            CryptoAlgorithm::Sha3_256 | CryptoAlgorithm::Sha3_384 | CryptoAlgorithm::Sha3_512 => {
5407                Ok(DigestAlgorithm::Sha3(
5408                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
5409                ))
5410            },
5411            CryptoAlgorithm::CShake128 | CryptoAlgorithm::CShake256 => Ok(DigestAlgorithm::CShake(
5412                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5413            )),
5414            CryptoAlgorithm::TurboShake128 | CryptoAlgorithm::TurboShake256 => Ok(
5415                DigestAlgorithm::TurboShake(object.try_into_with_cx_and_name(cx, algorithm_name)?),
5416            ),
5417            CryptoAlgorithm::Kt128 | CryptoAlgorithm::Kt256 => Ok(DigestAlgorithm::KangarooTwelve(
5418                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5419            )),
5420            _ => Err(Error::NotSupported(Some(format!(
5421                "{} does not support \"digest\" operation",
5422                algorithm_name.as_str()
5423            )))),
5424        }
5425    }
5426
5427    fn name(&self) -> CryptoAlgorithm {
5428        match self {
5429            DigestAlgorithm::Sha(algorithm) => algorithm.name,
5430            DigestAlgorithm::Sha3(algorithm) => algorithm.name,
5431            DigestAlgorithm::CShake(algorithm) => algorithm.name,
5432            DigestAlgorithm::TurboShake(algorithm) => algorithm.name,
5433            DigestAlgorithm::KangarooTwelve(algorithm) => algorithm.name,
5434        }
5435    }
5436
5437    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
5438        match self {
5439            DigestAlgorithm::Sha(_) |
5440            DigestAlgorithm::Sha3(_) |
5441            DigestAlgorithm::CShake(_) |
5442            DigestAlgorithm::TurboShake(_) => true,
5443            DigestAlgorithm::KangarooTwelve(normalized_algorithm) => {
5444                normalized_algorithm.output_length != 0 &&
5445                    normalized_algorithm.output_length.is_multiple_of(8)
5446            },
5447        }
5448    }
5449}
5450
5451impl DigestAlgorithm {
5452    fn digest(&self, message: &[u8]) -> Result<Vec<u8>, Error> {
5453        match self {
5454            DigestAlgorithm::Sha(algorithm) => sha_operation::digest(algorithm, message),
5455            DigestAlgorithm::Sha3(algorithm) => sha3_operation::digest(algorithm, message),
5456            DigestAlgorithm::CShake(algorithm) => cshake_operation::digest(algorithm, message),
5457            DigestAlgorithm::TurboShake(algorithm) => {
5458                turboshake_operation::digest(algorithm, message)
5459            },
5460            DigestAlgorithm::KangarooTwelve(algorithm) => {
5461                kangarootwelve_operation::digest(algorithm, message)
5462            },
5463        }
5464    }
5465}
5466
5467impl TryFrom<SerializableDigestAlgorithm> for DigestAlgorithm {
5468    type Error = ();
5469
5470    fn try_from(value: SerializableDigestAlgorithm) -> Result<Self, Self::Error> {
5471        match value {
5472            SerializableDigestAlgorithm::Sha(algorithm) => {
5473                Ok(DigestAlgorithm::Sha(algorithm.try_into()?))
5474            },
5475            SerializableDigestAlgorithm::Sha3(algorithm) => {
5476                Ok(DigestAlgorithm::Sha3(algorithm.try_into()?))
5477            },
5478            SerializableDigestAlgorithm::CShake(algorithm) => {
5479                Ok(DigestAlgorithm::CShake(algorithm.try_into()?))
5480            },
5481            SerializableDigestAlgorithm::TurboShake(algorithm) => {
5482                Ok(DigestAlgorithm::TurboShake(algorithm.try_into()?))
5483            },
5484            SerializableDigestAlgorithm::KangarooTwelve(algorithm) => {
5485                Ok(DigestAlgorithm::KangarooTwelve(algorithm.try_into()?))
5486            },
5487        }
5488    }
5489}
5490
5491impl From<&DigestAlgorithm> for SerializableDigestAlgorithm {
5492    fn from(value: &DigestAlgorithm) -> Self {
5493        match value {
5494            DigestAlgorithm::Sha(algorithm) => SerializableDigestAlgorithm::Sha(algorithm.into()),
5495            DigestAlgorithm::Sha3(algorithm) => SerializableDigestAlgorithm::Sha3(algorithm.into()),
5496            DigestAlgorithm::CShake(algorithm) => {
5497                SerializableDigestAlgorithm::CShake(algorithm.into())
5498            },
5499            DigestAlgorithm::TurboShake(algorithm) => {
5500                SerializableDigestAlgorithm::TurboShake(algorithm.into())
5501            },
5502            DigestAlgorithm::KangarooTwelve(algorithm) => {
5503                SerializableDigestAlgorithm::KangarooTwelve(algorithm.into())
5504            },
5505        }
5506    }
5507}
5508
5509/// The value of the key "deriveBits" in the internal object supportedAlgorithms
5510struct DeriveBitsOperation<D: Equivalence> {
5511    phantom: PhantomData<D>,
5512}
5513
5514impl<D: Equivalence> Operation for DeriveBitsOperation<D> {
5515    type RegisteredAlgorithm = DeriveBitsAlgorithm<D>;
5516}
5517
5518/// Normalized algorithm for the "deriveBits" operation, used as output of
5519/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
5520enum DeriveBitsAlgorithm<D: Equivalence> {
5521    Ecdh(EcdhKeyDeriveParams<D>),
5522    X25519(EcdhKeyDeriveParams<D>),
5523    X448(EcdhKeyDeriveParams<D>),
5524    Hkdf(HkdfParams),
5525    Pbkdf2(Pbkdf2Params),
5526    Argon2(Argon2Params),
5527}
5528
5529impl<D: Equivalence> NormalizedAlgorithm for DeriveBitsAlgorithm<D> {
5530    fn from_object(
5531        cx: &mut JSContext,
5532        algorithm_name: CryptoAlgorithm,
5533        object: HandleObject,
5534    ) -> Fallible<Self> {
5535        match algorithm_name {
5536            CryptoAlgorithm::Ecdh => Ok(DeriveBitsAlgorithm::Ecdh(
5537                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5538            )),
5539            CryptoAlgorithm::X25519 => Ok(DeriveBitsAlgorithm::X25519(
5540                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5541            )),
5542            CryptoAlgorithm::X448 => Ok(DeriveBitsAlgorithm::X448(
5543                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5544            )),
5545            CryptoAlgorithm::Hkdf => Ok(DeriveBitsAlgorithm::Hkdf(
5546                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5547            )),
5548            CryptoAlgorithm::Pbkdf2 => Ok(DeriveBitsAlgorithm::Pbkdf2(
5549                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5550            )),
5551            CryptoAlgorithm::Argon2D | CryptoAlgorithm::Argon2I | CryptoAlgorithm::Argon2ID => Ok(
5552                DeriveBitsAlgorithm::Argon2(object.try_into_with_cx_and_name(cx, algorithm_name)?),
5553            ),
5554            _ => Err(Error::NotSupported(Some(format!(
5555                "{} does not support \"deriveBits\" operation",
5556                algorithm_name.as_str()
5557            )))),
5558        }
5559    }
5560
5561    fn name(&self) -> CryptoAlgorithm {
5562        match self {
5563            DeriveBitsAlgorithm::Ecdh(algorithm) => algorithm.name,
5564            DeriveBitsAlgorithm::X25519(algorithm) => algorithm.name,
5565            DeriveBitsAlgorithm::X448(algorithm) => algorithm.name,
5566            DeriveBitsAlgorithm::Hkdf(algorithm) => algorithm.name,
5567            DeriveBitsAlgorithm::Pbkdf2(algorithm) => algorithm.name,
5568            DeriveBitsAlgorithm::Argon2(algorithm) => algorithm.name,
5569        }
5570    }
5571
5572    fn determine_support_from_operation_steps(&self, length: Option<u32>) -> bool {
5573        match self {
5574            DeriveBitsAlgorithm::Ecdh(normalized_algorithm) => {
5575                let public_key = normalized_algorithm.public.root();
5576                let Ok(maximum_length) = ecdh_operation::maximum_length(&public_key) else {
5577                    return false;
5578                };
5579                public_key.Type() == KeyType::Public &&
5580                    public_key.algorithm().name() == normalized_algorithm.name &&
5581                    length.is_none_or(|length| length <= maximum_length)
5582            },
5583            DeriveBitsAlgorithm::X25519(normalized_algorithm) => {
5584                let public_key = normalized_algorithm.public.root();
5585                public_key.Type() == KeyType::Public &&
5586                    public_key.algorithm().name() == normalized_algorithm.name &&
5587                    length.is_none_or(|length| length <= 256)
5588            },
5589            DeriveBitsAlgorithm::X448(_) => {
5590                length.is_none_or(|length| x448_operation::SECRET_LENGTH as u32 * 8 >= length)
5591            },
5592            DeriveBitsAlgorithm::Hkdf(normalized_algorithm) => {
5593                let hash_length = match normalized_algorithm.hash.name() {
5594                    CryptoAlgorithm::Sha1 => 160,
5595                    CryptoAlgorithm::Sha256 => 256,
5596                    CryptoAlgorithm::Sha384 => 384,
5597                    CryptoAlgorithm::Sha512 => 512,
5598                    _ => return false,
5599                };
5600                length.is_some_and(|length| length % 8 == 0 && length <= 255 * hash_length)
5601            },
5602            DeriveBitsAlgorithm::Pbkdf2(normalized_algorithm) => {
5603                length.is_some_and(|length| length % 8 == 0) && normalized_algorithm.iterations != 0
5604            },
5605            DeriveBitsAlgorithm::Argon2(normalized_algorithm) => {
5606                length.is_some_and(|length| length >= 32 && length % 8 == 0) &&
5607                    normalized_algorithm
5608                        .version
5609                        .is_none_or(|version| version == 19) &&
5610                    normalized_algorithm.parallelism != 0 &&
5611                    normalized_algorithm.parallelism <= 16777215 &&
5612                    normalized_algorithm.memory >= 8 * normalized_algorithm.parallelism &&
5613                    normalized_algorithm.passes != 0
5614            },
5615        }
5616    }
5617}
5618
5619impl<D: Equivalence> DeriveBitsAlgorithm<D> {
5620    fn derive_bits(&self, key: &CryptoKey<D>, length: Option<u32>) -> Result<Vec<u8>, Error> {
5621        match self {
5622            DeriveBitsAlgorithm::Ecdh(algorithm) => {
5623                ecdh_operation::derive_bits(algorithm, key, length)
5624            },
5625            DeriveBitsAlgorithm::X25519(algorithm) => {
5626                x25519_operation::derive_bits(algorithm, key, length)
5627            },
5628            DeriveBitsAlgorithm::X448(algorithm) => {
5629                x448_operation::derive_bits(algorithm, key, length)
5630            },
5631            DeriveBitsAlgorithm::Hkdf(algorithm) => {
5632                hkdf_operation::derive_bits(algorithm, key, length)
5633            },
5634            DeriveBitsAlgorithm::Pbkdf2(algorithm) => {
5635                pbkdf2_operation::derive_bits(algorithm, key, length)
5636            },
5637            DeriveBitsAlgorithm::Argon2(algorithm) => {
5638                argon2_operation::derive_bits(algorithm, key, length)
5639            },
5640        }
5641    }
5642}
5643
5644/// The value of the key "wrapKey" in the internal object supportedAlgorithms
5645struct WrapKeyOperation {}
5646
5647impl Operation for WrapKeyOperation {
5648    type RegisteredAlgorithm = WrapKeyAlgorithm;
5649}
5650
5651/// Normalized algorithm for the "wrapKey" operation, used as output of
5652/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
5653enum WrapKeyAlgorithm {
5654    AesKw(Algorithm),
5655}
5656
5657impl NormalizedAlgorithm for WrapKeyAlgorithm {
5658    fn from_object(
5659        cx: &mut JSContext,
5660        algorithm_name: CryptoAlgorithm,
5661        object: HandleObject,
5662    ) -> Fallible<Self> {
5663        match algorithm_name {
5664            CryptoAlgorithm::AesKw => Ok(WrapKeyAlgorithm::AesKw(
5665                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5666            )),
5667            _ => Err(Error::NotSupported(Some(format!(
5668                "{} does not support \"wrapKey\" operation",
5669                algorithm_name.as_str()
5670            )))),
5671        }
5672    }
5673
5674    fn name(&self) -> CryptoAlgorithm {
5675        match self {
5676            WrapKeyAlgorithm::AesKw(algorithm) => algorithm.name,
5677        }
5678    }
5679
5680    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
5681        match self {
5682            WrapKeyAlgorithm::AesKw(_) => true,
5683        }
5684    }
5685}
5686
5687impl WrapKeyAlgorithm {
5688    fn wrap_key<D: Equivalence>(
5689        &self,
5690        key: &CryptoKey<D>,
5691        plaintext: &[u8],
5692    ) -> Result<Vec<u8>, Error> {
5693        match self {
5694            WrapKeyAlgorithm::AesKw(_algorithm) => aes_kw_operation::wrap_key(key, plaintext),
5695        }
5696    }
5697}
5698
5699/// The value of the key "unwrapKey" in the internal object supportedAlgorithms
5700struct UnwrapKeyOperation {}
5701
5702impl Operation for UnwrapKeyOperation {
5703    type RegisteredAlgorithm = UnwrapKeyAlgorithm;
5704}
5705
5706/// Normalized algorithm for the "unwrapKey" operation, used as output of
5707/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
5708enum UnwrapKeyAlgorithm {
5709    AesKw(Algorithm),
5710}
5711
5712impl NormalizedAlgorithm for UnwrapKeyAlgorithm {
5713    fn from_object(
5714        cx: &mut JSContext,
5715        algorithm_name: CryptoAlgorithm,
5716        object: HandleObject,
5717    ) -> Fallible<Self> {
5718        match algorithm_name {
5719            CryptoAlgorithm::AesKw => Ok(UnwrapKeyAlgorithm::AesKw(
5720                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5721            )),
5722            _ => Err(Error::NotSupported(Some(format!(
5723                "{} does not support \"unwrapKey\" operation",
5724                algorithm_name.as_str()
5725            )))),
5726        }
5727    }
5728
5729    fn name(&self) -> CryptoAlgorithm {
5730        match self {
5731            UnwrapKeyAlgorithm::AesKw(algorithm) => algorithm.name,
5732        }
5733    }
5734
5735    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
5736        match self {
5737            UnwrapKeyAlgorithm::AesKw(_) => true,
5738        }
5739    }
5740}
5741
5742impl UnwrapKeyAlgorithm {
5743    fn unwrap_key<D: Equivalence>(
5744        &self,
5745        key: &CryptoKey<D>,
5746        ciphertext: &[u8],
5747    ) -> Result<Vec<u8>, Error> {
5748        match self {
5749            UnwrapKeyAlgorithm::AesKw(_algorithm) => aes_kw_operation::unwrap_key(key, ciphertext),
5750        }
5751    }
5752}
5753
5754/// The value of the key "unwrapKey" in the internal object supportedAlgorithms
5755struct GenerateKeyOperation {}
5756
5757impl Operation for GenerateKeyOperation {
5758    type RegisteredAlgorithm = GenerateKeyAlgorithm;
5759}
5760
5761/// Normalized algorithm for the "generateKey" operation, used as output of
5762/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
5763enum GenerateKeyAlgorithm {
5764    RsassaPkcs1V1_5(RsaHashedKeyGenParams),
5765    RsaPss(RsaHashedKeyGenParams),
5766    RsaOaep(RsaHashedKeyGenParams),
5767    Ecdsa(EcKeyGenParams),
5768    Ecdh(EcKeyGenParams),
5769    Ed25519(Algorithm),
5770    X25519(Algorithm),
5771    Ed448(Algorithm),
5772    X448(Algorithm),
5773    AesCtr(AesKeyGenParams),
5774    AesCbc(AesKeyGenParams),
5775    AesGcm(AesKeyGenParams),
5776    AesKw(AesKeyGenParams),
5777    Hmac(HmacKeyGenParams),
5778    MlKem(Algorithm),
5779    HybridKem(Algorithm),
5780    MlDsa(Algorithm),
5781    AesOcb(AesKeyGenParams),
5782    ChaCha20Poly1305(Algorithm),
5783    Kmac(KmacKeyGenParams),
5784}
5785
5786impl NormalizedAlgorithm for GenerateKeyAlgorithm {
5787    fn from_object(
5788        cx: &mut JSContext,
5789        algorithm_name: CryptoAlgorithm,
5790        object: HandleObject,
5791    ) -> Fallible<Self> {
5792        match algorithm_name {
5793            CryptoAlgorithm::RsassaPkcs1V1_5 => Ok(GenerateKeyAlgorithm::RsassaPkcs1V1_5(
5794                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5795            )),
5796            CryptoAlgorithm::RsaPss => Ok(GenerateKeyAlgorithm::RsaPss(
5797                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5798            )),
5799            CryptoAlgorithm::RsaOaep => Ok(GenerateKeyAlgorithm::RsaOaep(
5800                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5801            )),
5802            CryptoAlgorithm::Ecdsa => Ok(GenerateKeyAlgorithm::Ecdsa(
5803                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5804            )),
5805            CryptoAlgorithm::Ecdh => Ok(GenerateKeyAlgorithm::Ecdh(
5806                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5807            )),
5808            CryptoAlgorithm::Ed25519 => Ok(GenerateKeyAlgorithm::Ed25519(
5809                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5810            )),
5811            CryptoAlgorithm::X25519 => Ok(GenerateKeyAlgorithm::X25519(
5812                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5813            )),
5814            CryptoAlgorithm::Ed448 => Ok(GenerateKeyAlgorithm::Ed448(
5815                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5816            )),
5817            CryptoAlgorithm::X448 => Ok(GenerateKeyAlgorithm::X448(
5818                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5819            )),
5820            CryptoAlgorithm::AesCtr => Ok(GenerateKeyAlgorithm::AesCtr(
5821                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5822            )),
5823            CryptoAlgorithm::AesCbc => Ok(GenerateKeyAlgorithm::AesCbc(
5824                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5825            )),
5826            CryptoAlgorithm::AesGcm => Ok(GenerateKeyAlgorithm::AesGcm(
5827                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5828            )),
5829            CryptoAlgorithm::AesKw => Ok(GenerateKeyAlgorithm::AesKw(
5830                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5831            )),
5832            CryptoAlgorithm::Hmac => Ok(GenerateKeyAlgorithm::Hmac(
5833                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5834            )),
5835            CryptoAlgorithm::MlKem512 | CryptoAlgorithm::MlKem768 | CryptoAlgorithm::MlKem1024 => {
5836                Ok(GenerateKeyAlgorithm::MlKem(
5837                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
5838                ))
5839            },
5840            CryptoAlgorithm::MlKem768X25519 => Ok(GenerateKeyAlgorithm::HybridKem(
5841                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5842            )),
5843            CryptoAlgorithm::MlDsa44 | CryptoAlgorithm::MlDsa65 | CryptoAlgorithm::MlDsa87 => Ok(
5844                GenerateKeyAlgorithm::MlDsa(object.try_into_with_cx_and_name(cx, algorithm_name)?),
5845            ),
5846            CryptoAlgorithm::AesOcb => Ok(GenerateKeyAlgorithm::AesOcb(
5847                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5848            )),
5849            CryptoAlgorithm::ChaCha20Poly1305 => Ok(GenerateKeyAlgorithm::ChaCha20Poly1305(
5850                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5851            )),
5852            CryptoAlgorithm::Kmac128 | CryptoAlgorithm::Kmac256 => Ok(GenerateKeyAlgorithm::Kmac(
5853                object.try_into_with_cx_and_name(cx, algorithm_name)?,
5854            )),
5855            _ => Err(Error::NotSupported(Some(format!(
5856                "{} does not support \"generateKey\" operation",
5857                algorithm_name.as_str()
5858            )))),
5859        }
5860    }
5861
5862    fn name(&self) -> CryptoAlgorithm {
5863        match self {
5864            GenerateKeyAlgorithm::RsassaPkcs1V1_5(algorithm) => algorithm.name,
5865            GenerateKeyAlgorithm::RsaPss(algorithm) => algorithm.name,
5866            GenerateKeyAlgorithm::RsaOaep(algorithm) => algorithm.name,
5867            GenerateKeyAlgorithm::Ecdsa(algorithm) => algorithm.name,
5868            GenerateKeyAlgorithm::Ecdh(algorithm) => algorithm.name,
5869            GenerateKeyAlgorithm::Ed25519(algorithm) => algorithm.name,
5870            GenerateKeyAlgorithm::X25519(algorithm) => algorithm.name,
5871            GenerateKeyAlgorithm::Ed448(algorithm) => algorithm.name,
5872            GenerateKeyAlgorithm::X448(algorithm) => algorithm.name,
5873            GenerateKeyAlgorithm::AesCtr(algorithm) => algorithm.name,
5874            GenerateKeyAlgorithm::AesCbc(algorithm) => algorithm.name,
5875            GenerateKeyAlgorithm::AesGcm(algorithm) => algorithm.name,
5876            GenerateKeyAlgorithm::AesKw(algorithm) => algorithm.name,
5877            GenerateKeyAlgorithm::Hmac(algorithm) => algorithm.name,
5878            GenerateKeyAlgorithm::MlKem(algorithm) => algorithm.name,
5879            GenerateKeyAlgorithm::HybridKem(algorithm) => algorithm.name,
5880            GenerateKeyAlgorithm::MlDsa(algorithm) => algorithm.name,
5881            GenerateKeyAlgorithm::AesOcb(algorithm) => algorithm.name,
5882            GenerateKeyAlgorithm::ChaCha20Poly1305(algorithm) => algorithm.name,
5883            GenerateKeyAlgorithm::Kmac(algorithm) => algorithm.name,
5884        }
5885    }
5886
5887    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
5888        match self {
5889            GenerateKeyAlgorithm::RsassaPkcs1V1_5(normalized_algorithm) |
5890            GenerateKeyAlgorithm::RsaPss(normalized_algorithm) |
5891            GenerateKeyAlgorithm::RsaOaep(normalized_algorithm) => {
5892                normalized_algorithm.validate_parameters().is_ok()
5893            },
5894            GenerateKeyAlgorithm::Ecdsa(normalized_algorithm) |
5895            GenerateKeyAlgorithm::Ecdh(normalized_algorithm) => {
5896                SUPPORTED_CURVES.contains(&normalized_algorithm.named_curve.as_str())
5897            },
5898            GenerateKeyAlgorithm::Ed25519(_) |
5899            GenerateKeyAlgorithm::X25519(_) |
5900            GenerateKeyAlgorithm::Ed448(_) |
5901            GenerateKeyAlgorithm::X448(_) => true,
5902            GenerateKeyAlgorithm::AesCtr(normalized_algorithm) |
5903            GenerateKeyAlgorithm::AesCbc(normalized_algorithm) |
5904            GenerateKeyAlgorithm::AesGcm(normalized_algorithm) |
5905            GenerateKeyAlgorithm::AesKw(normalized_algorithm) => {
5906                matches!(normalized_algorithm.length, 128 | 192 | 256)
5907            },
5908            GenerateKeyAlgorithm::Hmac(normalized_algorithm) => {
5909                normalized_algorithm.length.is_none_or(|length| length != 0)
5910            },
5911            GenerateKeyAlgorithm::MlKem(_) |
5912            GenerateKeyAlgorithm::HybridKem(_) |
5913            GenerateKeyAlgorithm::MlDsa(_) => true,
5914            GenerateKeyAlgorithm::AesOcb(normalized_algorithm) => {
5915                matches!(normalized_algorithm.length, 128 | 192 | 256)
5916            },
5917            GenerateKeyAlgorithm::ChaCha20Poly1305(_) | GenerateKeyAlgorithm::Kmac(_) => true,
5918        }
5919    }
5920}
5921
5922impl GenerateKeyAlgorithm {
5923    fn generate_key<D: Equivalence>(
5924        &self,
5925        cx: &mut JSContext,
5926        global: &D::GlobalScope,
5927        extractable: bool,
5928        usages: Vec<KeyUsage>,
5929    ) -> Result<CryptoKeyOrCryptoKeyPair<D>, Error> {
5930        match self {
5931            GenerateKeyAlgorithm::RsassaPkcs1V1_5(algorithm) => {
5932                rsassa_pkcs1_v1_5_operation::generate_key(
5933                    cx,
5934                    global,
5935                    algorithm,
5936                    extractable,
5937                    usages,
5938                )
5939                .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5940            },
5941            GenerateKeyAlgorithm::RsaPss(algorithm) => {
5942                rsa_pss_operation::generate_key(cx, global, algorithm, extractable, usages)
5943                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5944            },
5945            GenerateKeyAlgorithm::RsaOaep(algorithm) => {
5946                rsa_oaep_operation::generate_key(cx, global, algorithm, extractable, usages)
5947                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5948            },
5949            GenerateKeyAlgorithm::Ecdsa(algorithm) => {
5950                ecdsa_operation::generate_key(cx, global, algorithm, extractable, usages)
5951                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5952            },
5953            GenerateKeyAlgorithm::Ecdh(algorithm) => {
5954                ecdh_operation::generate_key(cx, global, algorithm, extractable, usages)
5955                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5956            },
5957            GenerateKeyAlgorithm::Ed25519(_algorithm) => {
5958                ed25519_operation::generate_key(cx, global, extractable, usages)
5959                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5960            },
5961            GenerateKeyAlgorithm::X25519(_algorithm) => {
5962                x25519_operation::generate_key(cx, global, extractable, usages)
5963                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5964            },
5965            GenerateKeyAlgorithm::Ed448(_algorithm) => {
5966                ed448_operation::generate_key(cx, global, extractable, usages)
5967                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5968            },
5969            GenerateKeyAlgorithm::X448(_algorithm) => {
5970                x448_operation::generate_key(cx, global, extractable, usages)
5971                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5972            },
5973            GenerateKeyAlgorithm::AesCtr(algorithm) => {
5974                aes_ctr_operation::generate_key(cx, global, algorithm, extractable, usages)
5975                    .map(CryptoKeyOrCryptoKeyPair::CryptoKey)
5976            },
5977            GenerateKeyAlgorithm::AesCbc(algorithm) => {
5978                aes_cbc_operation::generate_key(cx, global, algorithm, extractable, usages)
5979                    .map(CryptoKeyOrCryptoKeyPair::CryptoKey)
5980            },
5981            GenerateKeyAlgorithm::AesGcm(algorithm) => {
5982                aes_gcm_operation::generate_key(cx, global, algorithm, extractable, usages)
5983                    .map(CryptoKeyOrCryptoKeyPair::CryptoKey)
5984            },
5985            GenerateKeyAlgorithm::AesKw(algorithm) => {
5986                aes_kw_operation::generate_key(cx, global, algorithm, extractable, usages)
5987                    .map(CryptoKeyOrCryptoKeyPair::CryptoKey)
5988            },
5989            GenerateKeyAlgorithm::Hmac(algorithm) => {
5990                hmac_operation::generate_key(cx, global, algorithm, extractable, usages)
5991                    .map(CryptoKeyOrCryptoKeyPair::CryptoKey)
5992            },
5993            GenerateKeyAlgorithm::MlKem(algorithm) => {
5994                ml_kem_operation::generate_key(cx, global, algorithm, extractable, usages)
5995                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
5996            },
5997            GenerateKeyAlgorithm::HybridKem(algorithm) => {
5998                hybrid_kem_operation::generate_key(cx, global, algorithm, extractable, usages)
5999                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
6000            },
6001            GenerateKeyAlgorithm::MlDsa(algorithm) => {
6002                ml_dsa_operation::generate_key(cx, global, algorithm, extractable, usages)
6003                    .map(CryptoKeyOrCryptoKeyPair::CryptoKeyPair)
6004            },
6005            GenerateKeyAlgorithm::AesOcb(algorithm) => {
6006                aes_ocb_operation::generate_key(cx, global, algorithm, extractable, usages)
6007                    .map(CryptoKeyOrCryptoKeyPair::CryptoKey)
6008            },
6009            GenerateKeyAlgorithm::ChaCha20Poly1305(_algorithm) => {
6010                chacha20_poly1305_operation::generate_key(cx, global, extractable, usages)
6011                    .map(CryptoKeyOrCryptoKeyPair::CryptoKey)
6012            },
6013            GenerateKeyAlgorithm::Kmac(algorithm) => {
6014                kmac_operation::generate_key(cx, global, algorithm, extractable, usages)
6015                    .map(CryptoKeyOrCryptoKeyPair::CryptoKey)
6016            },
6017        }
6018    }
6019}
6020
6021/// The value of the key "importKey" in the internal object supportedAlgorithms
6022struct ImportKeyOperation {}
6023
6024impl Operation for ImportKeyOperation {
6025    type RegisteredAlgorithm = ImportKeyAlgorithm;
6026}
6027
6028/// Normalized algorithm for the "importKey" operation, used as output of
6029/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
6030enum ImportKeyAlgorithm {
6031    RsassaPkcs1V1_5(RsaHashedImportParams),
6032    RsaPss(RsaHashedImportParams),
6033    RsaOaep(RsaHashedImportParams),
6034    Ecdsa(EcKeyImportParams),
6035    Ecdh(EcKeyImportParams),
6036    Ed25519(Algorithm),
6037    X25519(Algorithm),
6038    Ed448(Algorithm),
6039    X448(Algorithm),
6040    AesCtr(Algorithm),
6041    AesCbc(Algorithm),
6042    AesGcm(Algorithm),
6043    AesKw(Algorithm),
6044    Hmac(HmacImportParams),
6045    Hkdf(Algorithm),
6046    Pbkdf2(Algorithm),
6047    MlKem(Algorithm),
6048    HybridKem(Algorithm),
6049    MlDsa(Algorithm),
6050    AesOcb(Algorithm),
6051    ChaCha20Poly1305(Algorithm),
6052    Kmac(KmacImportParams),
6053    Argon2(Algorithm),
6054}
6055
6056impl NormalizedAlgorithm for ImportKeyAlgorithm {
6057    fn from_object(
6058        cx: &mut JSContext,
6059        algorithm_name: CryptoAlgorithm,
6060        object: HandleObject,
6061    ) -> Fallible<Self> {
6062        match algorithm_name {
6063            CryptoAlgorithm::RsassaPkcs1V1_5 => Ok(ImportKeyAlgorithm::RsassaPkcs1V1_5(
6064                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6065            )),
6066            CryptoAlgorithm::RsaPss => Ok(ImportKeyAlgorithm::RsaPss(
6067                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6068            )),
6069            CryptoAlgorithm::RsaOaep => Ok(ImportKeyAlgorithm::RsaOaep(
6070                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6071            )),
6072            CryptoAlgorithm::Ecdsa => Ok(ImportKeyAlgorithm::Ecdsa(
6073                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6074            )),
6075            CryptoAlgorithm::Ecdh => Ok(ImportKeyAlgorithm::Ecdh(
6076                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6077            )),
6078            CryptoAlgorithm::Ed25519 => Ok(ImportKeyAlgorithm::Ed25519(
6079                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6080            )),
6081            CryptoAlgorithm::X25519 => Ok(ImportKeyAlgorithm::X25519(
6082                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6083            )),
6084            CryptoAlgorithm::Ed448 => Ok(ImportKeyAlgorithm::Ed448(
6085                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6086            )),
6087            CryptoAlgorithm::X448 => Ok(ImportKeyAlgorithm::X448(
6088                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6089            )),
6090            CryptoAlgorithm::AesCtr => Ok(ImportKeyAlgorithm::AesCtr(
6091                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6092            )),
6093            CryptoAlgorithm::AesCbc => Ok(ImportKeyAlgorithm::AesCbc(
6094                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6095            )),
6096            CryptoAlgorithm::AesGcm => Ok(ImportKeyAlgorithm::AesGcm(
6097                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6098            )),
6099            CryptoAlgorithm::AesKw => Ok(ImportKeyAlgorithm::AesKw(
6100                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6101            )),
6102            CryptoAlgorithm::Hmac => Ok(ImportKeyAlgorithm::Hmac(
6103                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6104            )),
6105            CryptoAlgorithm::Hkdf => Ok(ImportKeyAlgorithm::Hkdf(
6106                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6107            )),
6108            CryptoAlgorithm::Pbkdf2 => Ok(ImportKeyAlgorithm::Pbkdf2(
6109                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6110            )),
6111            CryptoAlgorithm::MlKem512 | CryptoAlgorithm::MlKem768 | CryptoAlgorithm::MlKem1024 => {
6112                Ok(ImportKeyAlgorithm::MlKem(
6113                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
6114                ))
6115            },
6116            CryptoAlgorithm::MlKem768X25519 => Ok(ImportKeyAlgorithm::HybridKem(
6117                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6118            )),
6119            CryptoAlgorithm::MlDsa44 | CryptoAlgorithm::MlDsa65 | CryptoAlgorithm::MlDsa87 => Ok(
6120                ImportKeyAlgorithm::MlDsa(object.try_into_with_cx_and_name(cx, algorithm_name)?),
6121            ),
6122            CryptoAlgorithm::AesOcb => Ok(ImportKeyAlgorithm::AesOcb(
6123                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6124            )),
6125            CryptoAlgorithm::ChaCha20Poly1305 => Ok(ImportKeyAlgorithm::ChaCha20Poly1305(
6126                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6127            )),
6128            CryptoAlgorithm::Kmac128 | CryptoAlgorithm::Kmac256 => Ok(ImportKeyAlgorithm::Kmac(
6129                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6130            )),
6131            CryptoAlgorithm::Argon2D | CryptoAlgorithm::Argon2I | CryptoAlgorithm::Argon2ID => Ok(
6132                ImportKeyAlgorithm::Argon2(object.try_into_with_cx_and_name(cx, algorithm_name)?),
6133            ),
6134            _ => Err(Error::NotSupported(Some(format!(
6135                "{} does not support \"importKey\" operation",
6136                algorithm_name.as_str()
6137            )))),
6138        }
6139    }
6140
6141    fn name(&self) -> CryptoAlgorithm {
6142        match self {
6143            ImportKeyAlgorithm::RsassaPkcs1V1_5(algorithm) => algorithm.name,
6144            ImportKeyAlgorithm::RsaPss(algorithm) => algorithm.name,
6145            ImportKeyAlgorithm::RsaOaep(algorithm) => algorithm.name,
6146            ImportKeyAlgorithm::Ecdsa(algorithm) => algorithm.name,
6147            ImportKeyAlgorithm::Ecdh(algorithm) => algorithm.name,
6148            ImportKeyAlgorithm::Ed25519(algorithm) => algorithm.name,
6149            ImportKeyAlgorithm::X25519(algorithm) => algorithm.name,
6150            ImportKeyAlgorithm::Ed448(algorithm) => algorithm.name,
6151            ImportKeyAlgorithm::X448(algorithm) => algorithm.name,
6152            ImportKeyAlgorithm::AesCtr(algorithm) => algorithm.name,
6153            ImportKeyAlgorithm::AesCbc(algorithm) => algorithm.name,
6154            ImportKeyAlgorithm::AesGcm(algorithm) => algorithm.name,
6155            ImportKeyAlgorithm::AesKw(algorithm) => algorithm.name,
6156            ImportKeyAlgorithm::Hmac(algorithm) => algorithm.name,
6157            ImportKeyAlgorithm::Hkdf(algorithm) => algorithm.name,
6158            ImportKeyAlgorithm::Pbkdf2(algorithm) => algorithm.name,
6159            ImportKeyAlgorithm::MlKem(algorithm) => algorithm.name,
6160            ImportKeyAlgorithm::HybridKem(algorithm) => algorithm.name,
6161            ImportKeyAlgorithm::MlDsa(algorithm) => algorithm.name,
6162            ImportKeyAlgorithm::AesOcb(algorithm) => algorithm.name,
6163            ImportKeyAlgorithm::ChaCha20Poly1305(algorithm) => algorithm.name,
6164            ImportKeyAlgorithm::Kmac(algorithm) => algorithm.name,
6165            ImportKeyAlgorithm::Argon2(algorithm) => algorithm.name,
6166        }
6167    }
6168
6169    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
6170        match self {
6171            ImportKeyAlgorithm::RsassaPkcs1V1_5(_) |
6172            ImportKeyAlgorithm::RsaPss(_) |
6173            ImportKeyAlgorithm::RsaOaep(_) => true,
6174            ImportKeyAlgorithm::Ecdsa(normalized_algorithm) |
6175            ImportKeyAlgorithm::Ecdh(normalized_algorithm) => {
6176                SUPPORTED_CURVES.contains(&normalized_algorithm.named_curve.as_str())
6177            },
6178            ImportKeyAlgorithm::Ed25519(_) |
6179            ImportKeyAlgorithm::X25519(_) |
6180            ImportKeyAlgorithm::Ed448(_) |
6181            ImportKeyAlgorithm::X448(_) |
6182            ImportKeyAlgorithm::AesCtr(_) |
6183            ImportKeyAlgorithm::AesCbc(_) |
6184            ImportKeyAlgorithm::AesGcm(_) |
6185            ImportKeyAlgorithm::AesKw(_) => true,
6186            ImportKeyAlgorithm::Hmac(normalized_algorithm) => {
6187                normalized_algorithm.length.is_none_or(|length| length != 0)
6188            },
6189            ImportKeyAlgorithm::Hkdf(_) |
6190            ImportKeyAlgorithm::Pbkdf2(_) |
6191            ImportKeyAlgorithm::MlKem(_) |
6192            ImportKeyAlgorithm::HybridKem(_) |
6193            ImportKeyAlgorithm::MlDsa(_) |
6194            ImportKeyAlgorithm::AesOcb(_) |
6195            ImportKeyAlgorithm::ChaCha20Poly1305(_) |
6196            ImportKeyAlgorithm::Kmac(_) |
6197            ImportKeyAlgorithm::Argon2(_) => true,
6198        }
6199    }
6200}
6201
6202impl ImportKeyAlgorithm {
6203    fn import_key<D: Equivalence>(
6204        &self,
6205        cx: &mut JSContext,
6206        global: &D::GlobalScope,
6207        format: KeyFormat,
6208        key_data: &[u8],
6209        extractable: bool,
6210        usages: Vec<KeyUsage>,
6211    ) -> Result<DomRoot<CryptoKey<D>>, Error> {
6212        match self {
6213            ImportKeyAlgorithm::RsassaPkcs1V1_5(algorithm) => {
6214                rsassa_pkcs1_v1_5_operation::import_key(
6215                    cx,
6216                    global,
6217                    algorithm,
6218                    format,
6219                    key_data,
6220                    extractable,
6221                    usages,
6222                )
6223            },
6224            ImportKeyAlgorithm::RsaPss(algorithm) => rsa_pss_operation::import_key(
6225                cx,
6226                global,
6227                algorithm,
6228                format,
6229                key_data,
6230                extractable,
6231                usages,
6232            ),
6233            ImportKeyAlgorithm::RsaOaep(algorithm) => rsa_oaep_operation::import_key(
6234                cx,
6235                global,
6236                algorithm,
6237                format,
6238                key_data,
6239                extractable,
6240                usages,
6241            ),
6242            ImportKeyAlgorithm::Ecdsa(algorithm) => ecdsa_operation::import_key(
6243                cx,
6244                global,
6245                algorithm,
6246                format,
6247                key_data,
6248                extractable,
6249                usages,
6250            ),
6251            ImportKeyAlgorithm::Ecdh(algorithm) => ecdh_operation::import_key(
6252                cx,
6253                global,
6254                algorithm,
6255                format,
6256                key_data,
6257                extractable,
6258                usages,
6259            ),
6260            ImportKeyAlgorithm::Ed25519(_algorithm) => {
6261                ed25519_operation::import_key(cx, global, format, key_data, extractable, usages)
6262            },
6263            ImportKeyAlgorithm::X25519(_algorithm) => {
6264                x25519_operation::import_key(cx, global, format, key_data, extractable, usages)
6265            },
6266            ImportKeyAlgorithm::Ed448(_algorithm) => {
6267                ed448_operation::import_key(cx, global, format, key_data, extractable, usages)
6268            },
6269            ImportKeyAlgorithm::X448(_algorithm) => {
6270                x448_operation::import_key(cx, global, format, key_data, extractable, usages)
6271            },
6272            ImportKeyAlgorithm::AesCtr(_algorithm) => {
6273                aes_ctr_operation::import_key(cx, global, format, key_data, extractable, usages)
6274            },
6275            ImportKeyAlgorithm::AesCbc(_algorithm) => {
6276                aes_cbc_operation::import_key(cx, global, format, key_data, extractable, usages)
6277            },
6278            ImportKeyAlgorithm::AesGcm(_algorithm) => {
6279                aes_gcm_operation::import_key(cx, global, format, key_data, extractable, usages)
6280            },
6281            ImportKeyAlgorithm::AesKw(_algorithm) => {
6282                aes_kw_operation::import_key(cx, global, format, key_data, extractable, usages)
6283            },
6284            ImportKeyAlgorithm::Hmac(algorithm) => hmac_operation::import_key(
6285                cx,
6286                global,
6287                algorithm,
6288                format,
6289                key_data,
6290                extractable,
6291                usages,
6292            ),
6293            ImportKeyAlgorithm::Hkdf(_algorithm) => {
6294                hkdf_operation::import_key(cx, global, format, key_data, extractable, usages)
6295            },
6296            ImportKeyAlgorithm::Pbkdf2(_algorithm) => {
6297                pbkdf2_operation::import_key(cx, global, format, key_data, extractable, usages)
6298            },
6299            ImportKeyAlgorithm::MlKem(algorithm) => ml_kem_operation::import_key(
6300                cx,
6301                global,
6302                algorithm,
6303                format,
6304                key_data,
6305                extractable,
6306                usages,
6307            ),
6308            ImportKeyAlgorithm::HybridKem(algorithm) => hybrid_kem_operation::import_key(
6309                cx,
6310                global,
6311                algorithm,
6312                format,
6313                key_data,
6314                extractable,
6315                usages,
6316            ),
6317            ImportKeyAlgorithm::MlDsa(algorithm) => ml_dsa_operation::import_key(
6318                cx,
6319                global,
6320                algorithm,
6321                format,
6322                key_data,
6323                extractable,
6324                usages,
6325            ),
6326            ImportKeyAlgorithm::AesOcb(_algorithm) => {
6327                aes_ocb_operation::import_key(cx, global, format, key_data, extractable, usages)
6328            },
6329            ImportKeyAlgorithm::ChaCha20Poly1305(_algorithm) => {
6330                chacha20_poly1305_operation::import_key(
6331                    cx,
6332                    global,
6333                    format,
6334                    key_data,
6335                    extractable,
6336                    usages,
6337                )
6338            },
6339            ImportKeyAlgorithm::Kmac(algorithm) => kmac_operation::import_key(
6340                cx,
6341                global,
6342                algorithm,
6343                format,
6344                key_data,
6345                extractable,
6346                usages,
6347            ),
6348            ImportKeyAlgorithm::Argon2(algorithm) => argon2_operation::import_key(
6349                cx,
6350                global,
6351                algorithm,
6352                format,
6353                key_data,
6354                extractable,
6355                usages,
6356            ),
6357        }
6358    }
6359
6360    /// Return whether the import key operation specified by normalized algorithm would throw an
6361    /// error for every value of keyData that is a byte sequence whose length in bits is
6362    /// sharedKeyLength when format is "raw-secret".
6363    fn will_throw_for_key_data_length(&self, key_data_length: u32) -> bool {
6364        match self {
6365            ImportKeyAlgorithm::RsassaPkcs1V1_5(_) |
6366            ImportKeyAlgorithm::RsaPss(_) |
6367            ImportKeyAlgorithm::RsaOaep(_) |
6368            ImportKeyAlgorithm::Ecdsa(_) |
6369            ImportKeyAlgorithm::Ecdh(_) |
6370            ImportKeyAlgorithm::Ed25519(_) |
6371            ImportKeyAlgorithm::X25519(_) |
6372            ImportKeyAlgorithm::Ed448(_) |
6373            ImportKeyAlgorithm::X448(_) => true,
6374            ImportKeyAlgorithm::AesCtr(_) |
6375            ImportKeyAlgorithm::AesCbc(_) |
6376            ImportKeyAlgorithm::AesGcm(_) |
6377            ImportKeyAlgorithm::AesKw(_) => !matches!(key_data_length, 128 | 192 | 256),
6378            ImportKeyAlgorithm::Hmac(algorithm) => {
6379                key_data_length == 0 ||
6380                    algorithm.length.is_some_and(|length| {
6381                        length > key_data_length || length + 8 <= key_data_length
6382                    })
6383            },
6384            ImportKeyAlgorithm::Hkdf(_) | ImportKeyAlgorithm::Pbkdf2(_) => false,
6385            ImportKeyAlgorithm::MlKem(_) |
6386            ImportKeyAlgorithm::HybridKem(_) |
6387            ImportKeyAlgorithm::MlDsa(_) => true,
6388            ImportKeyAlgorithm::AesOcb(_) => !matches!(key_data_length, 128 | 192 | 256),
6389            ImportKeyAlgorithm::ChaCha20Poly1305(_) => key_data_length != 256,
6390            ImportKeyAlgorithm::Kmac(algorithm) => algorithm
6391                .length
6392                .is_some_and(|length| length > key_data_length || length + 8 <= key_data_length),
6393            ImportKeyAlgorithm::Argon2(_) => false,
6394        }
6395    }
6396}
6397
6398/// The value of the key "exportKey" in the internal object supportedAlgorithms
6399struct ExportKeyOperation {}
6400
6401impl Operation for ExportKeyOperation {
6402    type RegisteredAlgorithm = ExportKeyAlgorithm;
6403}
6404
6405/// Normalized algorithm for the "exportKey" operation, used as output of
6406/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
6407enum ExportKeyAlgorithm {
6408    RsassaPkcs1V1_5(Algorithm),
6409    RsaPss(Algorithm),
6410    RsaOaep(Algorithm),
6411    Ecdsa(Algorithm),
6412    Ecdh(Algorithm),
6413    Ed25519(Algorithm),
6414    X25519(Algorithm),
6415    Ed448(Algorithm),
6416    X448(Algorithm),
6417    AesCtr(Algorithm),
6418    AesCbc(Algorithm),
6419    AesGcm(Algorithm),
6420    AesKw(Algorithm),
6421    Hmac(Algorithm),
6422    MlKem(Algorithm),
6423    HybridKem(Algorithm),
6424    MlDsa(Algorithm),
6425    AesOcb(Algorithm),
6426    ChaCha20Poly1305(Algorithm),
6427    Kmac(Algorithm),
6428}
6429
6430impl NormalizedAlgorithm for ExportKeyAlgorithm {
6431    fn from_object(
6432        cx: &mut JSContext,
6433        algorithm_name: CryptoAlgorithm,
6434        object: HandleObject,
6435    ) -> Fallible<Self> {
6436        match algorithm_name {
6437            CryptoAlgorithm::RsassaPkcs1V1_5 => Ok(ExportKeyAlgorithm::RsassaPkcs1V1_5(
6438                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6439            )),
6440            CryptoAlgorithm::RsaPss => Ok(ExportKeyAlgorithm::RsaPss(
6441                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6442            )),
6443            CryptoAlgorithm::RsaOaep => Ok(ExportKeyAlgorithm::RsaOaep(
6444                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6445            )),
6446            CryptoAlgorithm::Ecdsa => Ok(ExportKeyAlgorithm::Ecdsa(
6447                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6448            )),
6449            CryptoAlgorithm::Ecdh => Ok(ExportKeyAlgorithm::Ecdh(
6450                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6451            )),
6452            CryptoAlgorithm::Ed25519 => Ok(ExportKeyAlgorithm::Ed25519(
6453                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6454            )),
6455            CryptoAlgorithm::X25519 => Ok(ExportKeyAlgorithm::X25519(
6456                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6457            )),
6458            CryptoAlgorithm::Ed448 => Ok(ExportKeyAlgorithm::Ed448(
6459                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6460            )),
6461            CryptoAlgorithm::X448 => Ok(ExportKeyAlgorithm::X448(
6462                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6463            )),
6464            CryptoAlgorithm::AesCtr => Ok(ExportKeyAlgorithm::AesCtr(
6465                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6466            )),
6467            CryptoAlgorithm::AesCbc => Ok(ExportKeyAlgorithm::AesCbc(
6468                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6469            )),
6470            CryptoAlgorithm::AesGcm => Ok(ExportKeyAlgorithm::AesGcm(
6471                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6472            )),
6473            CryptoAlgorithm::AesKw => Ok(ExportKeyAlgorithm::AesKw(
6474                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6475            )),
6476            CryptoAlgorithm::Hmac => Ok(ExportKeyAlgorithm::Hmac(
6477                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6478            )),
6479            CryptoAlgorithm::MlKem512 | CryptoAlgorithm::MlKem768 | CryptoAlgorithm::MlKem1024 => {
6480                Ok(ExportKeyAlgorithm::MlKem(
6481                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
6482                ))
6483            },
6484            CryptoAlgorithm::MlKem768X25519 => Ok(ExportKeyAlgorithm::HybridKem(
6485                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6486            )),
6487            CryptoAlgorithm::MlDsa44 | CryptoAlgorithm::MlDsa65 | CryptoAlgorithm::MlDsa87 => Ok(
6488                ExportKeyAlgorithm::MlDsa(object.try_into_with_cx_and_name(cx, algorithm_name)?),
6489            ),
6490            CryptoAlgorithm::AesOcb => Ok(ExportKeyAlgorithm::AesOcb(
6491                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6492            )),
6493            CryptoAlgorithm::ChaCha20Poly1305 => Ok(ExportKeyAlgorithm::ChaCha20Poly1305(
6494                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6495            )),
6496            CryptoAlgorithm::Kmac128 | CryptoAlgorithm::Kmac256 => Ok(ExportKeyAlgorithm::Kmac(
6497                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6498            )),
6499            _ => Err(Error::NotSupported(Some(format!(
6500                "{} does not support \"exportKey\" operation",
6501                algorithm_name.as_str()
6502            )))),
6503        }
6504    }
6505
6506    fn name(&self) -> CryptoAlgorithm {
6507        match self {
6508            ExportKeyAlgorithm::RsassaPkcs1V1_5(algorithm) => algorithm.name,
6509            ExportKeyAlgorithm::RsaPss(algorithm) => algorithm.name,
6510            ExportKeyAlgorithm::RsaOaep(algorithm) => algorithm.name,
6511            ExportKeyAlgorithm::Ecdsa(algorithm) => algorithm.name,
6512            ExportKeyAlgorithm::Ecdh(algorithm) => algorithm.name,
6513            ExportKeyAlgorithm::Ed25519(algorithm) => algorithm.name,
6514            ExportKeyAlgorithm::X25519(algorithm) => algorithm.name,
6515            ExportKeyAlgorithm::Ed448(algorithm) => algorithm.name,
6516            ExportKeyAlgorithm::X448(algorithm) => algorithm.name,
6517            ExportKeyAlgorithm::AesCtr(algorithm) => algorithm.name,
6518            ExportKeyAlgorithm::AesCbc(algorithm) => algorithm.name,
6519            ExportKeyAlgorithm::AesGcm(algorithm) => algorithm.name,
6520            ExportKeyAlgorithm::AesKw(algorithm) => algorithm.name,
6521            ExportKeyAlgorithm::Hmac(algorithm) => algorithm.name,
6522            ExportKeyAlgorithm::MlKem(algorithm) => algorithm.name,
6523            ExportKeyAlgorithm::HybridKem(algorithm) => algorithm.name,
6524            ExportKeyAlgorithm::MlDsa(algorithm) => algorithm.name,
6525            ExportKeyAlgorithm::AesOcb(algorithm) => algorithm.name,
6526            ExportKeyAlgorithm::ChaCha20Poly1305(algorithm) => algorithm.name,
6527            ExportKeyAlgorithm::Kmac(algorithm) => algorithm.name,
6528        }
6529    }
6530
6531    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
6532        match self {
6533            ExportKeyAlgorithm::RsassaPkcs1V1_5(_) |
6534            ExportKeyAlgorithm::RsaPss(_) |
6535            ExportKeyAlgorithm::RsaOaep(_) |
6536            ExportKeyAlgorithm::Ecdsa(_) |
6537            ExportKeyAlgorithm::Ecdh(_) |
6538            ExportKeyAlgorithm::Ed25519(_) |
6539            ExportKeyAlgorithm::X25519(_) |
6540            ExportKeyAlgorithm::Ed448(_) |
6541            ExportKeyAlgorithm::X448(_) |
6542            ExportKeyAlgorithm::AesCtr(_) |
6543            ExportKeyAlgorithm::AesCbc(_) |
6544            ExportKeyAlgorithm::AesGcm(_) |
6545            ExportKeyAlgorithm::AesKw(_) |
6546            ExportKeyAlgorithm::Hmac(_) |
6547            ExportKeyAlgorithm::MlKem(_) |
6548            ExportKeyAlgorithm::HybridKem(_) |
6549            ExportKeyAlgorithm::MlDsa(_) |
6550            ExportKeyAlgorithm::AesOcb(_) |
6551            ExportKeyAlgorithm::ChaCha20Poly1305(_) |
6552            ExportKeyAlgorithm::Kmac(_) => true,
6553        }
6554    }
6555}
6556
6557impl ExportKeyAlgorithm {
6558    fn export_key<D: Equivalence>(
6559        &self,
6560        format: KeyFormat,
6561        key: &CryptoKey<D>,
6562    ) -> Result<ExportedKey, Error> {
6563        match self {
6564            ExportKeyAlgorithm::RsassaPkcs1V1_5(_algorithm) => {
6565                rsassa_pkcs1_v1_5_operation::export_key(format, key)
6566            },
6567            ExportKeyAlgorithm::RsaPss(_algorithm) => rsa_pss_operation::export_key(format, key),
6568            ExportKeyAlgorithm::RsaOaep(_algorithm) => rsa_oaep_operation::export_key(format, key),
6569            ExportKeyAlgorithm::Ecdsa(_algorithm) => ecdsa_operation::export_key(format, key),
6570            ExportKeyAlgorithm::Ecdh(_algorithm) => ecdh_operation::export_key(format, key),
6571            ExportKeyAlgorithm::Ed25519(_algorithm) => ed25519_operation::export_key(format, key),
6572            ExportKeyAlgorithm::X25519(_algorithm) => x25519_operation::export_key(format, key),
6573            ExportKeyAlgorithm::Ed448(_algorithm) => ed448_operation::export_key(format, key),
6574            ExportKeyAlgorithm::X448(_algorithm) => x448_operation::export_key(format, key),
6575            ExportKeyAlgorithm::AesCtr(_algorithm) => aes_ctr_operation::export_key(format, key),
6576            ExportKeyAlgorithm::AesCbc(_algorithm) => aes_cbc_operation::export_key(format, key),
6577            ExportKeyAlgorithm::AesGcm(_algorithm) => aes_gcm_operation::export_key(format, key),
6578            ExportKeyAlgorithm::AesKw(_algorithm) => aes_kw_operation::export_key(format, key),
6579            ExportKeyAlgorithm::Hmac(_algorithm) => hmac_operation::export_key(format, key),
6580            ExportKeyAlgorithm::MlKem(_algorithm) => ml_kem_operation::export_key(format, key),
6581            ExportKeyAlgorithm::HybridKem(_algorithm) => {
6582                hybrid_kem_operation::export_key(format, key)
6583            },
6584            ExportKeyAlgorithm::MlDsa(_algorithm) => ml_dsa_operation::export_key(format, key),
6585            ExportKeyAlgorithm::AesOcb(_algorithm) => aes_ocb_operation::export_key(format, key),
6586            ExportKeyAlgorithm::ChaCha20Poly1305(_algorithm) => {
6587                chacha20_poly1305_operation::export_key(format, key)
6588            },
6589            ExportKeyAlgorithm::Kmac(_algorithm) => kmac_operation::export_key(format, key),
6590        }
6591    }
6592}
6593
6594/// The value of the key "get key length" in the internal object supportedAlgorithms
6595struct GetKeyLengthOperation {}
6596
6597impl Operation for GetKeyLengthOperation {
6598    type RegisteredAlgorithm = GetKeyLengthAlgorithm;
6599}
6600
6601/// Normalized algorithm for the "get key length" operation, used as output of
6602/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
6603enum GetKeyLengthAlgorithm {
6604    AesCtr(AesDerivedKeyParams),
6605    AesCbc(AesDerivedKeyParams),
6606    AesGcm(AesDerivedKeyParams),
6607    AesKw(AesDerivedKeyParams),
6608    Hmac(HmacImportParams),
6609    Hkdf(Algorithm),
6610    Pbkdf2(Algorithm),
6611    AesOcb(AesDerivedKeyParams),
6612    ChaCha20Poly1305(Algorithm),
6613    Kmac(KmacImportParams),
6614    Argon2(Algorithm),
6615}
6616
6617impl NormalizedAlgorithm for GetKeyLengthAlgorithm {
6618    fn from_object(
6619        cx: &mut JSContext,
6620        algorithm_name: CryptoAlgorithm,
6621        object: HandleObject,
6622    ) -> Fallible<Self> {
6623        match algorithm_name {
6624            CryptoAlgorithm::AesCtr => Ok(GetKeyLengthAlgorithm::AesCtr(
6625                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6626            )),
6627            CryptoAlgorithm::AesCbc => Ok(GetKeyLengthAlgorithm::AesCbc(
6628                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6629            )),
6630            CryptoAlgorithm::AesGcm => Ok(GetKeyLengthAlgorithm::AesGcm(
6631                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6632            )),
6633            CryptoAlgorithm::AesKw => Ok(GetKeyLengthAlgorithm::AesKw(
6634                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6635            )),
6636            CryptoAlgorithm::Hmac => Ok(GetKeyLengthAlgorithm::Hmac(
6637                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6638            )),
6639            CryptoAlgorithm::Hkdf => Ok(GetKeyLengthAlgorithm::Hkdf(
6640                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6641            )),
6642            CryptoAlgorithm::Pbkdf2 => Ok(GetKeyLengthAlgorithm::Pbkdf2(
6643                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6644            )),
6645            CryptoAlgorithm::AesOcb => Ok(GetKeyLengthAlgorithm::AesOcb(
6646                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6647            )),
6648            CryptoAlgorithm::ChaCha20Poly1305 => Ok(GetKeyLengthAlgorithm::ChaCha20Poly1305(
6649                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6650            )),
6651            CryptoAlgorithm::Kmac128 | CryptoAlgorithm::Kmac256 => Ok(GetKeyLengthAlgorithm::Kmac(
6652                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6653            )),
6654            CryptoAlgorithm::Argon2D | CryptoAlgorithm::Argon2I | CryptoAlgorithm::Argon2ID => {
6655                Ok(GetKeyLengthAlgorithm::Argon2(
6656                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
6657                ))
6658            },
6659            _ => Err(Error::NotSupported(Some(format!(
6660                "{} does not support \"get key length\" operation",
6661                algorithm_name.as_str()
6662            )))),
6663        }
6664    }
6665
6666    fn name(&self) -> CryptoAlgorithm {
6667        match self {
6668            GetKeyLengthAlgorithm::AesCtr(algorithm) => algorithm.name,
6669            GetKeyLengthAlgorithm::AesCbc(algorithm) => algorithm.name,
6670            GetKeyLengthAlgorithm::AesGcm(algorithm) => algorithm.name,
6671            GetKeyLengthAlgorithm::AesKw(algorithm) => algorithm.name,
6672            GetKeyLengthAlgorithm::Hmac(algorithm) => algorithm.name,
6673            GetKeyLengthAlgorithm::Hkdf(algorithm) => algorithm.name,
6674            GetKeyLengthAlgorithm::Pbkdf2(algorithm) => algorithm.name,
6675            GetKeyLengthAlgorithm::AesOcb(algorithm) => algorithm.name,
6676            GetKeyLengthAlgorithm::ChaCha20Poly1305(algorithm) => algorithm.name,
6677            GetKeyLengthAlgorithm::Kmac(algorithm) => algorithm.name,
6678            GetKeyLengthAlgorithm::Argon2(algorithm) => algorithm.name,
6679        }
6680    }
6681
6682    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
6683        match self {
6684            GetKeyLengthAlgorithm::AesCtr(normalized_derived_key_algorithm) |
6685            GetKeyLengthAlgorithm::AesCbc(normalized_derived_key_algorithm) |
6686            GetKeyLengthAlgorithm::AesGcm(normalized_derived_key_algorithm) |
6687            GetKeyLengthAlgorithm::AesKw(normalized_derived_key_algorithm) => {
6688                matches!(normalized_derived_key_algorithm.length, 128 | 192 | 256)
6689            },
6690            GetKeyLengthAlgorithm::Hmac(normalized_derived_key_algorithm) => {
6691                normalized_derived_key_algorithm
6692                    .length
6693                    .is_none_or(|length| length != 0)
6694            },
6695            GetKeyLengthAlgorithm::Hkdf(_) | GetKeyLengthAlgorithm::Pbkdf2(_) => true,
6696            GetKeyLengthAlgorithm::AesOcb(normalized_derived_key_algorithm) => {
6697                matches!(normalized_derived_key_algorithm.length, 128 | 192 | 256)
6698            },
6699            GetKeyLengthAlgorithm::ChaCha20Poly1305(_) |
6700            GetKeyLengthAlgorithm::Kmac(_) |
6701            GetKeyLengthAlgorithm::Argon2(_) => true,
6702        }
6703    }
6704}
6705
6706impl GetKeyLengthAlgorithm {
6707    fn get_key_length(&self) -> Result<Option<u32>, Error> {
6708        match self {
6709            GetKeyLengthAlgorithm::AesCtr(algorithm) => {
6710                aes_ctr_operation::get_key_length(algorithm)
6711            },
6712            GetKeyLengthAlgorithm::AesCbc(algorithm) => {
6713                aes_cbc_operation::get_key_length(algorithm)
6714            },
6715            GetKeyLengthAlgorithm::AesGcm(algorithm) => {
6716                aes_gcm_operation::get_key_length(algorithm)
6717            },
6718            GetKeyLengthAlgorithm::AesKw(algorithm) => aes_kw_operation::get_key_length(algorithm),
6719            GetKeyLengthAlgorithm::Hmac(algorithm) => hmac_operation::get_key_length(algorithm),
6720            GetKeyLengthAlgorithm::Hkdf(_algorithm) => hkdf_operation::get_key_length(),
6721            GetKeyLengthAlgorithm::Pbkdf2(_algorithm) => pbkdf2_operation::get_key_length(),
6722            GetKeyLengthAlgorithm::AesOcb(algorithm) => {
6723                aes_ocb_operation::get_key_length(algorithm)
6724            },
6725            GetKeyLengthAlgorithm::ChaCha20Poly1305(_algorithm) => {
6726                chacha20_poly1305_operation::get_key_length()
6727            },
6728            GetKeyLengthAlgorithm::Kmac(algorithm) => kmac_operation::get_key_length(algorithm),
6729            GetKeyLengthAlgorithm::Argon2(_algorithm) => argon2_operation::get_key_length(),
6730        }
6731    }
6732}
6733
6734/// The value of the key "encapsulate" in the internal object supportedAlgorithms
6735struct EncapsulateOperation {}
6736
6737impl Operation for EncapsulateOperation {
6738    type RegisteredAlgorithm = EncapsulateAlgorithm;
6739}
6740
6741/// Normalized algorithm for the "encapsulate" operation, used as output of
6742/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
6743enum EncapsulateAlgorithm {
6744    MlKem(Algorithm),
6745    HybridKem(Algorithm),
6746}
6747
6748impl NormalizedAlgorithm for EncapsulateAlgorithm {
6749    fn from_object(
6750        cx: &mut JSContext,
6751        algorithm_name: CryptoAlgorithm,
6752        object: HandleObject,
6753    ) -> Fallible<Self> {
6754        match algorithm_name {
6755            CryptoAlgorithm::MlKem512 | CryptoAlgorithm::MlKem768 | CryptoAlgorithm::MlKem1024 => {
6756                Ok(EncapsulateAlgorithm::MlKem(
6757                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
6758                ))
6759            },
6760            CryptoAlgorithm::MlKem768X25519 => Ok(EncapsulateAlgorithm::HybridKem(
6761                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6762            )),
6763            _ => Err(Error::NotSupported(Some(format!(
6764                "{} does not support \"encapsulate\" operation",
6765                algorithm_name.as_str()
6766            )))),
6767        }
6768    }
6769
6770    fn name(&self) -> CryptoAlgorithm {
6771        match self {
6772            EncapsulateAlgorithm::MlKem(algorithm) => algorithm.name,
6773            EncapsulateAlgorithm::HybridKem(algorithm) => algorithm.name,
6774        }
6775    }
6776
6777    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
6778        match self {
6779            EncapsulateAlgorithm::MlKem(_) | EncapsulateAlgorithm::HybridKem(_) => true,
6780        }
6781    }
6782}
6783
6784impl EncapsulateAlgorithm {
6785    fn encapsulate<D: Equivalence>(&self, key: &CryptoKey<D>) -> Result<EncapsulatedBits, Error> {
6786        match self {
6787            EncapsulateAlgorithm::MlKem(algorithm) => ml_kem_operation::encapsulate(algorithm, key),
6788            EncapsulateAlgorithm::HybridKem(algorithm) => {
6789                hybrid_kem_operation::encapsulate(algorithm, key)
6790            },
6791        }
6792    }
6793}
6794
6795/// The value of the key "decapsulate" in the internal object supportedAlgorithms
6796struct DecapsulateOperation {}
6797
6798impl Operation for DecapsulateOperation {
6799    type RegisteredAlgorithm = DecapsulateAlgorithm;
6800}
6801
6802/// Normalized algorithm for the "decapsulate" operation, used as output of
6803/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
6804enum DecapsulateAlgorithm {
6805    MlKem(Algorithm),
6806    HybridKem(Algorithm),
6807}
6808
6809impl NormalizedAlgorithm for DecapsulateAlgorithm {
6810    fn from_object(
6811        cx: &mut JSContext,
6812        algorithm_name: CryptoAlgorithm,
6813        object: HandleObject,
6814    ) -> Fallible<Self> {
6815        match algorithm_name {
6816            CryptoAlgorithm::MlKem512 | CryptoAlgorithm::MlKem768 | CryptoAlgorithm::MlKem1024 => {
6817                Ok(DecapsulateAlgorithm::MlKem(
6818                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
6819                ))
6820            },
6821            CryptoAlgorithm::MlKem768X25519 => Ok(DecapsulateAlgorithm::HybridKem(
6822                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6823            )),
6824            _ => Err(Error::NotSupported(Some(format!(
6825                "{} does not support \"decapsulate\" operation",
6826                algorithm_name.as_str()
6827            )))),
6828        }
6829    }
6830
6831    fn name(&self) -> CryptoAlgorithm {
6832        match self {
6833            DecapsulateAlgorithm::MlKem(algorithm) => algorithm.name,
6834            DecapsulateAlgorithm::HybridKem(algorithm) => algorithm.name,
6835        }
6836    }
6837
6838    fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
6839        match self {
6840            DecapsulateAlgorithm::MlKem(_) | DecapsulateAlgorithm::HybridKem(_) => true,
6841        }
6842    }
6843}
6844
6845impl DecapsulateAlgorithm {
6846    fn decapsulate<D: Equivalence>(
6847        &self,
6848        key: &CryptoKey<D>,
6849        ciphertext: &[u8],
6850    ) -> Result<Vec<u8>, Error> {
6851        match self {
6852            DecapsulateAlgorithm::MlKem(algorithm) => {
6853                ml_kem_operation::decapsulate(algorithm, key, ciphertext)
6854            },
6855            DecapsulateAlgorithm::HybridKem(algorithm) => {
6856                hybrid_kem_operation::decapsulate(algorithm, key, ciphertext)
6857            },
6858        }
6859    }
6860}
6861
6862/// The value of the key "get shared key length" in the internal object supportedAlgorithms
6863struct GetSharedKeyLengthOperation {}
6864
6865impl Operation for GetSharedKeyLengthOperation {
6866    type RegisteredAlgorithm = GetSharedKeyLengthAlgorithm;
6867}
6868
6869/// Normalized algorithm for the "get shared key length" operation, used as output of
6870/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
6871enum GetSharedKeyLengthAlgorithm {
6872    MlKem(Algorithm),
6873    HybridKem(Algorithm),
6874}
6875
6876impl NormalizedAlgorithm for GetSharedKeyLengthAlgorithm {
6877    fn from_object(
6878        cx: &mut JSContext,
6879        algorithm_name: CryptoAlgorithm,
6880        object: HandleObject,
6881    ) -> Fallible<Self> {
6882        match algorithm_name {
6883            CryptoAlgorithm::MlKem512 | CryptoAlgorithm::MlKem768 | CryptoAlgorithm::MlKem1024 => {
6884                Ok(GetSharedKeyLengthAlgorithm::MlKem(
6885                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
6886                ))
6887            },
6888            CryptoAlgorithm::MlKem768X25519 => Ok(GetSharedKeyLengthAlgorithm::HybridKem(
6889                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6890            )),
6891            _ => Err(Error::NotSupported(Some(format!(
6892                "{} does not support \"get shared key length\" operation",
6893                algorithm_name.as_str()
6894            )))),
6895        }
6896    }
6897
6898    fn name(&self) -> CryptoAlgorithm {
6899        match self {
6900            GetSharedKeyLengthAlgorithm::MlKem(algorithm) => algorithm.name,
6901            GetSharedKeyLengthAlgorithm::HybridKem(algorithm) => algorithm.name,
6902        }
6903    }
6904}
6905
6906impl GetSharedKeyLengthAlgorithm {
6907    fn get_shared_key_length(&self) -> u32 {
6908        match self {
6909            GetSharedKeyLengthAlgorithm::MlKem(_algorithm) => {
6910                ml_kem_operation::get_shared_key_length()
6911            },
6912            GetSharedKeyLengthAlgorithm::HybridKem(_algorithm) => {
6913                hybrid_kem_operation::get_shared_key_length()
6914            },
6915        }
6916    }
6917}
6918
6919/// The value of the key "getPublicKey" in the internal object supportedAlgorithms
6920struct GetPublicKeyOperation {}
6921
6922impl Operation for GetPublicKeyOperation {
6923    type RegisteredAlgorithm = GetPublicKeyAlgorithm;
6924}
6925
6926/// Normalized algorithm for the "getPublicKey" operation, used as output of
6927/// <https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm>
6928enum GetPublicKeyAlgorithm {
6929    RsassaPkcs1v1_5(Algorithm),
6930    RsaPss(Algorithm),
6931    RsaOaep(Algorithm),
6932    Ecdsa(Algorithm),
6933    Ecdh(Algorithm),
6934    Ed25519(Algorithm),
6935    X25519(Algorithm),
6936    Ed448(Algorithm),
6937    X448(Algorithm),
6938    MlKem(Algorithm),
6939    HybridKem(Algorithm),
6940    MlDsa(Algorithm),
6941}
6942
6943impl NormalizedAlgorithm for GetPublicKeyAlgorithm {
6944    fn from_object(
6945        cx: &mut JSContext,
6946        algorithm_name: CryptoAlgorithm,
6947        object: HandleObject,
6948    ) -> Fallible<Self> {
6949        match algorithm_name {
6950            CryptoAlgorithm::RsassaPkcs1V1_5 => Ok(GetPublicKeyAlgorithm::RsassaPkcs1v1_5(
6951                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6952            )),
6953            CryptoAlgorithm::RsaPss => Ok(GetPublicKeyAlgorithm::RsaPss(
6954                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6955            )),
6956            CryptoAlgorithm::RsaOaep => Ok(GetPublicKeyAlgorithm::RsaOaep(
6957                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6958            )),
6959            CryptoAlgorithm::Ecdsa => Ok(GetPublicKeyAlgorithm::Ecdsa(
6960                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6961            )),
6962            CryptoAlgorithm::Ecdh => Ok(GetPublicKeyAlgorithm::Ecdh(
6963                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6964            )),
6965            CryptoAlgorithm::Ed25519 => Ok(GetPublicKeyAlgorithm::Ed25519(
6966                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6967            )),
6968            CryptoAlgorithm::X25519 => Ok(GetPublicKeyAlgorithm::X25519(
6969                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6970            )),
6971            CryptoAlgorithm::Ed448 => Ok(GetPublicKeyAlgorithm::Ed448(
6972                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6973            )),
6974            CryptoAlgorithm::X448 => Ok(GetPublicKeyAlgorithm::X448(
6975                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6976            )),
6977            CryptoAlgorithm::MlKem512 | CryptoAlgorithm::MlKem768 | CryptoAlgorithm::MlKem1024 => {
6978                Ok(GetPublicKeyAlgorithm::MlKem(
6979                    object.try_into_with_cx_and_name(cx, algorithm_name)?,
6980                ))
6981            },
6982            CryptoAlgorithm::MlKem768X25519 => Ok(GetPublicKeyAlgorithm::HybridKem(
6983                object.try_into_with_cx_and_name(cx, algorithm_name)?,
6984            )),
6985            CryptoAlgorithm::MlDsa44 | CryptoAlgorithm::MlDsa65 | CryptoAlgorithm::MlDsa87 => Ok(
6986                GetPublicKeyAlgorithm::MlDsa(object.try_into_with_cx_and_name(cx, algorithm_name)?),
6987            ),
6988            _ => Err(Error::NotSupported(Some(format!(
6989                "{} does not support \"getPublicKey\" operation",
6990                algorithm_name.as_str()
6991            )))),
6992        }
6993    }
6994
6995    fn name(&self) -> CryptoAlgorithm {
6996        match self {
6997            GetPublicKeyAlgorithm::RsassaPkcs1v1_5(algorithm) => algorithm.name,
6998            GetPublicKeyAlgorithm::RsaPss(algorithm) => algorithm.name,
6999            GetPublicKeyAlgorithm::RsaOaep(algorithm) => algorithm.name,
7000            GetPublicKeyAlgorithm::Ecdsa(algorithm) => algorithm.name,
7001            GetPublicKeyAlgorithm::Ecdh(algorithm) => algorithm.name,
7002            GetPublicKeyAlgorithm::Ed25519(algorithm) => algorithm.name,
7003            GetPublicKeyAlgorithm::X25519(algorithm) => algorithm.name,
7004            GetPublicKeyAlgorithm::Ed448(algorithm) => algorithm.name,
7005            GetPublicKeyAlgorithm::X448(algorithm) => algorithm.name,
7006            GetPublicKeyAlgorithm::MlKem(algorithm) => algorithm.name,
7007            GetPublicKeyAlgorithm::HybridKem(algorithm) => algorithm.name,
7008            GetPublicKeyAlgorithm::MlDsa(algorithm) => algorithm.name,
7009        }
7010    }
7011}
7012
7013impl GetPublicKeyAlgorithm {
7014    fn get_public_key<D: Equivalence>(
7015        &self,
7016        cx: &mut JSContext,
7017        global: &D::GlobalScope,
7018        key: &CryptoKey<D>,
7019        algorithm: &KeyAlgorithmAndDerivatives,
7020        usages: Vec<KeyUsage>,
7021    ) -> Result<DomRoot<CryptoKey<D>>, Error> {
7022        match self {
7023            GetPublicKeyAlgorithm::RsassaPkcs1v1_5(_algorithm) => {
7024                rsassa_pkcs1_v1_5_operation::get_public_key(cx, global, key, algorithm, usages)
7025            },
7026            GetPublicKeyAlgorithm::RsaPss(_algorithm) => {
7027                rsa_pss_operation::get_public_key(cx, global, key, algorithm, usages)
7028            },
7029            GetPublicKeyAlgorithm::RsaOaep(_algorithm) => {
7030                rsa_oaep_operation::get_public_key(cx, global, key, algorithm, usages)
7031            },
7032            GetPublicKeyAlgorithm::Ecdsa(_algorithm) => {
7033                ecdsa_operation::get_public_key(cx, global, key, algorithm, usages)
7034            },
7035            GetPublicKeyAlgorithm::Ecdh(_algorithm) => {
7036                ecdh_operation::get_public_key(cx, global, key, algorithm, usages)
7037            },
7038            GetPublicKeyAlgorithm::Ed25519(_algorithm) => {
7039                ed25519_operation::get_public_key(cx, global, key, algorithm, usages)
7040            },
7041            GetPublicKeyAlgorithm::X25519(_algorithm) => {
7042                x25519_operation::get_public_key(cx, global, key, algorithm, usages)
7043            },
7044            GetPublicKeyAlgorithm::Ed448(_algorithm) => {
7045                ed448_operation::get_public_key(cx, global, key, algorithm, usages)
7046            },
7047            GetPublicKeyAlgorithm::X448(_algorithm) => {
7048                x448_operation::get_public_key(cx, global, key, algorithm, usages)
7049            },
7050            GetPublicKeyAlgorithm::MlKem(_algorithm) => {
7051                ml_kem_operation::get_public_key(cx, global, key, algorithm, usages)
7052            },
7053            GetPublicKeyAlgorithm::HybridKem(_algorithm) => {
7054                hybrid_kem_operation::get_public_key(cx, global, key, algorithm, usages)
7055            },
7056            GetPublicKeyAlgorithm::MlDsa(_algorithm) => {
7057                ml_dsa_operation::get_public_key(cx, global, key, algorithm, usages)
7058            },
7059        }
7060    }
7061}