1mod 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
95const 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 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#[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 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 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 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 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 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 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 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 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 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 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 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 let data = Zeroizing::new(get_buffer_source_copy((&data).into()));
438
439 let promise = D::Promise::new_in_realm(cx);
442
443 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 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 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 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 subtle.resolve_promise_with_data(promise, ciphertext.into());
494 }));
495 promise
496 }
497
498 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 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 let data = get_buffer_source_copy((&data).into());
525
526 let promise = D::Promise::new_in_realm(cx);
529
530 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 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 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 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 subtle.resolve_promise_with_data(promise, plaintext);
580 }));
581 promise
582 }
583
584 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 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 let data = get_buffer_source_copy((&data).into());
611
612 let promise = D::Promise::new_in_realm(cx);
615
616 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 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 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 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 subtle.resolve_promise_with_data(promise, signature.into());
665 }));
666 promise
667 }
668
669 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 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 let signature = get_buffer_source_copy((&signature).into());
697
698 let data = get_buffer_source_copy((&data).into());
701
702 let promise = D::Promise::new_in_realm(cx);
705
706 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 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 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 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 subtle.resolve_promise_with_bool(promise, result);
754 }));
755 promise
756 }
757
758 fn Digest(
760 &self,
761 cx: &mut CurrentRealm,
762 algorithm: AlgorithmIdentifier,
763 data: ArrayBufferViewOrArrayBuffer,
764 ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
765 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 let data = get_buffer_source_copy((&data).into());
783
784 let promise = D::Promise::new_in_realm(cx);
787
788 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 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 subtle.resolve_promise_with_data(promise, digest.into());
816 }));
817 promise
818 }
819
820 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 subtle.resolve_promise_with_key(promise, &result);
1078 }),
1079 );
1080 promise
1081 }
1082
1083 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 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 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 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 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 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 subtle.resolve_promise_with_data(promise, bits);
1161 }));
1162 promise
1163 }
1164
1165 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 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 let key_data = match format {
1192 KeyFormat::Jwk => {
1194 match key_data {
1195 ArrayBufferViewOrArrayBufferOrJsonWebKey::ArrayBufferView(_) |
1196 ArrayBufferViewOrArrayBufferOrJsonWebKey::ArrayBuffer(_) => {
1197 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 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 _ => {
1230 match &key_data {
1231 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 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 let promise = D::Promise::new_in_realm(cx);
1257
1258 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 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 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 subtle.resolve_promise_with_key(promise, &result);
1310 }));
1311
1312 promise
1313 }
1314
1315 fn ExportKey(
1317 &self,
1318 cx: &mut CurrentRealm,
1319 format: KeyFormat,
1320 key: &CryptoKey<D>,
1321 ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
1322 let promise = D::Promise::new_in_realm(cx);
1329
1330 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 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 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 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 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 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 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 let promise = D::Promise::new_in_realm(cx);
1444
1445 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 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 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 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 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 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 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 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 subtle.resolve_promise_with_data(promise, result.into());
1581 }));
1582 promise
1583 }
1584
1585 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 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 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 let wrapped_key = get_buffer_source_copy((&wrapped_key).into());
1642
1643 let promise = D::Promise::new_in_realm(cx);
1646
1647 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 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 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 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 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 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 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 subtle.resolve_promise_with_key(promise, &result);
1773 }));
1774 promise
1775 }
1776
1777 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 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 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 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 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 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 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 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 if usages.is_empty() {
1904 subtle.reject_promise_with_error(promise, Error::Syntax(Some(
1905 "Usages is empty".into())));
1906 return;
1907 }
1908
1909 let encapsulated_key = EncapsulatedKey {
1917 shared_key: Some(Trusted::new(&shared_key)),
1918 ciphertext:encapsulated_bits.ciphertext,
1919 };
1920
1921 subtle.resolve_promise_with_encapsulated_key(promise, encapsulated_key);
1927 })
1928 );
1929 promise
1930 }
1931
1932 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 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 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 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 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 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 subtle.resolve_promise_with_encapsulated_bits(promise, encapsulated_bits);
2015 }),
2016 );
2017 promise
2018 }
2019
2020 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 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 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 let ciphertext = get_buffer_source_copy((&ciphertext).into());
2067
2068 let promise = D::Promise::new_in_realm(cx);
2071
2072 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 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 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 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 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 if usages.is_empty() {
2145 subtle.reject_promise_with_error(promise, Error::Syntax(Some(
2146 "Usages is empty".into())));
2147 return;
2148 }
2149
2150 subtle.resolve_promise_with_key(promise, &shared_key);
2161 }));
2162 promise
2163 }
2164
2165 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 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 let ciphertext = get_buffer_source_copy((&ciphertext).into());
2193
2194 let promise = D::Promise::new_in_realm(cx);
2197
2198 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 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 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 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 subtle.resolve_promise_with_data(promise, decapsulated_bits);
2254 }));
2255 promise
2256 }
2257
2258 fn GetPublicKey(
2260 &self,
2261 cx: &mut CurrentRealm,
2262 key: &CryptoKey<D>,
2263 usages: Vec<KeyUsage>,
2264 ) -> <D::Promise as PromiseHelpers<D>>::StackRoot {
2265 let algorithm = key.algorithm();
2270
2271 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 let promise = D::Promise::new_in_realm(cx);
2292
2293 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 if let Err(error) = key.ensure_type(KeyType::Private) {
2310 subtle.reject_promise_with_error(promise, error);
2311 return;
2312 }
2313
2314 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 subtle.resolve_promise_with_key(promise, &result);
2347 }));
2348 promise
2349 }
2350
2351 fn Supports(
2353 cx: &mut JSContext,
2354 _global: &D::GlobalScope,
2355 operation: DOMString,
2356 algorithm: AlgorithmIdentifier,
2357 length: Option<u32>,
2358 ) -> bool {
2359 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 check_support_for_algorithm::<D>(cx, operation, &algorithm, length)
2390 }
2391
2392 fn Supports_(
2394 cx: &mut JSContext,
2395 _global: &D::GlobalScope,
2396 operation: DOMString,
2397 algorithm: AlgorithmIdentifier,
2398 additional_algorithm: AlgorithmIdentifier,
2399 ) -> bool {
2400 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 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 if matches!(operation, "encapsulateKey" | "decapsulateKey") {
2448 let Ok(normalized_algorithm) =
2452 normalize_algorithm::<GetSharedKeyLengthOperation>(cx, &algorithm)
2453 else {
2454 return false;
2455 };
2456
2457 let shared_key_length = normalized_algorithm.get_shared_key_length();
2460
2461 let Ok(normalized_additional_algorithm) =
2465 normalize_algorithm::<ImportKeyOperation>(cx, &additional_algorithm)
2466 else {
2467 return false;
2468 };
2469
2470 if !normalized_additional_algorithm.determine_support_from_operation_steps(None) {
2478 return false;
2479 }
2480
2481 if normalized_additional_algorithm.will_throw_for_key_data_length(shared_key_length) {
2485 return false;
2486 }
2487 }
2488
2489 let mut length = None;
2491
2492 if operation == "deriveKey" {
2494 if !check_support_for_algorithm::<D>(cx, "get key length", &additional_algorithm, None)
2497 {
2498 return false;
2499 }
2500
2501 let Ok(normalized_additional_algorithm) =
2504 normalize_algorithm::<GetKeyLengthOperation>(cx, &additional_algorithm)
2505 else {
2506 return false;
2507 };
2508
2509 match normalized_additional_algorithm.get_key_length() {
2512 Ok(key_length) => {
2513 length = key_length;
2514 },
2515 Err(_) => return false,
2516 };
2517
2518 operation = "deriveBits";
2520 }
2521
2522 check_support_for_algorithm::<D>(cx, operation, &algorithm, length)
2525 }
2526}
2527
2528fn check_support_for_algorithm<D: Equivalence>(
2530 cx: &mut JSContext,
2531 mut operation: &str,
2532 algorithm: &AlgorithmIdentifier,
2533 length: Option<u32>,
2534) -> bool {
2535 if operation == "encapsulateKey" || operation == "encapsulateBits" {
2537 operation = "encapsulate";
2538 }
2539
2540 if operation == "decapsulateKey" || operation == "decapsulateBits" {
2542 operation = "decapsulate";
2543 }
2544
2545 if operation == "getPublicKey" {
2547 let Ok(normalized_algorithm) = normalize_algorithm::<ExportKeyOperation>(cx, algorithm)
2551 else {
2552 return false;
2553 };
2554
2555 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 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
2627fn 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
2646trait 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
2657trait 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#[derive(Clone, MallocSizeOf)]
2703struct Algorithm {
2704 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#[derive(Clone, MallocSizeOf)]
2742pub(crate) struct KeyAlgorithm {
2743 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#[derive(Clone, MallocSizeOf)]
2780pub(crate) struct RsaHashedKeyGenParams {
2781 name: CryptoAlgorithm,
2783
2784 modulus_length: u32,
2786
2787 public_exponent: Vec<u8>,
2789
2790 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 fn validate_parameters(&self) -> Result<(), Error> {
2828 let modulus_length = self.modulus_length;
2830
2831 let public_exponent = &self.public_exponent;
2834
2835 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#[derive(Clone, MallocSizeOf)]
2877pub(crate) struct RsaHashedKeyAlgorithm {
2878 name: CryptoAlgorithm,
2880
2881 modulus_length: u32,
2883
2884 public_exponent: Vec<u8>,
2886
2887 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#[derive(Clone, MallocSizeOf)]
2966struct RsaHashedImportParams {
2967 name: CryptoAlgorithm,
2969
2970 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#[derive(Clone, MallocSizeOf)]
2993struct RsaPssParams {
2994 name: CryptoAlgorithm,
2996
2997 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#[derive(Clone, MallocSizeOf)]
3023struct RsaOaepParams {
3024 name: CryptoAlgorithm,
3026
3027 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#[derive(Clone, MallocSizeOf)]
3048struct EcdsaParams {
3049 name: CryptoAlgorithm,
3051
3052 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#[derive(Clone, MallocSizeOf)]
3075struct EcKeyGenParams {
3076 name: CryptoAlgorithm,
3078
3079 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#[derive(Clone, MallocSizeOf)]
3105pub(crate) struct EcKeyAlgorithm {
3106 name: CryptoAlgorithm,
3108
3109 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#[derive(Clone, MallocSizeOf)]
3153struct EcKeyImportParams {
3154 name: CryptoAlgorithm,
3156
3157 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#[derive(Clone, MallocSizeOf)]
3183struct EcdhKeyDeriveParams<D: DomTypes> {
3184 name: CryptoAlgorithm,
3186
3187 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#[derive(Clone, MallocSizeOf)]
3210struct AesCtrParams {
3211 name: CryptoAlgorithm,
3213
3214 counter: Vec<u8>,
3216
3217 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#[derive(Clone, MallocSizeOf)]
3244pub(crate) struct AesKeyAlgorithm {
3245 name: CryptoAlgorithm,
3247
3248 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#[derive(Clone, MallocSizeOf)]
3292struct AesKeyGenParams {
3293 name: CryptoAlgorithm,
3295
3296 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#[derive(Clone, MallocSizeOf)]
3322struct AesDerivedKeyParams {
3323 name: CryptoAlgorithm,
3325
3326 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#[derive(Clone, MallocSizeOf)]
3352struct AesCbcParams {
3353 name: CryptoAlgorithm,
3355
3356 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#[derive(Clone, MallocSizeOf)]
3377struct AesGcmParams {
3378 name: CryptoAlgorithm,
3380
3381 iv: Vec<u8>,
3383
3384 additional_data: Option<Vec<u8>>,
3386
3387 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#[derive(Clone, MallocSizeOf)]
3410struct HmacImportParams {
3411 name: CryptoAlgorithm,
3413
3414 hash: DigestAlgorithm,
3416
3417 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#[derive(Clone, MallocSizeOf)]
3441pub(crate) struct HmacKeyAlgorithm {
3442 name: CryptoAlgorithm,
3444
3445 hash: DigestAlgorithm,
3447
3448 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#[derive(Clone, MallocSizeOf)]
3502struct HmacKeyGenParams {
3503 name: CryptoAlgorithm,
3505
3506 hash: DigestAlgorithm,
3508
3509 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#[derive(Clone, MallocSizeOf)]
3533pub(crate) struct HkdfParams {
3534 name: CryptoAlgorithm,
3536
3537 hash: DigestAlgorithm,
3539
3540 salt: Vec<u8>,
3542
3543 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#[derive(Clone, MallocSizeOf)]
3568pub(crate) struct Pbkdf2Params {
3569 name: CryptoAlgorithm,
3571
3572 salt: Vec<u8>,
3574
3575 iterations: u32,
3577
3578 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#[derive(Clone, MallocSizeOf)]
3608struct ContextParams {
3609 name: CryptoAlgorithm,
3611
3612 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#[derive(Clone, MallocSizeOf)]
3633struct AeadParams {
3634 name: CryptoAlgorithm,
3636
3637 iv: Vec<u8>,
3639
3640 additional_data: Option<Vec<u8>>,
3642
3643 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#[derive(Clone, MallocSizeOf)]
3666struct CShakeParams {
3667 name: CryptoAlgorithm,
3669
3670 output_length: u32,
3672
3673 function_name: Option<Vec<u8>>,
3675
3676 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#[derive(Clone, MallocSizeOf)]
3728struct TurboShakeParams {
3729 name: CryptoAlgorithm,
3731
3732 output_length: u32,
3734
3735 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#[derive(Clone, MallocSizeOf)]
3789struct KangarooTwelveParams {
3790 name: CryptoAlgorithm,
3792
3793 output_length: u32,
3795
3796 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#[derive(Clone, MallocSizeOf)]
3845struct KmacKeyGenParams {
3846 name: CryptoAlgorithm,
3848
3849 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#[derive(Clone, MallocSizeOf)]
3870struct KmacImportParams {
3871 name: CryptoAlgorithm,
3873
3874 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#[derive(Clone, MallocSizeOf)]
3895pub(crate) struct KmacKeyAlgorithm {
3896 name: CryptoAlgorithm,
3898
3899 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
3941struct KmacParams {
3943 name: CryptoAlgorithm,
3945
3946 output_length: u32,
3948
3949 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#[derive(Clone, MallocSizeOf)]
3976struct Argon2Params {
3977 name: CryptoAlgorithm,
3979
3980 nonce: Vec<u8>,
3982
3983 parallelism: u32,
3985
3986 memory: u32,
3988
3989 passes: u32,
3991
3992 version: Option<u8>,
3994
3995 secret_value: Option<Vec<u8>>,
3997
3998 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
4038struct EncapsulatedKey<D: DomTypes> {
4040 shared_key: Option<Trusted<CryptoKey<D>>>,
4042
4043 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
4079struct EncapsulatedBits {
4081 shared_key: Option<Zeroizing<Vec<u8>>>,
4083
4084 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#[derive(Clone, MallocSizeOf)]
4130struct SubtleEd448Params {
4131 name: CryptoAlgorithm,
4133
4134 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
4153fn 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
4164fn 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
4176fn 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
4190fn 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
4202enum 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
4220fn truncate_bit_sequence(bit_sequence: &mut Vec<u8>, length: usize) {
4225 bit_sequence.truncate(length.div_ceil(8));
4226
4227 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
4235fn truncate_keccak_bit_string(bit_string: &mut Vec<u8>, length: usize) {
4240 bit_string.truncate(length.div_ceil(8));
4241
4242 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#[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#[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
4381trait JsonWebKeyHelper {
4383 fn parse(cx: &mut JSContext, data: &[u8]) -> Result<JsonWebKey, Error>;
4385
4386 fn stringify(&self, cx: &mut JSContext) -> Result<Zeroizing<DOMString>, Error>;
4392
4393 fn get_usages_from_key_ops(&self) -> Result<Vec<KeyUsage>, Error>;
4395
4396 fn check_key_ops(&self, specified_usages: &[KeyUsage]) -> Result<(), Error>;
4400
4401 fn set_key_ops(&mut self, usages: &[KeyUsage]);
4403
4404 fn encode_string_field(&mut self, field: JwkStringField, data: &[u8]);
4407
4408 fn decode_optional_string_field(
4411 &self,
4412 field: JwkStringField,
4413 ) -> Result<Option<Zeroizing<Vec<u8>>>, Error>;
4414
4415 fn decode_required_string_field(
4418 &self,
4419 field: JwkStringField,
4420 ) -> Result<Zeroizing<Vec<u8>>, Error>;
4421
4422 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 #[expect(unsafe_code)]
4439 fn parse(cx: &mut JSContext, data: &[u8]) -> Result<JsonWebKey, Error> {
4440 let json = String::from_utf8_lossy(data);
4445
4446 let json: Vec<_> = json.encode_utf16().collect();
4448
4449 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 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 if key.kty.is_none() {
4472 return Err(Error::Data(Some(
4473 "'kty' field of key is not defined".into(),
4474 )));
4475 }
4476
4477 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 let Some(ref key_ops) = self.key_ops {
4503 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 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 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
4673fn normalize_algorithm<Op: Operation>(
4675 cx: &mut JSContext,
4676 algorithm: &AlgorithmIdentifier,
4677) -> Result<Op::RegisteredAlgorithm, Error> {
4678 match algorithm {
4679 AlgorithmIdentifier::String(name) => {
4681 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 AlgorithmIdentifier::Object(object) => {
4698 let algorithm_name = get_required_parameter::<DOMString>(
4706 cx,
4707 object.handle(),
4708 c"name",
4709 StringificationBehavior::Default,
4710 )?;
4711
4712 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 Ok(normalized_algorithm)
4758 },
4759 }
4760}
4761
4762trait Operation {
4821 type RegisteredAlgorithm: NormalizedAlgorithm;
4822}
4823
4824trait NormalizedAlgorithm: Sized {
4825 fn from_object(
4827 cx: &mut JSContext,
4828 algorithm_name: CryptoAlgorithm,
4829 object: HandleObject,
4830 ) -> Fallible<Self>;
4831
4832 fn name(&self) -> CryptoAlgorithm;
4834
4835 fn determine_support_from_operation_steps(&self, _length: Option<u32>) -> bool {
4840 debug_assert!(
4881 false,
4882 "determine_support_from_operation_steps() is not implemented \
4883 for this normalized algorithm."
4884 );
4885 false
4886 }
4887}
4888
4889struct EncryptOperation {}
4891
4892impl Operation for EncryptOperation {
4893 type RegisteredAlgorithm = EncryptAlgorithm;
4894}
4895
4896enum 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
5014struct DecryptOperation {}
5016
5017impl Operation for DecryptOperation {
5018 type RegisteredAlgorithm = DecryptAlgorithm;
5019}
5020
5021enum 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
5142struct SignOperation {}
5144
5145impl Operation for SignOperation {
5146 type RegisteredAlgorithm = SignAlgorithm;
5147}
5148
5149enum 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
5250struct VerifyOperation {}
5252
5253impl Operation for VerifyOperation {
5254 type RegisteredAlgorithm = VerifyAlgorithm;
5255}
5256
5257enum 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
5375struct DigestOperation {}
5377
5378impl Operation for DigestOperation {
5379 type RegisteredAlgorithm = DigestAlgorithm;
5380}
5381
5382#[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
5509struct DeriveBitsOperation<D: Equivalence> {
5511 phantom: PhantomData<D>,
5512}
5513
5514impl<D: Equivalence> Operation for DeriveBitsOperation<D> {
5515 type RegisteredAlgorithm = DeriveBitsAlgorithm<D>;
5516}
5517
5518enum 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
5644struct WrapKeyOperation {}
5646
5647impl Operation for WrapKeyOperation {
5648 type RegisteredAlgorithm = WrapKeyAlgorithm;
5649}
5650
5651enum 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
5699struct UnwrapKeyOperation {}
5701
5702impl Operation for UnwrapKeyOperation {
5703 type RegisteredAlgorithm = UnwrapKeyAlgorithm;
5704}
5705
5706enum 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
5754struct GenerateKeyOperation {}
5756
5757impl Operation for GenerateKeyOperation {
5758 type RegisteredAlgorithm = GenerateKeyAlgorithm;
5759}
5760
5761enum 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
6021struct ImportKeyOperation {}
6023
6024impl Operation for ImportKeyOperation {
6025 type RegisteredAlgorithm = ImportKeyAlgorithm;
6026}
6027
6028enum 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 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
6398struct ExportKeyOperation {}
6400
6401impl Operation for ExportKeyOperation {
6402 type RegisteredAlgorithm = ExportKeyAlgorithm;
6403}
6404
6405enum 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
6594struct GetKeyLengthOperation {}
6596
6597impl Operation for GetKeyLengthOperation {
6598 type RegisteredAlgorithm = GetKeyLengthAlgorithm;
6599}
6600
6601enum 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
6734struct EncapsulateOperation {}
6736
6737impl Operation for EncapsulateOperation {
6738 type RegisteredAlgorithm = EncapsulateAlgorithm;
6739}
6740
6741enum 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
6795struct DecapsulateOperation {}
6797
6798impl Operation for DecapsulateOperation {
6799 type RegisteredAlgorithm = DecapsulateAlgorithm;
6800}
6801
6802enum 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
6862struct GetSharedKeyLengthOperation {}
6864
6865impl Operation for GetSharedKeyLengthOperation {
6866 type RegisteredAlgorithm = GetSharedKeyLengthAlgorithm;
6867}
6868
6869enum 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
6919struct GetPublicKeyOperation {}
6921
6922impl Operation for GetPublicKeyOperation {
6923 type RegisteredAlgorithm = GetPublicKeyAlgorithm;
6924}
6925
6926enum 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}