Truly independent web browser
LibWeb: Port WebCrypto HMAC and KMAC algorithms to Rust
Shannon Booth8fe2ee71ecb5
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rsindex 05484515d0e..34a98d363e4 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs@@ -22,7 +22,7 @@ use crate::webidl::dom_exception::DOMExceptionFields;use crate::webidl::quota_exceeded_error::{self, QuotaExceededErrorFields};unsafe extern "C" {- fn web_crypto_fill_with_random(bytes: SpanMut<'_, u8>);+ pub(super) fn web_crypto_fill_with_random(bytes: SpanMut<'_, u8>);fn web_crypto_generate_random_uuid(state: *mut c_void, receive: unsafe extern "C" fn(*mut c_void, Span<'_, u8>));}diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rsindex 3707b03c06c..72b91edd391 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs@@ -11,9 +11,10 @@use core::ffi::c_void;use core::ptr::{NonNull, null, null_mut};+use std::collections::HashSet;use std::rc::Rc;-use ak::{Span, Utf16String, Utf16StringUnits};+use ak::{Span, SpanMut, Utf16String, Utf16StringUnits};use libjs_rust::api::{ErrorKind, ErrorType, Gc, Object, PropertyKey, RawNativeFunctionResult, Realm, Trace, Value, Vm,};@@ -21,10 +22,12 @@ use libjs_rust::api::{use crate::bindings::conversions::{buffer_source_type_of, to_unsigned_long_enforcing_range};use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi, realm_arguments};use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::crypto::crypto::web_crypto_fill_with_random;use crate::crypto::crypto_bindings::{CryptoKeyPair, JsonWebKey, RawJsonWebKey};-use crate::crypto::crypto_key::{CryptoKey, KeyUsage};+use crate::crypto::crypto_key::{CryptoKey, InternalAlgorithmData, KEY_USAGES, KeyType, KeyUsage};use crate::crypto::subtle_crypto::{- AlgorithmIdentifier, CryptoKeyOrCryptoKeyPair, KeyFormat, get_a_copy_of_the_bytes, normalize_an_algorithm,+ AlgorithmIdentifier, CryptoKeyOrCryptoKeyPair, KeyFormat, dom_error, get_a_copy_of_the_bytes,+ normalize_an_algorithm,};// https://w3c.github.io/webcrypto/#algorithm-overview@@ -34,6 +37,7 @@ pub(crate) struct AlgorithmParams {pub(crate) name: Utf16String,}+#[derive(Clone)]struct HashAlgorithmIdentifier {name: Utf16String,}@@ -173,7 +177,13 @@ pub enum Asn1Structure {unsafe extern "C" {fn web_crypto_encode_base64url(bytes: Span<'_, u8>, receive: ReceiveBytes, state: *mut c_void) -> i32;- fn web_crypto_decode_base64url(raw: usize, out: *mut c_void, error_message: &mut usize) -> Base64DecodeResult;+ fn web_crypto_decode_base64url(+ raw: usize,+ out: *mut c_void,+ state: *mut c_void,+ receive: Option<ReceiveBytes>,+ error_message: &mut usize,+ ) -> Base64DecodeResult;fn web_crypto_decode_asn1_structure(data: Span<'_, u8>,structure: Asn1Structure,@@ -221,6 +231,8 @@ pub unsafe extern "C" fn web_rust_crypto_base64_url_bytes_encode(bytes: Span<'_,unsafe fn base64_url_bytes_decode(base64_url_string: &Utf16String,out: *mut c_void,+ state: *mut c_void,+ receive: Option<ReceiveBytes>,error_message: &mut usize,) -> Base64DecodeResult {let is_ascii = match base64_url_string.as_units() {@@ -233,7 +245,8 @@ unsafe fn base64_url_bytes_decode(}// SAFETY: The caller passes a live native ByteBuffer as the output.- let result = unsafe { web_crypto_decode_base64url(base64_url_string.raw_identity(), out, error_message) };+ let result =+ unsafe { web_crypto_decode_base64url(base64_url_string.raw_identity(), out, state, receive, error_message) };if result == Base64DecodeResult::InvalidBase64 {// SAFETY: The decoder hands over an owned diagnostic string.let detail = unsafe { Utf16String::from_raw_owned(*error_message) };@@ -257,7 +270,7 @@ pub unsafe extern "C" fn web_rust_crypto_base64_url_bytes_decode(Utf16String::from_raw_owned(raw)};// SAFETY: The caller supplies a live ByteBuffer.- unsafe { base64_url_bytes_decode(&base64_url_string, out, error_message) }+ unsafe { base64_url_bytes_decode(&base64_url_string, out, null_mut(), None, error_message) }}// https://w3c.github.io/webcrypto/#concept-parse-an-asn1-structure@@ -348,7 +361,6 @@ pub(crate) enum AlgorithmId {AesCbc,AesGcm,AesKw,- Hmac,Hkdf,Pbkdf2,X25519,@@ -360,7 +372,6 @@ pub(crate) enum AlgorithmId {Argon2,ChaCha20Poly1305,AesOcb,- Kmac,}#[derive(Clone, Copy)]@@ -384,17 +395,12 @@ pub(crate) enum ParameterId {AesDerivedKeyParams,AesCbcParams,AesGcmParams,- HmacKeyGenParams,- HmacImportParams,HkdfParams,Pbkdf2Params,Ed448Params,ContextParams,Argon2Params,AeadParams,- KmacParams,- KmacKeyGenParams,- KmacImportParams,}#[derive(Clone, Trace)]@@ -665,14 +671,27 @@ pub(crate) trait AlgorithmMethods: Trace {))}- fn sign(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _data: &Bytes) -> WebIdlResult<Bytes> {+ fn sign(+ &self,+ _realm: Gc<Realm>,+ _algorithm: &AlgorithmParams,+ _key: Ref<CryptoKey>,+ _data: &Bytes,+ ) -> WebIdlResult<Bytes> {Err(Exception::Dom("NotSupportedError",Utf16String::from_utf8("sign is not supported"),))}- fn verify(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _signature: &Bytes, _data: &Bytes) -> WebIdlResult<bool> {+ fn verify(+ &self,+ _realm: Gc<Realm>,+ _algorithm: &AlgorithmParams,+ _key: Ref<CryptoKey>,+ _signature: &Bytes,+ _data: &Bytes,+ ) -> WebIdlResult<bool> {Err(Exception::Dom("NotSupportedError",Utf16String::from_utf8("verify is not supported"),@@ -695,7 +714,8 @@ pub(crate) trait AlgorithmMethods: Trace {fn import_key(&self,- _realm: Gc<Realm>,+ _cx: &CallContext,+ _algorithm: &AlgorithmParams,_format: KeyFormat,_key_data: ImportKeyData,_extractable: bool,@@ -709,7 +729,8 @@ pub(crate) trait AlgorithmMethods: Trace {fn generate_key(&self,- _realm: Gc<Realm>,+ _cx: &CallContext,+ _algorithm: &AlgorithmParams,_extractable: bool,_usages: &[KeyUsage],) -> WebIdlResult<CryptoKeyOrCryptoKeyPair> {@@ -719,14 +740,14 @@ pub(crate) trait AlgorithmMethods: Trace {))}- fn export_key(&self, _realm: Gc<Realm>, _format: KeyFormat, _key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {+ fn export_key(&self, _cx: &CallContext, _format: KeyFormat, _key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {Err(Exception::Dom("NotSupportedError",Utf16String::from_utf8("exportKey is not supported"),))}- fn get_key_length(&self, _realm: Gc<Realm>) -> WebIdlResult<Option<u32>> {+ fn get_key_length(&self, _realm: Gc<Realm>, _algorithm: &AlgorithmParams) -> WebIdlResult<Option<u32>> {Err(Exception::Dom("NotSupportedError",Utf16String::from_utf8("getKeyLength is not supported"),@@ -849,7 +870,13 @@ impl AlgorithmMethods for CppAlgorithm {Ok(out.expect("LibWeb returns bytes"))}- fn sign(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {+ fn sign(+ &self,+ realm: Gc<Realm>,+ _algorithm: &AlgorithmParams,+ key: Ref<CryptoKey>,+ data: &Bytes,+ ) -> WebIdlResult<Bytes> {let mut out: Option<Bytes> = None;// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.unsafe {@@ -866,7 +893,14 @@ impl AlgorithmMethods for CppAlgorithm {Ok(out.expect("LibWeb returns bytes"))}- fn verify(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, signature: &Bytes, data: &Bytes) -> WebIdlResult<bool> {+ fn verify(+ &self,+ realm: Gc<Realm>,+ _algorithm: &AlgorithmParams,+ key: Ref<CryptoKey>,+ signature: &Bytes,+ data: &Bytes,+ ) -> WebIdlResult<bool> {let mut out = false;// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.unsafe {@@ -902,12 +936,14 @@ impl AlgorithmMethods for CppAlgorithm {fn import_key(&self,- realm: Gc<Realm>,+ cx: &CallContext,+ _algorithm: &AlgorithmParams,format: KeyFormat,key_data: ImportKeyData,extractable: bool,usages: &[KeyUsage],) -> WebIdlResult<Ref<CryptoKey>> {+ let realm = cx.realm();let mut out = null_mut();let mut import = |data, jwk| {// SAFETY: The realm and algorithm are live, and the input and output are lent for the call.@@ -937,10 +973,12 @@ impl AlgorithmMethods for CppAlgorithm {fn generate_key(&self,- realm: Gc<Realm>,+ cx: &CallContext,+ _algorithm: &AlgorithmParams,extractable: bool,usages: &[KeyUsage],) -> WebIdlResult<CryptoKeyOrCryptoKeyPair> {+ let realm = cx.realm();let (mut key, mut public_key, mut private_key) = (null_mut(), null_mut(), null_mut());// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.unsafe {@@ -968,7 +1006,8 @@ impl AlgorithmMethods for CppAlgorithm {}}- fn export_key(&self, realm: Gc<Realm>, format: KeyFormat, key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {+ fn export_key(&self, cx: &CallContext, format: KeyFormat, key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {+ let realm = cx.realm();let mut out: Option<ExportKeyResult> = None;// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.unsafe {@@ -986,7 +1025,7 @@ impl AlgorithmMethods for CppAlgorithm {Ok(out.expect("LibWeb returns an export result"))}- fn get_key_length(&self, realm: Gc<Realm>) -> WebIdlResult<Option<u32>> {+ fn get_key_length(&self, realm: Gc<Realm>, _algorithm: &AlgorithmParams) -> WebIdlResult<Option<u32>> {let mut out = OptionalLength::default();// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.unsafe { web_crypto_algorithm_get_key_length(realm.as_ptr().cast(), self.0.as_ptr(), &mut out) }@@ -1357,6 +1396,1352 @@ impl AlgorithmMethods for CShakeParams {}}+fn key_usage_to_string(usage: KeyUsage) -> &'static str {+ std::str::from_utf8(KEY_USAGES[usage as usize]).expect("a key usage is ASCII")+}++fn parse_jwk_symmetric_key(vm: &Vm, jwk: &JsonWebKey) -> WebIdlResult<Bytes> {+ let Some(base64_url_string) = &jwk.k else {+ return Err(dom_error("DataError", b"JWK has no 'k' field"));+ };++ let mut result: Option<Bytes> = None;+ let mut error_message = 0;+ // SAFETY: The receiver borrows the decoded bytes for the call.+ let status = unsafe {+ base64_url_bytes_decode(+ base64_url_string,+ null_mut(),+ core::ptr::from_mut(&mut result).cast(),+ Some(receive_bytes),+ &mut error_message,+ )+ };+ match status {+ Base64DecodeResult::Success => Ok(result.expect("LibWeb returns the decoded bytes")),+ Base64DecodeResult::OutOfMemory => vm+ .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])+ .map_err(Into::into),+ Base64DecodeResult::NonAscii => Err(dom_error("DataError", b"base64 decode: invalid base64url")),+ Base64DecodeResult::InvalidBase64 => {+ // SAFETY: The decoder hands over an owned diagnostic string.+ let message = unsafe { Utf16String::from_raw_owned(error_message) };+ Err(Exception::Dom("DataError", message))+ }+ }+}++// https://www.rfc-editor.org/rfc/rfc7517#section-4.3+fn validate_jwk_key_ops(jwk: &JsonWebKey, usages: &[KeyUsage]) -> WebIdlResult<()> {+ // Use of the "key_ops" member is OPTIONAL, unless the application requires its presence.+ let Some(key_operations) = &jwk.key_ops else {+ return Ok(());+ };++ // Duplicate key operation values MUST NOT be present in the array+ let mut seen_operations = HashSet::new();+ for key_operation in key_operations {+ if !seen_operations.insert(key_operation) {+ return Err(Exception::Dom(+ "DataError",+ libjs_rust::api::utf16_formatted("Duplicate key operation: {}", &[key_operation]),+ ));+ }+ }++ // Multiple unrelated key operations SHOULD NOT be specified for a key because of the potential+ // vulnerabilities associated with using the same key with multiple algorithms. Thus, the+ // combinations "sign" with "verify", "encrypt" with "decrypt", and "wrapKey" with "unwrapKey"+ // are permitted, but other combinations SHOULD NOT be used.+ let is_used_for_signing = seen_operations.contains(&Utf16String::from_ascii(b"sign"))+ || seen_operations.contains(&Utf16String::from_ascii(b"verify"));+ let is_used_for_encryption = seen_operations.contains(&Utf16String::from_ascii(b"encrypt"))+ || seen_operations.contains(&Utf16String::from_ascii(b"decrypt"));+ let is_used_for_wrapping = seen_operations.contains(&Utf16String::from_ascii(b"wrapKey"))+ || seen_operations.contains(&Utf16String::from_ascii(b"unwrapKey"));+ let number_of_operation_types =+ u8::from(is_used_for_signing) + u8::from(is_used_for_encryption) + u8::from(is_used_for_wrapping);+ if number_of_operation_types > 1 {+ return Err(dom_error(+ "DataError",+ b"Multiple unrelated key operations are specified",+ ));+ }++ // The "use" and "key_ops" JWK members SHOULD NOT be used together; however, if both are used,+ // the information they convey MUST be consistent. Applications should specify which of these+ // members they use, if either is to be used by the application.+ if let Some(key_use) = &jwk.r#use {+ for key_operation in key_operations {+ if *key_operation == Utf16String::from_ascii(b"deriveKey")+ || *key_operation == Utf16String::from_ascii(b"deriveBits")+ {+ continue;+ }+ if *key_use == Utf16String::from_ascii(b"sig")+ && *key_operation != Utf16String::from_ascii(b"sign")+ && *key_operation != Utf16String::from_ascii(b"verify")+ {+ return Err(dom_error(+ "DataError",+ b"use=sig but key_ops does not contain 'sign' or 'verify'",+ ));+ }+ if *key_use == Utf16String::from_ascii(b"enc")+ && (*key_operation == Utf16String::from_ascii(b"sign")+ || *key_operation == Utf16String::from_ascii(b"verify"))+ {+ return Err(dom_error(+ "DataError",+ b"use=enc but key_ops contains 'sign' or 'verify'",+ ));+ }+ }+ }++ // NOTE: This validation happens in multiple places in the spec, so it is here for convenience.+ for &usage in usages {+ let usage = key_usage_to_string(usage);+ if !seen_operations.contains(&Utf16String::from_utf8(usage)) {+ return Err(Exception::Dom(+ "DataError",+ libjs_rust::api::utf16_formatted("Missing key_ops usage: {}", &[&usage]),+ ));+ }+ }++ Ok(())+}++// NB: Keeps only the bytes that hold the first length_in_bits bits of data, and zeroes the unused low-order bits of+// the last byte when the length is not a whole number of bytes.+fn keep_first_bits(data: &mut Vec<u8>, length_in_bits: usize) {+ let length_in_bytes = length_in_bits.div_ceil(8);+ assert!(length_in_bytes <= data.len());+ data.truncate(length_in_bytes);++ let remainder_bits = length_in_bits % 8;+ if remainder_bits != 0 {+ data[length_in_bytes - 1] &= !(0xff >> remainder_bits);+ }+}++fn generate_random_key(vm: &Vm, size_in_bits: u32) -> WebIdlResult<Vec<u8>> {+ let size_in_bits = size_in_bits as usize;+ let length_in_bytes = size_in_bits.div_ceil(8);+ let mut key_buffer = Vec::new();+ if key_buffer.try_reserve_exact(length_in_bytes).is_err() {+ return vm+ .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])+ .map_err(Into::into);+ }+ key_buffer.resize(length_in_bytes, 0);+ // SAFETY: The service writes the bytes during this call.+ unsafe { web_crypto_fill_with_random(SpanMut::new(&mut key_buffer)) };+ keep_first_bits(&mut key_buffer, size_in_bits);+ Ok(key_buffer)+}++// NB: Our KMAC implementation is byte-oriented, so it cannot use keys with a partial last byte. OpenSSL also only+// accepts KMAC keys of up to 512 bytes.+fn validate_kmac_key_length(length_in_bits: u32) -> WebIdlResult<()> {+ if !length_in_bits.is_multiple_of(8) {+ return Err(dom_error(+ "NotSupportedError",+ b"KMAC key length must be a multiple of 8",+ ));+ }+ if length_in_bits > 512 * 8 {+ return Err(dom_error(+ "NotSupportedError",+ b"KMAC key length must not exceed 4096 bits",+ ));+ }+ Ok(())+}++#[repr(i32)]+#[derive(Clone, Copy)]+enum KmacKind {+ Kmac128,+ Kmac256,+}++unsafe extern "C" {+ fn web_crypto_hmac_sign(+ kind: ShaHashKind,+ key: Span<'_, u8>,+ message: Span<'_, u8>,+ state: *mut c_void,+ receive: ReceiveBytes,+ );+ fn web_crypto_timing_safe_compare(left: Span<'_, u8>, right: Span<'_, u8>) -> bool;+ fn web_crypto_kmac_default_key_length(kind: KmacKind) -> u32;+ fn web_crypto_kmac_validate_parameters(output_length: u32, customization: OptionalBytes<'_>) -> bool;+ fn web_crypto_kmac_sign(+ kind: KmacKind,+ key: Span<'_, u8>,+ message: Span<'_, u8>,+ output_length: u32,+ customization: OptionalBytes<'_>,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> bool;+}++fn hmac_calculate_message_digest(hash_name: &Utf16String, key: &[u8], message: &[u8]) -> WebIdlResult<Bytes> {+ let hash_kind = if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-1")) {+ ShaHashKind::Sha1+ } else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-256")) {+ ShaHashKind::Sha256+ } else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-384")) {+ ShaHashKind::Sha384+ } else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-512")) {+ ShaHashKind::Sha512+ } else {+ return Err(Exception::Dom(+ "NotSupportedError",+ libjs_rust::api::utf16_formatted("Invalid hash function '{}'", &[hash_name]),+ ));+ };++ let mut mac: Option<Bytes> = None;+ // SAFETY: The input and output are lent for the duration of the call.+ unsafe {+ web_crypto_hmac_sign(+ hash_kind,+ Span::new(key),+ Span::new(message),+ core::ptr::from_mut(&mut mac).cast(),+ receive_bytes,+ );+ }+ Ok(mac.expect("LibCrypto returns a MAC"))+}++fn hmac_hash_block_size(hash: &HashAlgorithmIdentifier) -> WebIdlResult<u32> {+ let hash_name = &hash.name;+ if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-1")) {+ return Ok(64);+ }+ if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-256")) {+ return Ok(64);+ }+ if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-384")) {+ return Ok(128);+ }+ if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-512")) {+ return Ok(128);+ }+ Err(Exception::Dom(+ "NotSupportedError",+ libjs_rust::api::utf16_formatted("Invalid hash function '{}'", &[hash_name]),+ ))+}++fn kmac_kind_from_algorithm_name(algorithm_name: &Utf16String) -> Option<KmacKind> {+ if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"KMAC128")) {+ return Some(KmacKind::Kmac128);+ }+ if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"KMAC256")) {+ return Some(KmacKind::Kmac256);+ }+ None+}++fn kmac_calculate_mac(+ algorithm_name: &Utf16String,+ key: &[u8],+ message: &[u8],+ output_length_bits: u32,+ customization: Option<&Bytes>,+) -> WebIdlResult<Bytes> {+ let Some(kind) = kmac_kind_from_algorithm_name(algorithm_name) else {+ return Err(dom_error("OperationError", b"Unsupported KMAC algorithm"));+ };++ let mut mac: Option<Bytes> = None;+ // SAFETY: The input and output are lent for the duration of the call.+ let success = unsafe {+ web_crypto_kmac_sign(+ kind,+ Span::new(key),+ Span::new(message),+ output_length_bits,+ customization.into(),+ core::ptr::from_mut(&mut mac).cast(),+ receive_bytes,+ )+ };+ if !success {+ return Err(dom_error("OperationError", b"KMAC operation failed"));+ }+ Ok(mac.expect("LibCrypto returns a MAC"))+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct HmacImportParams {+ #[gc(untraced)]+ hash: HashAlgorithmIdentifier,+ length: Option<u32>,+}++impl HmacImportParams {+ pub(crate) fn from_value(vm: &Vm, realm: Gc<Realm>, object: Gc<Object>) -> WebIdlResult<Self> {+ let hash_value = object.get(vm, &PropertyKey::from_utf8("hash"))?;+ let hash = hash_algorithm_identifier_from_value(vm, realm, hash_value, None)?;++ let mut length = None;+ let length_property = PropertyKey::from_utf8("length");+ if object.has_property(vm, &length_property)? {+ let length_value = object.get(vm, &length_property)?;+ length = Some(to_unsigned_long_enforcing_range(vm, length_value)?);+ }++ Ok(Self { hash, length })+ }+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct HmacKeyGenParams {+ #[gc(untraced)]+ hash: HashAlgorithmIdentifier,+ length: Option<u32>,+}++impl HmacKeyGenParams {+ pub(crate) fn from_value(vm: &Vm, realm: Gc<Realm>, object: Gc<Object>) -> WebIdlResult<Self> {+ let hash_value = object.get(vm, &PropertyKey::from_utf8("hash"))?;+ let hash = hash_algorithm_identifier_from_value(vm, realm, hash_value, None)?;++ let mut length = None;+ let length_property = PropertyKey::from_utf8("length");+ if object.has_property(vm, &length_property)? {+ let length_value = object.get(vm, &length_property)?;+ length = Some(to_unsigned_long_enforcing_range(vm, length_value)?);+ }++ Ok(Self { hash, length })+ }+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Hmac;++impl AlgorithmMethods for Hmac {+ // https://w3c.github.io/webcrypto/#hmac-operations-sign+ fn sign(&self, _: Gc<Realm>, _: &AlgorithmParams, key: Ref<CryptoKey>, message: &Bytes) -> WebIdlResult<Bytes> {+ // 1. Let mac be the result of performing the MAC Generation operation described in Section 4 of+ // [FIPS-198-1] using the key represented by [[handle]] internal slot of key, the hash+ // function identified by the hash attribute of the [[algorithm]] internal slot of key and+ // message as the input data text.+ let key_data = key.byte_handle_bytes();+ let algorithm = key.internal_algorithm();+ let InternalAlgorithmData::Hmac { hash, .. } = &*algorithm else {+ unreachable!("the key has an HMAC algorithm")+ };+ let mac = hmac_calculate_message_digest(hash, key_data, message.as_slice())?;++ // 2. Return the result of creating an ArrayBuffer containing mac.+ Ok(mac)+ }++ // https://w3c.github.io/webcrypto/#hmac-operations-verify+ fn verify(+ &self,+ _: Gc<Realm>,+ _: &AlgorithmParams,+ key: Ref<CryptoKey>,+ signature: &Bytes,+ message: &Bytes,+ ) -> WebIdlResult<bool> {+ // 1. Let mac be the result of performing the MAC Generation operation described in Section 4 of+ // [FIPS-198-1] using the key represented by [[handle]] internal slot of key, the hash+ // function identified by the hash attribute of the [[algorithm]] internal slot of key and+ // message as the input data text.+ let key_data = key.byte_handle_bytes();+ let algorithm = key.internal_algorithm();+ let InternalAlgorithmData::Hmac { hash, .. } = &*algorithm else {+ unreachable!("the key has an HMAC algorithm")+ };+ let mac = hmac_calculate_message_digest(hash, key_data, message.as_slice())?;++ // 2. Return true if mac is equal to signature and false otherwise. This comparison must be performed in+ // constant-time.+ // SAFETY: The input bytes live for the duration of the comparison.+ Ok(mac.as_slice().len() == signature.as_slice().len()+ && unsafe { web_crypto_timing_safe_compare(Span::new(mac.as_slice()), Span::new(signature.as_slice())) })+ }++ // https://w3c.github.io/webcrypto/#hmac-operations-export-key+ #[allow(+ clippy::field_reassign_with_default,+ reason = "the algorithm sets JWK members in separate steps"+ )]+ fn export_key(&self, _: &CallContext, format: KeyFormat, key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {+ // 1. If the underlying cryptographic key material represented by the [[handle]] internal slot+ // of key cannot be accessed, then throw an OperationError.+ // NOTE: In our impl this is always accessible++ // 2. Let bits be the raw bits of the key represented by [[handle]] internal slot of key.+ // 3. Let data be an octet string containing bits.+ let data = key.byte_handle_bytes();++ // 4. If format is "raw":+ // https://wicg.github.io/webcrypto-modern-algos/#subtlecrypto-interface-keyformat+ // For all existing symmetric algorithms in WebCrypto, "raw-secret" acts as an alias of "raw".+ let result = if format == KeyFormat::Raw || format == KeyFormat::RawSecret {+ // Let result be the result of creating an ArrayBuffer containing data.+ ExportKeyResult::Bytes(Bytes::new(data.to_vec()))+ }+ // If format is "jwk":+ else if format == KeyFormat::Jwk {+ // Let jwk be a new JsonWebKey dictionary.+ let mut jwk = JsonWebKey::default();++ // Set the kty attribute of jwk to the string "oct".+ jwk.kty = Some(Utf16String::from_ascii(b"oct"));++ // Set the k attribute of jwk to be a string containing data, encoded according to Section+ // 6.4 of JSON Web Algorithms [JWA].+ jwk.k = Some(base64_url_bytes_encode(data).expect("base64url encoding succeeds"));++ // Let algorithm be the [[algorithm]] internal slot of key.+ let algorithm = key.internal_algorithm();++ // Let hash be the hash attribute of algorithm.+ // If the name attribute of hash is "SHA-1":+ let InternalAlgorithmData::Hmac { hash: hash_name, .. } = &*algorithm else {+ unreachable!("the key has an HMAC algorithm")+ };+ if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-1")) {+ // Set the alg attribute of jwk to the string "HS1".+ jwk.alg = Some(Utf16String::from_ascii(b"HS1"));+ }+ // If the name attribute of hash is "SHA-256":+ else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-256")) {+ // Set the alg attribute of jwk to the string "HS256".+ jwk.alg = Some(Utf16String::from_ascii(b"HS256"));+ }+ // If the name attribute of hash is "SHA-384":+ else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-384")) {+ // Set the alg attribute of jwk to the string "HS384".+ jwk.alg = Some(Utf16String::from_ascii(b"HS384"));+ }+ // If the name attribute of hash is "SHA-512":+ else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-512")) {+ // Set the alg attribute of jwk to the string "HS512".+ jwk.alg = Some(Utf16String::from_ascii(b"HS512"));+ }+ // Otherwise, the name attribute of hash is defined in another applicable+ // specification:+ else {+ // Perform any key export steps defined by other applicable specifications,+ // passing format and key and obtaining alg.+ // Set the alg attribute of jwk to alg.+ return Err(dom_error("DataError", b"Invalid algorithm"));+ }++ // Set the key_ops attribute of jwk to equal the usages attribute of key.+ jwk.key_ops = Some(+ key.internal_usages()+ .iter()+ .map(|usage| Utf16String::from_ascii(KEY_USAGES[*usage as usize]))+ .collect(),+ );++ // Set the ext attribute of jwk to equal the [[extractable]] internal slot of key.+ jwk.ext = Some(key.is_extractable());++ // Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL].+ ExportKeyResult::JsonWebKey(jwk)+ }+ // Otherwise:+ else {+ // throw a NotSupportedError.+ return Err(dom_error("NotSupportedError", b"Invalid key format"));+ };++ // 5. Return result.+ Ok(result)+ }+}++impl AlgorithmMethods for HmacKeyGenParams {+ // https://w3c.github.io/webcrypto/#hmac-operations-generate-key+ fn validate_generate_key_parameters(&self, _: Gc<Realm>) -> WebIdlResult<()> {+ let normalized_algorithm = self;++ // NB: Step 2 throws an error when the length member of normalizedAlgorithm is not present and we do not know the+ // block size of the hash function, or when the length member is zero.+ if normalized_algorithm.length.is_none() {+ hmac_hash_block_size(&normalized_algorithm.hash)?;+ } else if normalized_algorithm.length == Some(0) {+ return Err(dom_error("OperationError", b"Invalid length"));+ }++ Ok(())+ }++ // https://w3c.github.io/webcrypto/#hmac-operations-generate-key+ fn generate_key(+ &self,+ cx: &CallContext,+ _: &AlgorithmParams,+ extractable: bool,+ usages: &[KeyUsage],+ ) -> WebIdlResult<CryptoKeyOrCryptoKeyPair> {+ // 1. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.+ for &usage in usages {+ if usage != KeyUsage::Sign && usage != KeyUsage::Verify {+ return Err(Exception::Dom(+ "SyntaxError",+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),+ ));+ }+ }++ // 2. If the length member of normalizedAlgorithm is not present:+ let normalized_algorithm = self;+ let length = if normalized_algorithm.length.is_none() {+ // Let length be the block size in bits of the hash function identified by the hash member+ // of normalizedAlgorithm.+ hmac_hash_block_size(&normalized_algorithm.hash)? * 8+ }+ // Otherwise, if the length member of normalizedAlgorithm is non-zero:+ else if let Some(length @ 1..) = normalized_algorithm.length {+ // Let length be equal to the length member of normalizedAlgorithm.+ length+ }+ // Otherwise:+ else {+ // throw an OperationError.+ return Err(dom_error("OperationError", b"Invalid length"));+ };++ // 3. Generate a key of length length bits.+ // 4. If the key generation step fails, then throw an OperationError.+ let key_data =+ generate_random_key(cx.vm(), length).map_err(|_| dom_error("OperationError", b"Failed to generate key"))?;++ // 5. Let key be a new CryptoKey object representing the generated key.+ let key = CryptoKey::from_byte_handle(cx.vm(), &key_data);++ // 6. Let algorithm be a new HmacKeyAlgorithm.+ // 7. Set the name attribute of algorithm to "HMAC".+ // 8. Let hash be a new KeyAlgorithm.+ // 9. Set the name attribute of hash to equal the name member of the hash member of normalizedAlgorithm.+ let hash_name = normalized_algorithm.hash.name.clone();++ // 12. Set the [[type]] internal slot of key to "secret".+ key.set_type(KeyType::Secret);++ // 10. Set the hash attribute of algorithm to hash.+ // 11. Set the length attribute of algorithm to length.+ // 13. Set the [[algorithm]] internal slot of key to algorithm.+ key.set_algorithm(InternalAlgorithmData::Hmac {+ name: Utf16String::from_ascii(b"HMAC"),+ hash: hash_name,+ length,+ });++ // 14. Set the [[extractable]] internal slot of key to be extractable.+ key.set_extractable(extractable);++ // 15. Set the [[usages]] internal slot of key to be the normalized value of usages.+ key.set_usages(normalized_key_usages(usages));++ // 16. Return key.+ Ok(CryptoKeyOrCryptoKeyPair::CryptoKey(key))+ }+}++impl AlgorithmMethods for HmacImportParams {+ // https://w3c.github.io/webcrypto/#hmac-operations-import-key+ fn validate_import_key_parameters(&self, _: Gc<Realm>) -> WebIdlResult<()> {+ let normalized_algorithm = self;++ // 1. If the length member of normalizedAlgorithm is present and is zero, then throw a DataError.+ if normalized_algorithm.length == Some(0) {+ return Err(dom_error("DataError", b"Invalid key length"));+ }++ Ok(())+ }++ // https://w3c.github.io/webcrypto/#hmac-operations-import-key+ #[allow(+ clippy::cast_possible_truncation,+ reason = "the key algorithm's unsigned long length truncates to 32 bits"+ )]+ fn import_key(+ &self,+ cx: &CallContext,+ _: &AlgorithmParams,+ key_format: KeyFormat,+ key_data: ImportKeyData,+ extractable: bool,+ usages: &[KeyUsage],+ ) -> WebIdlResult<Ref<CryptoKey>> {+ let normalized_algorithm = self;++ // NB: Step 1 is performed by validate_import_key_parameters().+ self.validate_import_key_parameters(cx.realm())?;++ // 2. Let keyData be the key data to be imported.+ // 3. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.+ for &usage in usages {+ if usage != KeyUsage::Sign && usage != KeyUsage::Verify {+ return Err(Exception::Dom(+ "SyntaxError",+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),+ ));+ }+ }++ // 4. Let hash be a new KeyAlgorithm.+ let hash_name;++ // 5. If format is "raw":+ let data;+ if key_format == KeyFormat::Raw || key_format == KeyFormat::RawSecret {+ // 5.1. Let data be the octet string contained in keyData.+ let ImportKeyData::Bytes(bytes) = key_data else {+ unreachable!("raw key data contains bytes")+ };+ data = bytes;++ // 5.2. Set hash to equal the hash member of normalizedAlgorithm.+ hash_name = normalized_algorithm.hash.name.clone();+ }+ // If format is "jwk":+ else if key_format == KeyFormat::Jwk {+ // 1. If keyData is a JsonWebKey dictionary:+ // Let jwk equal keyData.+ // Otherwise:+ // Throw a DataError.+ let ImportKeyData::JsonWebKey(jwk) = key_data else {+ return Err(dom_error("DataError", b"Data is not a JsonWebKey dictionary"));+ };++ // 2. If the kty field of jwk is not "oct", then throw a DataError.+ if jwk.kty.as_ref() != Some(&Utf16String::from_ascii(b"oct")) {+ return Err(dom_error("DataError", b"Invalid key type"));+ }++ // 3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA],+ // then throw a DataError.+ // 4. Let data be the octet string obtained by decoding the k field of jwk.+ data = parse_jwk_symmetric_key(cx.vm(), &jwk)?;++ // 5. Set the hash to equal the hash member of normalizedAlgorithm.+ hash_name = normalized_algorithm.hash.name.clone();++ // 6. If the name attribute of hash is "SHA-1":+ if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-1")) {+ // If the alg field of jwk is present and is not "HS1", then throw a DataError.+ if jwk+ .alg+ .as_ref()+ .is_some_and(|alg| *alg != Utf16String::from_ascii(b"HS1"))+ {+ return Err(dom_error("DataError", b"Invalid algorithm"));+ }+ }+ // If the name attribute of hash is "SHA-256":+ else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-256")) {+ // If the alg field of jwk is present and is not "HS256", then throw a DataError.+ if jwk+ .alg+ .as_ref()+ .is_some_and(|alg| *alg != Utf16String::from_ascii(b"HS256"))+ {+ return Err(dom_error("DataError", b"Invalid algorithm"));+ }+ }+ // If the name attribute of hash is "SHA-384":+ else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-384")) {+ // If the alg field of jwk is present and is not "HS384", then throw a DataError.+ if jwk+ .alg+ .as_ref()+ .is_some_and(|alg| *alg != Utf16String::from_ascii(b"HS384"))+ {+ return Err(dom_error("DataError", b"Invalid algorithm"));+ }+ }+ // If the name attribute of hash is "SHA-512":+ else if matches!(hash_name.as_units(), Utf16StringUnits::Ascii(b"SHA-512")) {+ // If the alg field of jwk is present and is not "HS512", then throw a DataError.+ if jwk+ .alg+ .as_ref()+ .is_some_and(|alg| *alg != Utf16String::from_ascii(b"HS512"))+ {+ return Err(dom_error("DataError", b"Invalid algorithm"));+ }+ }+ // Otherwise, if the name attribute of hash is defined in another applicable specification:+ else {+ // Perform any key import steps defined by other applicable specifications, passing format,+ // jwk and hash and obtaining hash.+ return Err(dom_error("DataError", b"Invalid algorithm"));+ }++ // 7. If usages is non-empty and the use field of jwk is present and is not "sig", then+ // throw a DataError.+ if !usages.is_empty()+ && jwk+ .r#use+ .as_ref()+ .is_some_and(|key_use| *key_use != Utf16String::from_ascii(b"sig"))+ {+ return Err(dom_error("DataError", b"Invalid use in JsonWebKey"));+ }++ // 8. If the key_ops field of jwk is present, and is invalid according to the requirements+ // of JSON Web Key [JWK] or does not contain all of the specified usages values, then+ // throw a DataError.+ validate_jwk_key_ops(&jwk, usages)?;++ // 9. If the ext field of jwk is present and has the value false and extractable is true,+ // then throw a DataError.+ if jwk.ext == Some(false) && extractable {+ return Err(dom_error("DataError", b"Invalid ext field"));+ }+ }+ // Otherwise:+ else {+ // throw a NotSupportedError.+ return Err(dom_error("NotSupportedError", b"Invalid key format"));+ }++ // 6. Let length be equivalent to the length, in octets, of data, multiplied by 8.+ let mut length = data.as_slice().len() * 8;++ // 7. If length is zero then throw a DataError.+ if length == 0 {+ return Err(dom_error("DataError", b"No data provided"));+ }++ // 8. If the length member of normalizedAlgorithm is present:+ if let Some(normalized_algorithm_length) = normalized_algorithm.length {+ // If the length member of normalizedAlgorithm is greater than length:+ let normalized_algorithm_length = normalized_algorithm_length as usize;+ if normalized_algorithm_length > length {+ // throw a DataError.+ return Err(dom_error("DataError", b"Invalid data size"));+ }++ // If the length member of normalizedAlgorithm, is less than or equal to length minus eight:+ if normalized_algorithm_length <= length - 8 {+ // throw a DataError.+ return Err(dom_error("DataError", b"Invalid data size"));+ }++ // Otherwise:+ // Set length equal to the length member of normalizedAlgorithm.+ length = normalized_algorithm_length;+ }++ // 9. Let key be a new CryptoKey object representing an HMAC key with the first length bits of data.+ let mut data = Rc::unwrap_or_clone(data.0);+ keep_first_bits(&mut data, length);+ let key = CryptoKey::from_byte_handle(cx.vm(), &data);++ // 10. Set the [[type]] internal slot of key to "secret".+ key.set_type(KeyType::Secret);++ // 11. Let algorithm be a new HmacKeyAlgorithm.+ // 12. Set the name attribute of algorithm to "HMAC".+ // 13. Set the length attribute of algorithm to length.+ // 14. Set the hash attribute of algorithm to hash.+ // 15. Set the [[algorithm]] internal slot of key to algorithm.+ key.set_algorithm(InternalAlgorithmData::Hmac {+ name: Utf16String::from_ascii(b"HMAC"),+ hash: hash_name,+ length: length as u32,+ });++ // 16. Return key.+ Ok(key)+ }++ // https://w3c.github.io/webcrypto/#hmac-operations-get-key-length+ fn get_key_length(&self, _: Gc<Realm>, _: &AlgorithmParams) -> WebIdlResult<Option<u32>> {+ let normalized_derived_key_algorithm = self;++ // 1. If the length member of normalizedDerivedKeyAlgorithm is not present:+ let length = if normalized_derived_key_algorithm.length.is_none() {+ // Let length be the block size in bits of the hash function identified by the hash member of+ // normalizedDerivedKeyAlgorithm.+ hmac_hash_block_size(&normalized_derived_key_algorithm.hash)? * 8+ }+ // Otherwise, if the length member of normalizedDerivedKeyAlgorithm is non-zero:+ else if let Some(length @ 1..) = normalized_derived_key_algorithm.length {+ // Let length be equal to the length member of normalizedDerivedKeyAlgorithm.+ length+ }+ // Otherwise:+ else {+ // throw a TypeError.+ return Err(Exception::type_error("Invalid key length"));+ };++ // 2. Return length.+ Ok(Some(length))+ }+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct KmacParams {+ output_length: u32,+ customization: Option<Bytes>,+}++impl KmacParams {+ // https://wicg.github.io/webcrypto-modern-algos/#kmac-params+ pub(crate) fn from_value(vm: &Vm, object: Gc<Object>) -> WebIdlResult<Self> {+ // 1. If the outputLength member is missing, throw a TypeError.+ let output_length_property = PropertyKey::from_utf8("outputLength");+ if !object.has_property(vm, &output_length_property)? {+ return vm+ .throw_completion(+ ErrorKind::TypeError,+ ErrorType::MissingRequiredProperty,+ &[&"outputLength"],+ )+ .map_err(Into::into);+ }++ let output_length = object.get(vm, &output_length_property)?;+ let length = to_unsigned_long_enforcing_range(vm, output_length)?;++ // 2. Let customization be the optional customization member or the empty octet string.+ let customization = get_optional_buffer_source(vm, object, &PropertyKey::from_utf8("customization"))?;++ Ok(Self {+ output_length: length,+ customization,+ })+ }+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct KmacKeyGenParams {+ length: Option<u32>,+}++impl KmacKeyGenParams {+ // https://wicg.github.io/webcrypto-modern-algos/#kmac-keygen-params+ pub(crate) fn from_value(vm: &Vm, object: Gc<Object>) -> WebIdlResult<Self> {+ // 1. If the length member is present, record its unsigned long value; otherwise leave it unset.+ let mut length = None;+ let length_property = PropertyKey::from_utf8("length");+ if object.has_property(vm, &length_property)? {+ let length_value = object.get(vm, &length_property)?;+ length = Some(to_unsigned_long_enforcing_range(vm, length_value)?);+ }++ Ok(Self { length })+ }+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct KmacImportParams {+ length: Option<u32>,+}++impl KmacImportParams {+ // https://wicg.github.io/webcrypto-modern-algos/#kmac-import-params+ pub(crate) fn from_value(vm: &Vm, object: Gc<Object>) -> WebIdlResult<Self> {+ // 1. If the length member is present, record its unsigned long value; otherwise leave it unset.+ let mut length = None;+ let length_property = PropertyKey::from_utf8("length");+ if object.has_property(vm, &length_property)? {+ let length_value = object.get(vm, &length_property)?;+ length = Some(to_unsigned_long_enforcing_range(vm, length_value)?);+ }++ Ok(Self { length })+ }+}++impl AlgorithmMethods for KmacParams {+ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-sign+ fn validate_sign_parameters(&self, _: Gc<Realm>) -> WebIdlResult<()> {+ // NB: Step 2 fails for the output lengths and customizations that our KMAC does not support.+ let normalized_algorithm = self;+ // SAFETY: The parameters are lent for the call.+ let result = unsafe {+ web_crypto_kmac_validate_parameters(+ normalized_algorithm.output_length,+ normalized_algorithm.customization.as_ref().into(),+ )+ };+ if !result {+ return Err(dom_error("OperationError", b"KMAC operation failed"));+ }++ Ok(())+ }++ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-sign+ fn sign(+ &self,+ _: Gc<Realm>,+ algorithm: &AlgorithmParams,+ key: Ref<CryptoKey>,+ message: &Bytes,+ ) -> WebIdlResult<Bytes> {+ let normalized_algorithm = self;++ // 1. Let customization be the customization member of normalizedAlgorithm if present or the empty octet string otherwise.+ let customization = normalized_algorithm.customization.as_ref();++ let key_data = key.byte_handle_bytes();+ let output_length = normalized_algorithm.output_length;++ // 2. If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":+ // Let mac be the result of performing the KMAC128 function defined in Section 4 of [NIST-SP800-185]+ // using the key represented by [[handle]] internal slot of key as the K input parameter,+ // message as the X input parameter, the outputLength member of normalizedAlgorithm as the L input parameter,+ // and customization as the S input parameter.+ // 2. If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":+ // Let mac be the result of performing the KMAC256 function defined in Section 4 of [NIST-SP800-185]+ // using the key represented by [[handle]] internal slot of key as the K input parameter,+ // message as the X input parameter, the outputLength member of normalizedAlgorithm as the L input parameter,+ // and customization as the S input parameter.+ let mac = kmac_calculate_mac(+ &algorithm.name,+ key_data,+ message.as_slice(),+ output_length,+ customization,+ )?;++ // 3. Return a byte sequence containing mac.+ Ok(mac)+ }++ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-verify+ fn validate_verify_parameters(&self, _: Gc<Realm>) -> WebIdlResult<()> {+ // NB: Step 2 fails for the output lengths and customizations that our KMAC does not support.+ let normalized_algorithm = self;+ // SAFETY: The parameters are lent for the call.+ let result = unsafe {+ web_crypto_kmac_validate_parameters(+ normalized_algorithm.output_length,+ normalized_algorithm.customization.as_ref().into(),+ )+ };+ if !result {+ return Err(dom_error("OperationError", b"KMAC operation failed"));+ }++ Ok(())+ }++ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-verify+ fn verify(+ &self,+ _: Gc<Realm>,+ algorithm: &AlgorithmParams,+ key: Ref<CryptoKey>,+ signature: &Bytes,+ message: &Bytes,+ ) -> WebIdlResult<bool> {+ let normalized_algorithm = self;++ // 1. Let customization be the customization member of normalizedAlgorithm if present or the empty octet string otherwise.+ let customization = normalized_algorithm.customization.as_ref();++ let key_data = key.byte_handle_bytes();+ let output_length = normalized_algorithm.output_length;++ // 2. If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":+ // Let mac be the result of performing the KMAC128 function defined in Section 4 of [NIST-SP800-185]+ // using the key represented by [[handle]] internal slot of key as the K input parameter, message as the X input parameter,+ // the outputLength member of normalizedAlgorithm as the L input parameter, and customization as the S input parameter.+ // 2. If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":+ // Let mac be the result of performing the KMAC256 function defined in Section 4 of [NIST-SP800-185]+ // using the key represented by [[handle]] internal slot of key as the K input parameter, message as the X input parameter,+ // the outputLength member of normalizedAlgorithm as the L input parameter, and customization as the S input parameter.+ let mac = kmac_calculate_mac(+ &algorithm.name,+ key_data,+ message.as_slice(),+ output_length,+ customization,+ )?;++ // 3. Let computedMac be a byte sequence containing mac.+ // 4. Return true if computedMac is equal to signature and false otherwise. This comparison must be performed in+ // constant-time.+ // SAFETY: The input bytes live for the duration of the comparison.+ Ok(mac.as_slice().len() == signature.as_slice().len()+ && unsafe { web_crypto_timing_safe_compare(Span::new(mac.as_slice()), Span::new(signature.as_slice())) })+ }+}++impl AlgorithmMethods for KmacKeyGenParams {+ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-generate-key+ fn validate_generate_key_parameters(&self, _: Gc<Realm>) -> WebIdlResult<()> {+ // NB: Generating a key of a length that our KMAC does not support fails.+ let normalized_algorithm = self;+ if let Some(length) = normalized_algorithm.length {+ validate_kmac_key_length(length)?;+ }++ Ok(())+ }++ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-generate-key+ fn generate_key(+ &self,+ cx: &CallContext,+ algorithm: &AlgorithmParams,+ extractable: bool,+ usages: &[KeyUsage],+ ) -> WebIdlResult<CryptoKeyOrCryptoKeyPair> {+ // 1. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.+ for &usage in usages {+ if usage != KeyUsage::Sign && usage != KeyUsage::Verify {+ return Err(Exception::Dom(+ "SyntaxError",+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),+ ));+ }+ }++ let normalized_algorithm = self;++ // 2. If the length member of normalizedAlgorithm is present:+ // Let length be equal to the length member of normalizedAlgorithm.+ // 2. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":+ // Let length be 128.+ // 2. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":+ // Let length be 256.+ let length = if let Some(length) = normalized_algorithm.length {+ length+ } else {+ let Some(kind) = kmac_kind_from_algorithm_name(&algorithm.name) else {+ return Err(dom_error("OperationError", b"Unsupported KMAC algorithm"));+ };+ // SAFETY: The enum variant names a LibCrypto KMAC algorithm.+ unsafe { web_crypto_kmac_default_key_length(kind) }+ };++ validate_kmac_key_length(length)?;++ // 3. Generate a key of length bits.+ // 4. If key generation fails, throw an OperationError.+ let key_data =+ generate_random_key(cx.vm(), length).map_err(|_| dom_error("OperationError", b"Failed to generate key"))?;++ // 5. Let key be a new CryptoKey object representing the generated key.+ let key = CryptoKey::from_byte_handle(cx.vm(), &key_data);++ // 6. Set the [[type]] internal slot of key to "secret".+ key.set_type(KeyType::Secret);++ // 7. Let algorithm be a new KmacKeyAlgorithm.+ // 8. Set the name attribute of algorithm to the name member of normalizedAlgorithm.+ // 9. Set the length attribute of algorithm to length.+ // 10. Set the [[algorithm]] internal slot of key to algorithm.+ key.set_algorithm(InternalAlgorithmData::Kmac {+ name: algorithm.name.clone(),+ length,+ });++ // 11. Set the [[extractable]] internal slot of key to extractable.+ key.set_extractable(extractable);++ // 12. Set the [[usages]] internal slot of key to be the normalized value of usages.+ key.set_usages(normalized_key_usages(usages));++ // 13. Return key.+ Ok(CryptoKeyOrCryptoKeyPair::CryptoKey(key))+ }+}++impl AlgorithmMethods for KmacImportParams {+ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-import-key+ fn validate_import_key_parameters(&self, _: Gc<Realm>) -> WebIdlResult<()> {+ // NB: Importing a key of a length that our KMAC does not support fails.+ let normalized_algorithm = self;+ if let Some(length) = normalized_algorithm.length {+ validate_kmac_key_length(length)?;+ }++ Ok(())+ }++ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-import-key+ #[allow(+ clippy::collapsible_if,+ reason = "the spec checks the JWK algorithm after matching the KMAC variant"+ )]+ #[allow(+ clippy::cast_possible_truncation,+ reason = "the key algorithm's unsigned long length truncates to 32 bits"+ )]+ fn import_key(+ &self,+ cx: &CallContext,+ algorithm: &AlgorithmParams,+ format: KeyFormat,+ key_data: ImportKeyData,+ extractable: bool,+ usages: &[KeyUsage],+ ) -> WebIdlResult<Ref<CryptoKey>> {+ let normalized_algorithm = self;++ // 1. Let keyData be the key data to be imported.++ // 2. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.+ for &usage in usages {+ if usage != KeyUsage::Sign && usage != KeyUsage::Verify {+ return Err(Exception::Dom(+ "SyntaxError",+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),+ ));+ }+ }++ let data;++ // 3. If format is "raw-secret":+ if format == KeyFormat::RawSecret {+ // 1. Let data be keyData.+ let ImportKeyData::Bytes(bytes) = key_data else {+ unreachable!("raw key data contains bytes")+ };+ data = bytes;+ }+ // 3. If format is "jwk":+ else if format == KeyFormat::Jwk {+ // 1. If keyData is a JsonWebKey dictionary:+ // Let jwk equal keyData.+ // Otherwise:+ // Throw a DataError.+ let ImportKeyData::JsonWebKey(jwk) = key_data else {+ return Err(dom_error("DataError", b"Data is not a JsonWebKey dictionary"));+ };++ // 2. If the kty field of jwk is not "oct", then throw a DataError.+ if jwk.kty.as_ref() != Some(&Utf16String::from_ascii(b"oct")) {+ return Err(dom_error("DataError", b"Invalid key type"));+ }++ // 3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA], then throw a DataError.+ // NOTE: parse_jwk_symmetric_key() performs the validation required for symmetric JWKs.++ // 4. Let data be the byte sequence obtained by decoding the k field of jwk.+ data = parse_jwk_symmetric_key(cx.vm(), &jwk)?;++ // 5. -> If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":+ // If the alg field of jwk is present and is not "K128", then throw a DataError.+ // -> If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":+ // If the alg field of jwk is present and is not "K256", then throw a DataError.+ let algorithm_name = &algorithm.name;+ if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"KMAC128")) {+ if jwk+ .alg+ .as_ref()+ .is_some_and(|alg| *alg != Utf16String::from_ascii(b"K128"))+ {+ return Err(dom_error("DataError", b"Invalid alg field for KMAC128"));+ }+ } else if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"KMAC256")) {+ if jwk+ .alg+ .as_ref()+ .is_some_and(|alg| *alg != Utf16String::from_ascii(b"K256"))+ {+ return Err(dom_error("DataError", b"Invalid alg field for KMAC256"));+ }+ }++ // 6. If usages is non-empty and the use field of jwk is present and is not "sig", then throw a DataError.+ if !usages.is_empty()+ && jwk+ .r#use+ .as_ref()+ .is_some_and(|key_use| *key_use != Utf16String::from_ascii(b"sig"))+ {+ return Err(dom_error("DataError", b"Invalid use in JsonWebKey"));+ }++ // 7. If the key_ops field of jwk is present, and is invalid according to the requirements of JSON Web Key [JWK]+ // or does not contain all of the specified usages values, then throw a DataError.+ validate_jwk_key_ops(&jwk, usages)?;++ // 8. If the ext field of jwk is present and has the value false and extractable is true, then throw a DataError.+ if jwk.ext == Some(false) && extractable {+ return Err(dom_error("DataError", b"Invalid ext field"));+ }+ }+ // 3. Otherwise:+ else {+ // 1. Throw a NotSupportedError.+ return Err(dom_error(+ "NotSupportedError",+ b"Only raw-secret and jwk formats are supported",+ ));+ }++ // 4. Let length be the length in bits of data.+ let mut length = (data.as_slice().len() * 8) as u32;++ // 5. If the length member of normalizedAlgorithm is present:+ if let Some(requested_length) = normalized_algorithm.length {+ // 1. If the length member of normalizedAlgorithm is greater than length, then throw a DataError.+ if requested_length > length {+ return Err(dom_error("DataError", b"Invalid data size"));+ }++ // 2. If the length member of normalizedAlgorithm is less than or equal to length minus eight, then throw a DataError.+ if requested_length.wrapping_add(8) <= length {+ return Err(dom_error("DataError", b"Invalid data size"));+ }++ // 3. Otherwise:+ // Set length equal to the length member of normalizedAlgorithm.+ length = requested_length;+ }++ validate_kmac_key_length(length)?;++ // 6. Let key be a new CryptoKey object representing a KMAC key with the first length bits of the Keccak decoding+ // of data.+ // NB: The length is a multiple of 8 and less than 8 bits shorter than data, so the key is all of data.+ let key = CryptoKey::from_byte_handle(cx.vm(), data.as_slice());++ // 7. Set the [[type]] internal slot of key to "secret".+ key.set_type(KeyType::Secret);++ // 8. Let algorithm be a new KmacKeyAlgorithm.+ // 9. Set the name attribute of algorithm to the name member of normalizedAlgorithm.+ // 10. Set the length attribute of algorithm to length.+ // 11. Set the [[algorithm]] internal slot of key to algorithm.+ key.set_algorithm(InternalAlgorithmData::Kmac {+ name: algorithm.name.clone(),+ length,+ });++ // 12. Return key.+ Ok(key)+ }++ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-get-key-length+ fn get_key_length(&self, _: Gc<Realm>, algorithm: &AlgorithmParams) -> WebIdlResult<Option<u32>> {+ let normalized_algorithm = self;++ // 1. If the length member of normalizedAlgorithm is present:+ // Let length be equal to the length member of normalizedAlgorithm.+ let length = if let Some(length) = normalized_algorithm.length {+ length+ }+ // 1. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":+ // Let length be 128.+ // 1. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":+ // Let length be 256.+ else {+ let Some(kind) = kmac_kind_from_algorithm_name(&algorithm.name) else {+ return Err(dom_error("OperationError", b"Unsupported KMAC algorithm"));+ };+ // SAFETY: The enum variant names a LibCrypto KMAC algorithm.+ unsafe { web_crypto_kmac_default_key_length(kind) }+ };++ // 2. Return length.+ Ok(Some(length))+ }+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Kmac;++impl AlgorithmMethods for Kmac {+ // https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-export-key+ #[allow(+ clippy::field_reassign_with_default,+ reason = "the algorithm sets JWK members in separate steps"+ )]+ fn export_key(&self, cx: &CallContext, format: KeyFormat, key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {+ // 1. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be accessed, then throw an OperationError.+ // Note: In our impl this is always accessible++ // 2. If format is "raw-secret":+ let result = if format == KeyFormat::RawSecret {+ // 1. Let result be the raw bits of the key represented by [[handle]] internal slot of key.+ let data = key.byte_handle_bytes();+ ExportKeyResult::Bytes(Bytes::new(data.to_vec()))+ }+ // 2. If format is "jwk":+ else if format == KeyFormat::Jwk {+ // 1. Let jwk be a new JsonWebKey dictionary.+ let mut jwk = JsonWebKey::default();++ // 2. Set the kty attribute of jwk to the string "oct".+ jwk.kty = Some(Utf16String::from_ascii(b"oct"));++ // 3. Set the k attribute of jwk to be a string containing the raw bits of the key represented by [[handle]] internal slot of key,+ // encoded according to JSON Web Algorithms [JWA].+ let key_bytes = key.byte_handle_bytes();+ let Ok(encoded) = base64_url_bytes_encode(key_bytes) else {+ return cx+ .vm()+ .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])+ .map_err(Into::into);+ };+ jwk.k = Some(encoded);++ // 4. Let keyAlgorithm be the [[algorithm]] internal slot of key.+ // 5. -> If the name member of keyAlgorithm is "KMAC128":+ // Set the alg attribute of jwk to the string "K128".+ // -> If the name member of keyAlgorithm is "KMAC256":+ // Set the alg attribute of jwk to the string "K256".+ let algorithm_name = key.algorithm_name();+ if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"KMAC128")) {+ jwk.alg = Some(Utf16String::from_ascii(b"K128"));+ } else if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"KMAC256")) {+ jwk.alg = Some(Utf16String::from_ascii(b"K256"));+ }++ // 6. Set the key_ops attribute of jwk to equal the usages attribute of key.+ jwk.key_ops = Some(+ key.internal_usages()+ .iter()+ .map(|usage| Utf16String::from_ascii(KEY_USAGES[*usage as usize]))+ .collect(),+ );++ // 7. Set the ext attribute of jwk to equal the [[extractable]] internal slot of key.+ jwk.ext = Some(key.is_extractable());++ // 8. Let result be jwk.+ return Ok(ExportKeyResult::JsonWebKey(jwk));+ }+ // 2. Otherwise:+ else {+ // 1. throw a NotSupportedError.+ return Err(dom_error("NotSupportedError", b"Cannot export to unsupported format"));+ };++ // 3. Return result.+ Ok(result)+ }+}+unsafe extern "C" fn receive_bytes(state: *mut c_void, bytes: Span<'_, u8>) {// SAFETY: The state is the caller's slot, and the service lends the bytes.unsafe { *state.cast::<Option<Bytes>>() = Some(Bytes::new(bytes.as_slice().to_vec())) };diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rsindex d4b2234ec78..ede0e993eba 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rs@@ -28,7 +28,7 @@ pub(crate) struct RsaOtherPrimesInfo {pub(crate) t: Option<Utf16String>,}-#[derive(Clone, Trace)]+#[derive(Clone, Default, Trace)]#[gc(crate = libjs_rust)]pub(crate) struct JsonWebKey {pub(crate) alg: Option<Utf16String>,diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rsindex b9e272aa8be..1d87c2553f4 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs@@ -279,6 +279,22 @@ impl CryptoKey {})}+ pub(crate) fn from_byte_handle(vm: &Vm, bytes: &[u8]) -> Ref<Self> {+ // SAFETY: The bytes are lent to the service for the copy.+ let handle = unsafe { web_crypto_key_create_byte_handle(Span::new(bytes)) };+ Self::create(+ vm,+ CryptoKeyHandle(NonNull::new(handle).expect("LibWeb returns a key handle")),+ )+ }++ pub(crate) fn byte_handle_bytes(&self) -> &[u8] {+ let mut bytes = Span::new(&[]);+ // SAFETY: The service borrows bytes from the handle for as long as the key is borrowed.+ unsafe { web_crypto_key_byte_handle_bytes(self.handle().as_ptr(), &mut bytes) };+ bytes.as_slice()+ }+fn handle(&self) -> NonNull<c_void> {self.handle.borrow().as_ref().expect("a live key has its handle").0}@@ -402,6 +418,8 @@ struct RawHandle<'a> {unsafe extern "C" {fn web_crypto_key_destroy_handle(handle: *mut c_void);+ fn web_crypto_key_create_byte_handle(bytes: Span<'_, u8>) -> *mut c_void;+ fn web_crypto_key_byte_handle_bytes(handle: *mut c_void, bytes: &mut Span<'_, u8>);fn web_crypto_key_encode_handle(handle: *mut c_void,state: *mut c_void,@@ -420,7 +438,7 @@ const MAX_HANDLE_BUFFERS: usize = 8;const KEY_TYPES: [&[u8]; 3] = [b"public", b"private", b"secret"];/// The identifiers by which a storage record holds a key usage.-const KEY_USAGES: [&[u8]; 12] = [+pub(super) const KEY_USAGES: [&[u8]; 12] = [b"encrypt",b"decrypt",b"sign",diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rsindex a7511e4d0c1..b690a1796ee 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs@@ -32,7 +32,8 @@ use crate::bindings::promise::{use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};use crate::crypto::crypto_algorithms::{AlgorithmId, AlgorithmMethods, AlgorithmParams, Bytes, CShakeParams, CppAlgorithm, EncapsulatedKeyData,- ExportKeyResult, ImportKeyData, ParameterId, Sha, normalized_key_usages, public_key_for_private_key,+ ExportKeyResult, Hmac, HmacImportParams, HmacKeyGenParams, ImportKeyData, Kmac, KmacImportParams, KmacKeyGenParams,+ KmacParams, ParameterId, Sha, normalized_key_usages, public_key_for_private_key,};#[allow(unused_imports,@@ -87,6 +88,13 @@ pub(crate) enum KeyFormat {enum RegisteredAlgorithm {Cpp(AlgorithmId, ParameterId),Sha,+ Hmac,+ HmacKeyGen,+ HmacImport,+ Kmac,+ KmacSignOrVerify,+ KmacKeyGen,+ KmacImport,CShake,}@@ -98,6 +106,13 @@ type SupportedAlgorithmsMap = HashMap<&'static str, RegisteredAlgorithms>;enum AlgorithmImplementation {Cpp(#[gc(untraced)] Rc<CppAlgorithm>),Sha(Sha),+ Hmac(Hmac),+ HmacKeyGen(HmacKeyGenParams),+ HmacImport(HmacImportParams),+ Kmac(Kmac),+ KmacSignOrVerify(KmacParams),+ KmacKeyGen(KmacKeyGenParams),+ KmacImport(KmacImportParams),CShake(CShakeParams),}@@ -108,6 +123,13 @@ impl Deref for AlgorithmImplementation {match self {Self::Cpp(algorithm) => algorithm.as_ref(),Self::Sha(algorithm) => algorithm,+ Self::Hmac(algorithm) => algorithm,+ Self::HmacKeyGen(algorithm) => algorithm,+ Self::HmacImport(algorithm) => algorithm,+ Self::Kmac(algorithm) => algorithm,+ Self::KmacSignOrVerify(algorithm) => algorithm,+ Self::KmacKeyGen(algorithm) => algorithm,+ Self::KmacImport(algorithm) => algorithm,Self::CShake(algorithm) => algorithm,}}@@ -176,7 +198,7 @@ fn export_key_result_to_bytes(vm: &Vm, result: ExportKeyResult) -> WebIdlResult<Ok(Bytes::new(String::from_utf16_lossy(&json.to_utf16()).into_bytes()))}-fn dom_error(name: &'static str, message: &[u8]) -> Exception {+pub(super) fn dom_error(name: &'static str, message: &[u8]) -> Exception {Exception::Dom(name, Utf16String::from_ascii(message))}@@ -290,6 +312,23 @@ pub(crate) fn normalize_an_algorithm()?))}RegisteredAlgorithm::Sha => AlgorithmImplementation::Sha(Sha),+ RegisteredAlgorithm::Hmac => AlgorithmImplementation::Hmac(Hmac),+ RegisteredAlgorithm::HmacKeyGen => {+ AlgorithmImplementation::HmacKeyGen(HmacKeyGenParams::from_value(vm, realm, *algorithm)?)+ }+ RegisteredAlgorithm::HmacImport => {+ AlgorithmImplementation::HmacImport(HmacImportParams::from_value(vm, realm, *algorithm)?)+ }+ RegisteredAlgorithm::Kmac => AlgorithmImplementation::Kmac(Kmac),+ RegisteredAlgorithm::KmacSignOrVerify => {+ AlgorithmImplementation::KmacSignOrVerify(KmacParams::from_value(vm, *algorithm)?)+ }+ RegisteredAlgorithm::KmacKeyGen => {+ AlgorithmImplementation::KmacKeyGen(KmacKeyGenParams::from_value(vm, *algorithm)?)+ }+ RegisteredAlgorithm::KmacImport => {+ AlgorithmImplementation::KmacImport(KmacImportParams::from_value(vm, *algorithm)?)+ }RegisteredAlgorithm::CShake => AlgorithmImplementation::CShake(CShakeParams::from_value(vm, *algorithm)?),};@@ -620,9 +659,12 @@ impl SubtleCrypto {// 7. Let result be the result of performing the generate key operation specified by normalizedAlgorithm// using algorithm, extractable and usages.- let result_or_error = normalized_algorithm- .methods- .generate_key(realm, extractable, &key_usages);+ let result_or_error = normalized_algorithm.methods.generate_key(+ &CallContext::new(vm, realm),+ &normalized_algorithm.parameter,+ extractable,+ &key_usages,+ );if let Err(error) = result_or_error {reject_promise_with_exception(vm, promise, error);@@ -780,10 +822,14 @@ impl SubtleCrypto {// 9. Let result be the CryptoKey object that results from performing the import key operation// specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.- let maybe_result =- normalized_algorithm- .methods- .import_key(realm, format, real_key_data, extractable, &key_usages);+ let maybe_result = normalized_algorithm.methods.import_key(+ &CallContext::new(vm, realm),+ &normalized_algorithm.parameter,+ format,+ real_key_data,+ extractable,+ &key_usages,+ );if let Err(error) = maybe_result {reject_promise_with_exception(vm, promise, error);return;@@ -872,7 +918,10 @@ impl SubtleCrypto {}// 7. Let result be the result of performing the export key operation specified by the [[algorithm]] internal slot of key using key and format.- let result_or_error = normalized_algorithm.methods.export_key(realm, format, key);+ let result_or_error =+ normalized_algorithm+ .methods+ .export_key(&CallContext::new(vm, realm), format, key);if let Err(error) = result_or_error {reject_promise_with_exception(vm, promise, error);return;@@ -963,7 +1012,10 @@ impl SubtleCrypto {// 11. Let signature be the result of performing the sign operation specified by normalizedAlgorithm using key// and algorithm and with data as message.- let signature = normalized_algorithm.methods.sign(realm, key, &data);+ let signature =+ normalized_algorithm+ .methods+ .sign(realm, &normalized_algorithm.parameter, key, &data);if let Err(error) = signature {throw_in_this_context(error);return;@@ -1069,7 +1121,13 @@ impl SubtleCrypto {// 12. Let result be the result of performing the verify operation specified by normalizedAlgorithm using key,// algorithm and signature and with data as message.- let result = normalized_algorithm.methods.verify(realm, key, &signature, &data);+ let result = normalized_algorithm.methods.verify(+ realm,+ &normalized_algorithm.parameter,+ key,+ &signature,+ &data,+ );if let Err(error) = result {throw_in_this_context(error);return;@@ -1260,7 +1318,9 @@ impl SubtleCrypto {}// 13. Let length be the result of performing the get key length algorithm specified by normalizedDerivedKeyAlgorithmLength using derivedKeyType.- let length_result = normalized_derived_key_algorithm_length.methods.get_key_length(realm);+ let length_result = normalized_derived_key_algorithm_length+ .methods+ .get_key_length(realm, &normalized_derived_key_algorithm_length.parameter);if let Err(error) = length_result {reject_promise_with_exception(vm, promise, error);return;@@ -1278,7 +1338,8 @@ impl SubtleCrypto {// 15. Let result be the result of performing the import key operation specified by normalizedDerivedKeyAlgorithmImport using "raw" as format, secret as keyData, derivedKeyType as algorithm and using extractable and usages.let secret_bytes = secret.must();let result_or_error = normalized_derived_key_algorithm_import.methods.import_key(- realm,+ &CallContext::new(vm, realm),+ &normalized_derived_key_algorithm_import.parameter,KeyFormat::Raw,ImportKeyData::Bytes(secret_bytes),extractable,@@ -1430,7 +1491,11 @@ impl SubtleCrypto {return;}- let exported_key_or_error = normalized_key_algorithm.must().methods.export_key(realm, format, key);+ let exported_key_or_error =+ normalized_key_algorithm+ .must()+ .methods+ .export_key(&CallContext::new(vm, realm), format, key);if let Err(error) = exported_key_or_error {reject_promise_with_exception(vm, promise, error);return;@@ -1660,10 +1725,14 @@ impl SubtleCrypto {// 16. Let result be the result of performing the import key operation specified by normalizedKeyAlgorithm// using unwrappedKeyAlgorithm as algorithm, format, usages and extractable and with key as keyData.- let result_or_error =- normalized_key_algorithm- .methods- .import_key(realm, format, key, extractable, &key_usages);+ let result_or_error = normalized_key_algorithm.methods.import_key(+ &CallContext::new(vm, realm),+ &normalized_key_algorithm.parameter,+ format,+ key,+ extractable,+ &key_usages,+ );if let Err(error) = result_or_error {reject_promise_with_exception(vm, promise, error);return;@@ -1814,7 +1883,8 @@ impl SubtleCrypto {// normalizedSharedKeyAlgorithm using "raw-secret" as format, the sharedKey field of encapsulatedBits as// keyData, sharedKeyAlgorithm as algorithm and using extractable and usages.let maybe_shared_key = normalized_shared_key_algorithm.methods.import_key(- realm,+ &CallContext::new(vm, realm),+ &normalized_shared_key_algorithm.parameter,KeyFormat::RawSecret,ImportKeyData::Bytes(encapsulated_bits@@ -2095,7 +2165,8 @@ impl SubtleCrypto {// normalizedSharedKeyAlgorithm using "raw-secret" as format, the decapsulatedBits as keyData,// sharedKeyAlgorithm as algorithm and using extractable and usages.let maybe_shared_key = normalized_shared_key_algorithm.methods.import_key(- realm,+ &CallContext::new(vm, realm),+ &normalized_shared_key_algorithm.parameter,KeyFormat::RawSecret,ImportKeyData::Bytes(decapsulated_bits),extractable,@@ -2482,7 +2553,14 @@ impl SubtleCrypto {let import_algorithm = normalized_additional_algorithm;if import_algorithm.methods- .import_key(realm, KeyFormat::RawSecret, key_data, false, &[])+ .import_key(+ &CallContext::new(vm, realm),+ &import_algorithm.parameter,+ KeyFormat::RawSecret,+ key_data,+ false,+ &[],+ ).is_err(){return Ok(false);@@ -2512,7 +2590,9 @@ impl SubtleCrypto {// 3. Let length be the result of performing the get key length algorithm specified by additionalAlgorithm// using normalizedAdditionalAlgorithm.let normalized_length_algorithm = normalized_additional_algorithm.must();- let key_length = normalized_length_algorithm.methods.get_key_length(realm);+ let key_length = normalized_length_algorithm+ .methods+ .get_key_length(realm, &normalized_length_algorithm.parameter);if key_length.is_err() {return Ok(false);}@@ -2581,7 +2661,7 @@ fn determine_support_from_operation_steps(return methods.validate_derive_bits_parameters(realm, length);}if op == "get key length" {- methods.get_key_length(realm)?;+ methods.get_key_length(realm, &normalized_algorithm.parameter)?;}Ok(())})();@@ -3010,41 +3090,26 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {);// https://w3c.github.io/webcrypto/#hmac-registration- define_an_algorithm(- &mut internal_object,- "sign",- "HMAC",- RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::AlgorithmParams),- );- define_an_algorithm(- &mut internal_object,- "verify",- "HMAC",- RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::AlgorithmParams),- );+ define_an_algorithm(&mut internal_object, "sign", "HMAC", RegisteredAlgorithm::Hmac);+ define_an_algorithm(&mut internal_object, "verify", "HMAC", RegisteredAlgorithm::Hmac);define_an_algorithm(&mut internal_object,"generateKey","HMAC",- RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::HmacKeyGenParams),+ RegisteredAlgorithm::HmacKeyGen,);define_an_algorithm(&mut internal_object,"importKey","HMAC",- RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::HmacImportParams),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "HMAC",- RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::AlgorithmParams),+ RegisteredAlgorithm::HmacImport,);+ define_an_algorithm(&mut internal_object, "exportKey", "HMAC", RegisteredAlgorithm::Hmac);define_an_algorithm(&mut internal_object,"get key length","HMAC",- RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::HmacImportParams),+ RegisteredAlgorithm::HmacImport,);// https://w3c.github.io/webcrypto/#sha-registration@@ -3396,37 +3461,32 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {&mut internal_object,"sign",algorithm,- RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacParams),+ RegisteredAlgorithm::KmacSignOrVerify,);define_an_algorithm(&mut internal_object,"verify",algorithm,- RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacParams),+ RegisteredAlgorithm::KmacSignOrVerify,);define_an_algorithm(&mut internal_object,"generateKey",algorithm,- RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacKeyGenParams),+ RegisteredAlgorithm::KmacKeyGen,);define_an_algorithm(&mut internal_object,"importKey",algorithm,- RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacImportParams),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- algorithm,- RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::AlgorithmParams),+ RegisteredAlgorithm::KmacImport,);+ define_an_algorithm(&mut internal_object, "exportKey", algorithm, RegisteredAlgorithm::Kmac);define_an_algorithm(&mut internal_object,"get key length",algorithm,- RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacImportParams),+ RegisteredAlgorithm::KmacImport,);}diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cppindex f44283b1856..1a2675d99cc 100644--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp@@ -61,7 +61,7 @@ enum class Base64DecodeResult : u8 {InvalidBase64,NonAscii,};-Base64DecodeResult web_crypto_decode_base64url(FlatPtr, ByteBuffer*, FlatPtr*);+Base64DecodeResult web_crypto_decode_base64url(FlatPtr, ByteBuffer*, void*, ReceiveEncodedBytes, FlatPtr*);Base64DecodeResult web_rust_crypto_base64_url_bytes_decode(FlatPtr, ByteBuffer*, FlatPtr*);enum class Asn1Structure : u8 {@@ -248,7 +248,7 @@ ErrorOr<Utf16String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integerreturn TRY(base64_url_bytes_encode(result));}-Base64DecodeResult web_crypto_decode_base64url(FlatPtr raw, ByteBuffer* bytes, FlatPtr* error_message)+Base64DecodeResult web_crypto_decode_base64url(FlatPtr raw, ByteBuffer* bytes, void* state, ReceiveEncodedBytes receive, FlatPtr* error_message){auto base64_url_string = Utf16String::from_raw(raw);auto base64_bytes_or_error = decode_base64url(base64_url_string.to_byte_string(), AK::LastChunkHandling::Loose);@@ -258,7 +258,10 @@ Base64DecodeResult web_crypto_decode_base64url(FlatPtr raw, ByteBuffer* bytes, F*error_message = Utf16String::formatted("{}", base64_bytes_or_error.release_error()).into_raw();return Base64DecodeResult::InvalidBase64;}- *bytes = base64_bytes_or_error.release_value();+ if (receive)+ receive(state, base64_bytes_or_error.value());+ else+ *bytes = base64_bytes_or_error.release_value();return Base64DecodeResult::Success;}@@ -450,17 +453,6 @@ static WebIDL::ExceptionOr<ByteBuffer> generate_random_key(JS::VM& vm, u32 constreturn key_buffer;}-// NB: Our KMAC implementation is byte-oriented, so it cannot use keys with a partial last byte. OpenSSL also only-// accepts KMAC keys of up to 512 bytes.-static WebIDL::ExceptionOr<void> validate_kmac_key_length(WebIDL::UnsignedLong length_in_bits)-{- if (length_in_bits % 8 != 0)- return WebIDL::NotSupportedError::create("KMAC key length must be a multiple of 8"_utf16);- if (length_in_bits > 512 * 8)- return WebIDL::NotSupportedError::create("KMAC key length must not exceed 4096 bits"_utf16);- return {};-}-AlgorithmParams::~AlgorithmParams() = default;AesCbcParams::~AesCbcParams() = default;@@ -738,44 +730,6 @@ JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> EcKeyImportParams::from_vareturn adopt_own<AlgorithmParams>(*new EcKeyImportParams { named_curve });}-HmacImportParams::~HmacImportParams() = default;--JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> HmacImportParams::from_value(JS::Realm& realm, JS::Value value)-{- auto& vm = realm.vm();- auto& object = value.as_object();-- auto hash_value = TRY(object.get("hash"_utf16_fly_string));- auto hash = TRY(hash_algorithm_identifier_from_value(realm, hash_value));-- auto maybe_length = Optional<WebIDL::UnsignedLong> {};- if (TRY(object.has_property("length"_utf16_fly_string))) {- auto length_value = TRY(object.get("length"_utf16_fly_string));- maybe_length = TRY(WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, length_value, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No));- }-- return adopt_own<AlgorithmParams>(*new HmacImportParams { hash, maybe_length });-}--HmacKeyGenParams::~HmacKeyGenParams() = default;--JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> HmacKeyGenParams::from_value(JS::Realm& realm, JS::Value value)-{- auto& vm = realm.vm();- auto& object = value.as_object();-- auto hash_value = TRY(object.get("hash"_utf16_fly_string));- auto hash = TRY(hash_algorithm_identifier_from_value(realm, hash_value));-- auto maybe_length = Optional<WebIDL::UnsignedLong> {};- if (TRY(object.has_property("length"_utf16_fly_string))) {- auto length_value = TRY(object.get("length"_utf16_fly_string));- maybe_length = TRY(WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, length_value, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No));- }-- return adopt_own<AlgorithmParams>(*new HmacKeyGenParams { hash, maybe_length });-}-Ed448Params::~Ed448Params() = default;JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> Ed448Params::from_value(JS::Realm& realm, JS::Value value)@@ -847,67 +801,6 @@ JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> Argon2Params::from_value(Jreturn adopt_own<AlgorithmParams>(*new Argon2Params { nonce, parallelism, memory, passes, maybe_version, secret_value, associated_data });}-KmacParams::~KmacParams() = default;--// https://wicg.github.io/webcrypto-modern-algos/#kmac-params-JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> KmacParams::from_value(JS::Realm& realm, JS::Value value)-{- auto& vm = realm.vm();- VERIFY(value.is_object());- auto& object = value.as_object();-- // 1. If the outputLength member is missing, throw a TypeError.- if (!TRY(object.has_property("outputLength"_utf16_fly_string))) {- return vm.throw_completion<JS::TypeError>(JS::ErrorType::MissingRequiredProperty, "outputLength");- }-- auto const output_length = TRY(object.get("outputLength"_utf16_fly_string));- auto const length = TRY(WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, output_length, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No));-- // 2. Let customization be the optional customization member or the empty octet string.- auto const customization = TRY(get_optional_buffer_source(vm, object, "customization"_utf16_fly_string));-- return adopt_own<AlgorithmParams>(*new KmacParams { length, customization });-}--KmacKeyGenParams::~KmacKeyGenParams() = default;--// https://wicg.github.io/webcrypto-modern-algos/#kmac-keygen-params-JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> KmacKeyGenParams::from_value(JS::Realm& realm, JS::Value value)-{- auto& vm = realm.vm();- VERIFY(value.is_object());- auto& object = value.as_object();-- // 1. If the length member is present, record its unsigned long value; otherwise leave it unset.- auto maybe_length = Optional<WebIDL::UnsignedLong> {};- if (TRY(object.has_property("length"_utf16_fly_string))) {- auto length_value = TRY(object.get("length"_utf16_fly_string));- maybe_length = TRY(WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, length_value, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No));- }-- return adopt_own<AlgorithmParams>(*new KmacKeyGenParams { maybe_length });-}--KmacImportParams::~KmacImportParams() = default;--// https://wicg.github.io/webcrypto-modern-algos/#kmac-import-params-JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> KmacImportParams::from_value(JS::Realm& realm, JS::Value value)-{- auto& vm = realm.vm();- VERIFY(value.is_object());- auto& object = value.as_object();-- // 1. If the length member is present, record its unsigned long value; otherwise leave it unset.- auto maybe_length = Optional<WebIDL::UnsignedLong> {};- if (TRY(object.has_property("length"_utf16_fly_string))) {- auto length_value = TRY(object.get("length"_utf16_fly_string));- maybe_length = TRY(WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, length_value, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No));- }-- return adopt_own<AlgorithmParams>(*new KmacImportParams { maybe_length });-}-// https://w3c.github.io/webcrypto/#rsa-oaep-operations-encryptWebIDL::ExceptionOr<ByteBuffer> RSAOAEP::encrypt(JS::Realm&, AlgorithmParams const& params, GC::Ref<CryptoKey> key, ByteBuffer const& plaintext){@@ -8271,431 +8164,27 @@ WebIDL::ExceptionOr<GC::Ref<CryptoKey>> X448::import_key(JS::Realm& realm,return WebIDL::NotSupportedError::create("Invalid key format"_utf16);}-static WebIDL::ExceptionOr<ByteBuffer> hmac_calculate_message_digest(JS::Realm&, Utf16String const& hash_name, ReadonlyBytes key, ReadonlyBytes message)-{- auto hash_kind = TRY([&] -> WebIDL::ExceptionOr<::Crypto::Hash::HashKind> {- if (hash_name == "SHA-1"sv)- return ::Crypto::Hash::HashKind::SHA1;- if (hash_name == "SHA-256"sv)- return ::Crypto::Hash::HashKind::SHA256;- if (hash_name == "SHA-384"sv)- return ::Crypto::Hash::HashKind::SHA384;- if (hash_name == "SHA-512"sv)- return ::Crypto::Hash::HashKind::SHA512;- return WebIDL::NotSupportedError::create(Utf16String::formatted("Invalid hash function '{}'", hash_name));- }());-- ::Crypto::Authentication::HMAC hmac(hash_kind, key);- return hmac.process(message);-}--static WebIDL::ExceptionOr<WebIDL::UnsignedLong> hmac_hash_block_size(HashAlgorithmIdentifier hash)-{- auto hash_name = hash.name;- if (hash_name == "SHA-1"sv)- return ::Crypto::Hash::SHA1::block_size();- if (hash_name == "SHA-256"sv)- return ::Crypto::Hash::SHA256::block_size();- if (hash_name == "SHA-384"sv)- return ::Crypto::Hash::SHA384::block_size();- if (hash_name == "SHA-512"sv)- return ::Crypto::Hash::SHA512::block_size();- return WebIDL::NotSupportedError::create(Utf16String::formatted("Invalid hash function '{}'", hash_name));-}--// https://w3c.github.io/webcrypto/#hmac-operations-sign-WebIDL::ExceptionOr<ByteBuffer> HMAC::sign(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey> key, ByteBuffer const& message)-{- // 1. Let mac be the result of performing the MAC Generation operation described in Section 4 of- // [FIPS-198-1] using the key represented by [[handle]] internal slot of key, the hash- // function identified by the hash attribute of the [[algorithm]] internal slot of key and- // message as the input data text.- auto const& key_data = key->handle().get<ByteBuffer>();- auto const& algorithm = key->hmac_algorithm();- auto mac = TRY(hmac_calculate_message_digest(realm, algorithm.hash(), key_data.bytes(), message.bytes()));-- // 2. Return the result of creating an ArrayBuffer containing mac.- return mac;-}--// https://w3c.github.io/webcrypto/#hmac-operations-verify-WebIDL::ExceptionOr<bool> HMAC::verify(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey> key, ByteBuffer const& signature, ByteBuffer const& message)-{- // 1. Let mac be the result of performing the MAC Generation operation described in Section 4 of- // [FIPS-198-1] using the key represented by [[handle]] internal slot of key, the hash- // function identified by the hash attribute of the [[algorithm]] internal slot of key and- // message as the input data text.- auto const& key_data = key->handle().get<ByteBuffer>();- auto const& algorithm = key->hmac_algorithm();- auto mac = TRY(hmac_calculate_message_digest(realm, algorithm.hash(), key_data.bytes(), message.bytes()));-- // 2. Return true if mac is equal to signature and false otherwise. This comparison must be performed in- // constant-time.- return mac.size() == signature.size() && timing_safe_compare(mac.data(), signature.data(), mac.size());-}--// https://w3c.github.io/webcrypto/#hmac-operations-generate-key-WebIDL::ExceptionOr<void> HMAC::validate_generate_key_parameters(AlgorithmParams const& params) const-{- auto const& normalized_algorithm = static_cast<HmacKeyGenParams const&>(params);-- // NB: Step 2 throws an error when the length member of normalizedAlgorithm is not present and we do not know the- // block size of the hash function, or when the length member is zero.- if (!normalized_algorithm.length.has_value())- TRY(hmac_hash_block_size(normalized_algorithm.hash));- else if (normalized_algorithm.length.value() == 0)- return WebIDL::OperationError::create("Invalid length"_utf16);-- return {};-}--// https://w3c.github.io/webcrypto/#hmac-operations-generate-key-WebIDL::ExceptionOr<Variant<GC::Ref<CryptoKey>, CryptoKeyPair>> HMAC::generate_key(JS::Realm& realm, AlgorithmParams const& params, bool extractable, Vector<KeyUsage> const& usages)-{- // 1. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.- for (auto const& usage : usages) {- if (usage != KeyUsage::Sign && usage != KeyUsage::Verify)- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));- }-- // 2. If the length member of normalizedAlgorithm is not present:- auto const& normalized_algorithm = static_cast<HmacKeyGenParams const&>(params);- WebIDL::UnsignedLong length;- if (!normalized_algorithm.length.has_value()) {- // Let length be the block size in bits of the hash function identified by the hash member- // of normalizedAlgorithm.- length = TRY(hmac_hash_block_size(normalized_algorithm.hash)) * 8;- }-- // Otherwise, if the length member of normalizedAlgorithm is non-zero:- else if (normalized_algorithm.length.value() != 0) {- // Let length be equal to the length member of normalizedAlgorithm.- length = normalized_algorithm.length.value();- }-- // Otherwise:- else {- // throw an OperationError.- return WebIDL::OperationError::create("Invalid length"_utf16);- }-- // 3. Generate a key of length length bits.- // 4. If the key generation step fails, then throw an OperationError.- auto key_data_or_error = generate_random_key(realm.vm(), length);- if (key_data_or_error.is_error())- return WebIDL::OperationError::create("Failed to generate key"_utf16);- auto key_data = key_data_or_error.release_value();-- // 5. Let key be a new CryptoKey object representing the generated key.- auto key = CryptoKey::create(move(key_data));-- // 6. Let algorithm be a new HmacKeyAlgorithm.- // 7. Set the name attribute of algorithm to "HMAC".- // 8. Let hash be a new KeyAlgorithm.- // 9. Set the name attribute of hash to equal the name member of the hash member of normalizedAlgorithm.- auto hash_name = normalized_algorithm.hash.name;-- // 12. Set the [[type]] internal slot of key to "secret".- key->set_type(KeyType::Secret);-- // 10. Set the hash attribute of algorithm to hash.- // 11. Set the length attribute of algorithm to length.- // 13. Set the [[algorithm]] internal slot of key to algorithm.- key->set_algorithm(CryptoKey::HmacKeyAlgorithmData { "HMAC"_utf16, move(hash_name), static_cast<WebIDL::UnsignedLong>(length) });-- // 14. Set the [[extractable]] internal slot of key to be extractable.- key->set_extractable(extractable);-- // 15. Set the [[usages]] internal slot of key to be the normalized value of usages.- key->set_usages(normalized_key_usages(usages));-- // 16. Return key.- return Variant<GC::Ref<CryptoKey>, CryptoKeyPair> { key };-}--// https://w3c.github.io/webcrypto/#hmac-operations-import-key-WebIDL::ExceptionOr<void> HMAC::validate_import_key_parameters(AlgorithmParams const& params) const-{- auto const& normalized_algorithm = static_cast<HmacImportParams const&>(params);-- // 1. If the length member of normalizedAlgorithm is present and is zero, then throw a DataError.- if (normalized_algorithm.length.has_value() && *normalized_algorithm.length == 0)- return WebIDL::DataError::create("Invalid key length"_utf16);-- return {};+extern "C" {+void web_crypto_hmac_sign(::Crypto::Hash::HashKind, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);+bool web_crypto_timing_safe_compare(ReadonlyBytes, ReadonlyBytes);}-// https://w3c.github.io/webcrypto/#hmac-operations-import-key-WebIDL::ExceptionOr<GC::Ref<CryptoKey>> HMAC::import_key(JS::Realm& realm, Web::Crypto::AlgorithmParams const& params, KeyFormat key_format, CryptoKey::ImportKeyData key_data, bool extractable, Vector<KeyUsage> const& usages)-{- auto const& normalized_algorithm = static_cast<HmacImportParams const&>(params);-- // NB: Step 1 is performed by validate_import_key_parameters().- TRY(validate_import_key_parameters(params));-- // 2. Let keyData be the key data to be imported.- // 3. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.- for (auto const& usage : usages) {- if (usage != KeyUsage::Sign && usage != KeyUsage::Verify)- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));- }-- // 4. Let hash be a new KeyAlgorithm.- Utf16String hash_name;-- // 5. If format is "raw":- AK::ByteBuffer data;- if (key_format == KeyFormat::Raw- || key_format == KeyFormat::RawSecret) {- // 5.1. Let data be the octet string contained in keyData.- data = move(key_data.get<ByteBuffer>());-- // 5.2. Set hash to equal the hash member of normalizedAlgorithm.- hash_name = normalized_algorithm.hash.name;- }-- // If format is "jwk":- else if (key_format == KeyFormat::Jwk) {- // 1. If keyData is a JsonWebKey dictionary:- // Let jwk equal keyData.- // Otherwise:- // Throw a DataError.- if (!key_data.has<JsonWebKey>())- return WebIDL::DataError::create("Data is not a JsonWebKey dictionary"_utf16);- auto& jwk = key_data.get<JsonWebKey>();-- // 2. If the kty field of jwk is not "oct", then throw a DataError.- if (jwk.kty != "oct"sv)- return WebIDL::DataError::create("Invalid key type"_utf16);-- // 3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA],- // then throw a DataError.- // 4. Let data be the octet string obtained by decoding the k field of jwk.- data = TRY(parse_jwk_symmetric_key(realm, jwk));-- // 5. Set the hash to equal the hash member of normalizedAlgorithm.- hash_name = normalized_algorithm.hash.name;-- // 6. If the name attribute of hash is "SHA-1":- if (hash_name == "SHA-1"_utf16) {- // If the alg field of jwk is present and is not "HS1", then throw a DataError.- if (jwk.alg.has_value() && jwk.alg != "HS1"sv)- return WebIDL::DataError::create("Invalid algorithm"_utf16);- }-- // If the name attribute of hash is "SHA-256":- else if (hash_name == "SHA-256"sv) {- // If the alg field of jwk is present and is not "HS256", then throw a DataError.- if (jwk.alg.has_value() && jwk.alg != "HS256"sv)- return WebIDL::DataError::create("Invalid algorithm"_utf16);- }-- // If the name attribute of hash is "SHA-384":- else if (hash_name == "SHA-384"sv) {- // If the alg field of jwk is present and is not "HS384", then throw a DataError.- if (jwk.alg.has_value() && jwk.alg != "HS384"sv)- return WebIDL::DataError::create("Invalid algorithm"_utf16);- }-- // If the name attribute of hash is "SHA-512":- else if (hash_name == "SHA-512"sv) {- // If the alg field of jwk is present and is not "HS512", then throw a DataError.- if (jwk.alg.has_value() && jwk.alg != "HS512"sv)- return WebIDL::DataError::create("Invalid algorithm"_utf16);- }-- // Otherwise, if the name attribute of hash is defined in another applicable specification:- else {- // Perform any key import steps defined by other applicable specifications, passing format,- // jwk and hash and obtaining hash.- return WebIDL::DataError::create("Invalid algorithm"_utf16);- }-- // 7. If usages is non-empty and the use field of jwk is present and is not "sig", then- // throw a DataError.- if (!usages.is_empty() && jwk.use.has_value() && jwk.use != "sig"sv)- return WebIDL::DataError::create("Invalid use in JsonWebKey"_utf16);+static_assert(::Crypto::Hash::SHA1::block_size() == 64);+static_assert(::Crypto::Hash::SHA256::block_size() == 64);+static_assert(::Crypto::Hash::SHA384::block_size() == 128);+static_assert(::Crypto::Hash::SHA512::block_size() == 128);- // 8. If the key_ops field of jwk is present, and is invalid according to the requirements- // of JSON Web Key [JWK] or does not contain all of the specified usages values, then- // throw a DataError.- TRY(validate_jwk_key_ops(realm, jwk, usages));-- // 9. If the ext field of jwk is present and has the value false and extractable is true,- // then throw a DataError.- if (jwk.ext.has_value() && !*jwk.ext && extractable)- return WebIDL::DataError::create("Invalid ext field"_utf16);- }-- // Otherwise:- else {- // throw a NotSupportedError.- return WebIDL::NotSupportedError::create("Invalid key format"_utf16);- }-- // 6. Let length be equivalent to the length, in octets, of data, multiplied by 8.- auto length = data.size() * 8;-- // 7. If length is zero then throw a DataError.- if (length == 0)- return WebIDL::DataError::create("No data provided"_utf16);-- // 8. If the length member of normalizedAlgorithm is present:- if (normalized_algorithm.length.has_value()) {- // If the length member of normalizedAlgorithm is greater than length:- auto normalized_algorithm_length = normalized_algorithm.length.value();- if (normalized_algorithm_length > length) {- // throw a DataError.- return WebIDL::DataError::create("Invalid data size"_utf16);- }-- // If the length member of normalizedAlgorithm, is less than or equal to length minus eight:- if (normalized_algorithm_length <= length - 8) {- // throw a DataError.- return WebIDL::DataError::create("Invalid data size"_utf16);- }-- // Otherwise:- // Set length equal to the length member of normalizedAlgorithm.- length = normalized_algorithm_length;- }-- // 9. Let key be a new CryptoKey object representing an HMAC key with the first length bits of data.- keep_first_bits(data, length);- auto key = CryptoKey::create(move(data));-- // 10. Set the [[type]] internal slot of key to "secret".- key->set_type(KeyType::Secret);-- // 11. Let algorithm be a new HmacKeyAlgorithm.- // 12. Set the name attribute of algorithm to "HMAC".- // 13. Set the length attribute of algorithm to length.- // 14. Set the hash attribute of algorithm to hash.- // 15. Set the [[algorithm]] internal slot of key to algorithm.- key->set_algorithm(CryptoKey::HmacKeyAlgorithmData { "HMAC"_utf16, move(hash_name), static_cast<WebIDL::UnsignedLong>(length) });-- // 16. Return key.- return key;-}--// https://w3c.github.io/webcrypto/#hmac-operations-export-key-WebIDL::ExceptionOr<ExportKeyResult> HMAC::export_key(JS::Realm&, KeyFormat format, GC::Ref<CryptoKey> key)+void web_crypto_hmac_sign(::Crypto::Hash::HashKind hash_kind, ReadonlyBytes key, ReadonlyBytes message, void* state, ReceiveEncodedBytes receive){- // 1. If the underlying cryptographic key material represented by the [[handle]] internal slot- // of key cannot be accessed, then throw an OperationError.- // NOTE: In our impl this is always accessible-- // 2. Let bits be the raw bits of the key represented by [[handle]] internal slot of key.- // 3. Let data be an octet string containing bits.- auto data = key->handle().get<ByteBuffer>();-- // 4. If format is "raw":- // https://wicg.github.io/webcrypto-modern-algos/#subtlecrypto-interface-keyformat- // For all existing symmetric algorithms in WebCrypto, "raw-secret" acts as an alias of "raw".- Optional<ExportKeyResult> result;- if (format == KeyFormat::Raw || format == KeyFormat::RawSecret) {- // Let result be the result of creating an ArrayBuffer containing data.- result = ExportKeyResult { data };- }-- // If format is "jwk":- else if (format == KeyFormat::Jwk) {- // Let jwk be a new JsonWebKey dictionary.- JsonWebKey jwk {};-- // Set the kty attribute of jwk to the string "oct".- jwk.kty = "oct"_utf16;-- // Set the k attribute of jwk to be a string containing data, encoded according to Section- // 6.4 of JSON Web Algorithms [JWA].- jwk.k = MUST(base64_url_bytes_encode(data));-- // Let algorithm be the [[algorithm]] internal slot of key.- auto const& algorithm = key->hmac_algorithm();-- // Let hash be the hash attribute of algorithm.- // If the name attribute of hash is "SHA-1":- auto hash_name = algorithm.hash();- if (hash_name == "SHA-1"_utf16) {- // Set the alg attribute of jwk to the string "HS1".- jwk.alg = "HS1"_utf16;- }- // If the name attribute of hash is "SHA-256":- else if (hash_name == "SHA-256"sv) {- // Set the alg attribute of jwk to the string "HS256".- jwk.alg = "HS256"_utf16;- }- // If the name attribute of hash is "SHA-384":- else if (hash_name == "SHA-384"sv) {- // Set the alg attribute of jwk to the string "HS384".- jwk.alg = "HS384"_utf16;- }- // If the name attribute of hash is "SHA-512":- else if (hash_name == "SHA-512"sv) {- // Set the alg attribute of jwk to the string "HS512".- jwk.alg = "HS512"_utf16;- }-- // Otherwise, the name attribute of hash is defined in another applicable- // specification:- else {- // Perform any key export steps defined by other applicable specifications,- // passing format and key and obtaining alg.- // Set the alg attribute of jwk to alg.- return WebIDL::DataError::create("Invalid algorithm"_utf16);- }-- // Set the key_ops attribute of jwk to equal the usages attribute of key.- jwk.key_ops = Vector<Utf16String> {};- jwk.key_ops->ensure_capacity(key->internal_usages().size());- for (auto const& usage : key->internal_usages()) {- jwk.key_ops->unchecked_append(Utf16String::from_utf8(key_usage_to_string(usage)));- }-- // Set the ext attribute of jwk to equal the [[extractable]] internal slot of key.- jwk.ext = key->extractable();-- // Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL].- result = ExportKeyResult { move(jwk) };- }-- // Otherwise:- else {- // throw a NotSupportedError.- return WebIDL::NotSupportedError::create("Invalid key format"_utf16);- }-- // 5. Return result.- return result.release_value();+ ::Crypto::Authentication::HMAC hmac(hash_kind, key);+ auto mac = hmac.process(message);+ receive(state, mac);}-// https://w3c.github.io/webcrypto/#hmac-operations-get-key-length-WebIDL::ExceptionOr<Optional<u32>> HMAC::get_key_length(JS::Realm&, AlgorithmParams const& params)+bool web_crypto_timing_safe_compare(ReadonlyBytes left, ReadonlyBytes right){- auto const& normalized_derived_key_algorithm = static_cast<HmacImportParams const&>(params);- WebIDL::UnsignedLong length;-- // 1. If the length member of normalizedDerivedKeyAlgorithm is not present:- if (!normalized_derived_key_algorithm.length.has_value()) {- // Let length be the block size in bits of the hash function identified by the hash member of- // normalizedDerivedKeyAlgorithm.- length = TRY(hmac_hash_block_size(normalized_derived_key_algorithm.hash)) * 8;- }-- // Otherwise, if the length member of normalizedDerivedKeyAlgorithm is non-zero:- else if (normalized_derived_key_algorithm.length.value() > 0) {- // Let length be equal to the length member of normalizedDerivedKeyAlgorithm.- length = normalized_derived_key_algorithm.length.value();- }-- // Otherwise:- else {- // throw a TypeError.- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid key length"_utf16 };- }-- // 2. Return length.- return length;+ VERIFY(left.size() == right.size());+ return timing_safe_compare(left.data(), right.data(), left.size());}// https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-operations-sign@@ -10697,407 +10186,33 @@ WebIDL::ExceptionOr<Optional<u32>> AesOcb::get_key_length(JS::Realm&, AlgorithmPreturn length;}-static Optional<::Crypto::Authentication::KMACKind> kmac_kind_from_algorithm_name(Utf16View algorithm_name)-{- if (algorithm_name == "KMAC128"sv)- return ::Crypto::Authentication::KMACKind::KMAC128;- if (algorithm_name == "KMAC256"sv)- return ::Crypto::Authentication::KMACKind::KMAC256;- return {};-}--static WebIDL::ExceptionOr<ByteBuffer> kmac_calculate_mac(- JS::Realm&,- Utf16View algorithm_name,- ReadonlyBytes key,- ReadonlyBytes message,- u32 output_length_bits,- Optional<ReadonlyBytes> customization)-{- auto kind = kmac_kind_from_algorithm_name(algorithm_name);- if (!kind.has_value())- return WebIDL::OperationError::create("Unsupported KMAC algorithm"_utf16);- ::Crypto::Authentication::KMAC kmac(*kind);-- auto maybe_result = kmac.sign(key, message, output_length_bits, customization);- if (maybe_result.is_error())- return WebIDL::OperationError::create("KMAC operation failed"_utf16);-- return maybe_result.release_value();-}--// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-sign-WebIDL::ExceptionOr<void> KMAC::validate_sign_parameters(AlgorithmParams const& params) const-{- // NB: Step 2 fails for the output lengths and customizations that our KMAC does not support.- auto const& normalized_algorithm = static_cast<KmacParams const&>(params);- auto result = ::Crypto::Authentication::KMAC::validate_parameters(normalized_algorithm.output_length,- normalized_algorithm.customization.map([](auto const& value) { return value.span(); }));- if (result.is_error())- return WebIDL::OperationError::create("KMAC operation failed"_utf16);-- return {};-}--// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-sign-WebIDL::ExceptionOr<ByteBuffer> KMAC::sign(JS::Realm& realm, AlgorithmParams const& params, GC::Ref<CryptoKey> key, ByteBuffer const& message)-{- auto const& normalized_algorithm = static_cast<KmacParams const&>(params);-- // 1. Let customization be the customization member of normalizedAlgorithm if present or the empty octet string otherwise.- auto const& customization = normalized_algorithm.customization;-- auto const& key_data = key->handle().get<ByteBuffer>();- auto const output_length = normalized_algorithm.output_length;-- // 2. If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":- // Let mac be the result of performing the KMAC128 function defined in Section 4 of [NIST-SP800-185]- // using the key represented by [[handle]] internal slot of key as the K input parameter,- // message as the X input parameter, the outputLength member of normalizedAlgorithm as the L input parameter,- // and customization as the S input parameter.- // 2. If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":- // Let mac be the result of performing the KMAC256 function defined in Section 4 of [NIST-SP800-185]- // using the key represented by [[handle]] internal slot of key as the K input parameter,- // message as the X input parameter, the outputLength member of normalizedAlgorithm as the L input parameter,- // and customization as the S input parameter.- auto mac = TRY(kmac_calculate_mac(- realm,- params.name,- key_data.bytes(),- message.bytes(),- output_length,- customization.map([](auto const& v) { return v.span(); })));-- // 3. Return a byte sequence containing mac.- return mac;-}--// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-verify-WebIDL::ExceptionOr<void> KMAC::validate_verify_parameters(AlgorithmParams const& params) const-{- // NB: Step 2 fails for the output lengths and customizations that our KMAC does not support.- auto const& normalized_algorithm = static_cast<KmacParams const&>(params);- auto result = ::Crypto::Authentication::KMAC::validate_parameters(normalized_algorithm.output_length,- normalized_algorithm.customization.map([](auto const& value) { return value.span(); }));- if (result.is_error())- return WebIDL::OperationError::create("KMAC operation failed"_utf16);-- return {};+extern "C" {+u32 web_crypto_kmac_default_key_length(::Crypto::Authentication::KMACKind);+bool web_crypto_kmac_validate_parameters(u32, OptionalBytes);+bool web_crypto_kmac_sign(::Crypto::Authentication::KMACKind, ReadonlyBytes, ReadonlyBytes, u32, OptionalBytes, void*, ReceiveEncodedBytes);}-// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-verify-WebIDL::ExceptionOr<bool> KMAC::verify(JS::Realm& realm, AlgorithmParams const& params, GC::Ref<CryptoKey> key, ByteBuffer const& signature, ByteBuffer const& message)-{- auto const& normalized_algorithm = static_cast<KmacParams const&>(params);-- // 1. Let customization be the customization member of normalizedAlgorithm if present or the empty octet string otherwise.- auto const& customization = normalized_algorithm.customization;-- auto const& key_data = key->handle().get<ByteBuffer>();- auto const output_length = normalized_algorithm.output_length;-- // 2. If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":- // Let mac be the result of performing the KMAC128 function defined in Section 4 of [NIST-SP800-185]- // using the key represented by [[handle]] internal slot of key as the K input parameter, message as the X input parameter,- // the outputLength member of normalizedAlgorithm as the L input parameter, and customization as the S input parameter.- // 2. If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":- // Let mac be the result of performing the KMAC256 function defined in Section 4 of [NIST-SP800-185]- // using the key represented by [[handle]] internal slot of key as the K input parameter, message as the X input parameter,- // the outputLength member of normalizedAlgorithm as the L input parameter, and customization as the S input parameter.- auto mac = TRY(kmac_calculate_mac(- realm,- params.name,- key_data.bytes(),- message.bytes(),- output_length,- customization.map([](auto const& v) { return v.span(); })));+static_assert(to_underlying(::Crypto::Authentication::KMACKind::KMAC128) == 0);+static_assert(to_underlying(::Crypto::Authentication::KMACKind::KMAC256) == 1);- // 3. Let computedMac be a byte sequence containing mac.- // 4. Return true if computedMac is equal to signature and false otherwise. This comparison must be performed in- // constant-time.- return mac.size() == signature.size() && timing_safe_compare(mac.data(), signature.data(), mac.size());-}--// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-generate-key-WebIDL::ExceptionOr<void> KMAC::validate_generate_key_parameters(AlgorithmParams const& params) const+u32 web_crypto_kmac_default_key_length(::Crypto::Authentication::KMACKind kind){- // NB: Generating a key of a length that our KMAC does not support fails.- auto const& normalized_algorithm = static_cast<KmacKeyGenParams const&>(params);- if (normalized_algorithm.length.has_value())- TRY(validate_kmac_key_length(normalized_algorithm.length.value()));-- return {};+ return ::Crypto::Authentication::KMAC::default_key_length(kind);}-// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-generate-key-WebIDL::ExceptionOr<Variant<GC::Ref<CryptoKey>, CryptoKeyPair>> KMAC::generate_key(JS::Realm& realm, AlgorithmParams const& params, bool extractable, Vector<KeyUsage> const& usages)+bool web_crypto_kmac_validate_parameters(u32 output_length, OptionalBytes customization){- // 1. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.- for (auto const& usage : usages) {- if (usage != KeyUsage::Sign && usage != KeyUsage::Verify)- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));- }-- auto const& normalized_algorithm = static_cast<KmacKeyGenParams const&>(params);-- WebIDL::UnsignedLong length;- // 2. If the length member of normalizedAlgorithm is present:- // Let length be equal to the length member of normalizedAlgorithm.- // 2. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":- // Let length be 128.- // 2. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":- // Let length be 256.- if (!normalized_algorithm.length.has_value()) {- auto kind = kmac_kind_from_algorithm_name(params.name);- if (!kind.has_value())- return WebIDL::OperationError::create("Unsupported KMAC algorithm"_utf16);- length = ::Crypto::Authentication::KMAC::default_key_length(*kind);- } else {- length = normalized_algorithm.length.value();- }-- TRY(validate_kmac_key_length(length));-- // 3. Generate a key of length bits.- // 4. If key generation fails, throw an OperationError.- auto key_data_or_error = generate_random_key(realm.vm(), length);- if (key_data_or_error.is_error())- return WebIDL::OperationError::create("Failed to generate key"_utf16);- auto key_data = key_data_or_error.release_value();-- // 5. Let key be a new CryptoKey object representing the generated key.- auto key = CryptoKey::create(move(key_data));-- // 6. Set the [[type]] internal slot of key to "secret".- key->set_type(KeyType::Secret);-- // 7. Let algorithm be a new KmacKeyAlgorithm.- // 8. Set the name attribute of algorithm to the name member of normalizedAlgorithm.- // 9. Set the length attribute of algorithm to length.- // 10. Set the [[algorithm]] internal slot of key to algorithm.- key->set_algorithm(CryptoKey::KmacKeyAlgorithmData { params.name, length });-- // 11. Set the [[extractable]] internal slot of key to extractable.- key->set_extractable(extractable);-- // 12. Set the [[usages]] internal slot of key to be the normalized value of usages.- key->set_usages(normalized_key_usages(usages));-- // 13. Return key.- return Variant<GC::Ref<CryptoKey>, CryptoKeyPair> { key };+ return !::Crypto::Authentication::KMAC::validate_parameters(output_length, customization.to_optional()).is_error();}-// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-import-key-WebIDL::ExceptionOr<void> KMAC::validate_import_key_parameters(AlgorithmParams const& params) const+bool web_crypto_kmac_sign(::Crypto::Authentication::KMACKind kind, ReadonlyBytes key, ReadonlyBytes message, u32 output_length, OptionalBytes customization, void* state, ReceiveEncodedBytes receive){- // NB: Importing a key of a length that our KMAC does not support fails.- auto const& normalized_algorithm = static_cast<KmacImportParams const&>(params);- if (normalized_algorithm.length.has_value())- TRY(validate_kmac_key_length(normalized_algorithm.length.value()));-- return {};-}--// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-import-key-WebIDL::ExceptionOr<GC::Ref<CryptoKey>> KMAC::import_key(JS::Realm& realm, AlgorithmParams const& params, KeyFormat format, CryptoKey::ImportKeyData key_data, bool extractable, Vector<KeyUsage> const& usages)-{- auto const& normalized_algorithm = static_cast<KmacImportParams const&>(params);-- // 1. Let keyData be the key data to be imported.-- // 2. If usages contains an entry which is not "sign" or "verify", then throw a SyntaxError.- for (auto const& usage : usages) {- if (usage != KeyUsage::Sign && usage != KeyUsage::Verify)- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));- }-- ByteBuffer data;-- // 3. If format is "raw-secret":- if (format == KeyFormat::RawSecret) {- // 1. Let data be keyData.- data = move(key_data.get<ByteBuffer>());- }- // 3. If format is "jwk":- else if (format == KeyFormat::Jwk) {- // 1. If keyData is a JsonWebKey dictionary:- // Let jwk equal keyData.- // Otherwise:- // Throw a DataError.- if (!key_data.has<JsonWebKey>())- return WebIDL::DataError::create("Data is not a JsonWebKey dictionary"_utf16);-- auto const& jwk = key_data.get<JsonWebKey>();-- // 2. If the kty field of jwk is not "oct", then throw a DataError.- if (jwk.kty != "oct"sv)- return WebIDL::DataError::create("Invalid key type"_utf16);-- // 3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA], then throw a DataError.- // NOTE: parse_jwk_symmetric_key() performs the validation required for symmetric JWKs.-- // 4. Let data be the byte sequence obtained by decoding the k field of jwk.- data = TRY(parse_jwk_symmetric_key(realm, jwk));-- // 5. -> If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":- // If the alg field of jwk is present and is not "K128", then throw a DataError.- // -> If the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":- // If the alg field of jwk is present and is not "K256", then throw a DataError.- auto const& algorithm_name = normalized_algorithm.name;- if (algorithm_name == "KMAC128"sv) {- if (jwk.alg.has_value() && *jwk.alg != "K128"sv)- return WebIDL::DataError::create("Invalid alg field for KMAC128"_utf16);- } else if (algorithm_name == "KMAC256"sv) {- if (jwk.alg.has_value() && *jwk.alg != "K256"sv)- return WebIDL::DataError::create("Invalid alg field for KMAC256"_utf16);- }-- // 6. If usages is non-empty and the use field of jwk is present and is not "sig", then throw a DataError.- if (!usages.is_empty() && jwk.use.has_value() && *jwk.use != "sig"sv)- return WebIDL::DataError::create("Invalid use in JsonWebKey"_utf16);-- // 7. If the key_ops field of jwk is present, and is invalid according to the requirements of JSON Web Key [JWK]- // or does not contain all of the specified usages values, then throw a DataError.- TRY(validate_jwk_key_ops(realm, jwk, usages));-- // 8. If the ext field of jwk is present and has the value false and extractable is true, then throw a DataError.- if (jwk.ext.has_value() && !*jwk.ext && extractable)- return WebIDL::DataError::create("Invalid ext field"_utf16);- }- // 3. Otherwise:- else {- // 1. Throw a NotSupportedError.- return WebIDL::NotSupportedError::create("Only raw-secret and jwk formats are supported"_utf16);- }-- // 4. Let length be the length in bits of data.- auto length = static_cast<WebIDL::UnsignedLong>(data.size() * 8);-- // 5. If the length member of normalizedAlgorithm is present:- if (normalized_algorithm.length.has_value()) {- auto requested_length = normalized_algorithm.length.value();-- // 1. If the length member of normalizedAlgorithm is greater than length, then throw a DataError.- if (requested_length > length)- return WebIDL::DataError::create("Invalid data size"_utf16);-- // 2. If the length member of normalizedAlgorithm is less than or equal to length minus eight, then throw a DataError.- if (requested_length + 8 <= length)- return WebIDL::DataError::create("Invalid data size"_utf16);-- // 3. Otherwise:- // Set length equal to the length member of normalizedAlgorithm.- length = requested_length;- }-- TRY(validate_kmac_key_length(length));-- // 6. Let key be a new CryptoKey object representing a KMAC key with the first length bits of the Keccak decoding- // of data.- // NB: The length is a multiple of 8 and less than 8 bits shorter than data, so the key is all of data.- auto key = CryptoKey::create(move(data));-- // 7. Set the [[type]] internal slot of key to "secret".- key->set_type(KeyType::Secret);-- // 8. Let algorithm be a new KmacKeyAlgorithm.- // 9. Set the name attribute of algorithm to the name member of normalizedAlgorithm.- // 10. Set the length attribute of algorithm to length.- // 11. Set the [[algorithm]] internal slot of key to algorithm.- key->set_algorithm(CryptoKey::KmacKeyAlgorithmData { normalized_algorithm.name, length });-- // 12. Return key.- return key;-}--// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-export-key-WebIDL::ExceptionOr<ExportKeyResult> KMAC::export_key(JS::Realm& realm, KeyFormat format, GC::Ref<CryptoKey> key)-{- // 1. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be accessed, then throw an OperationError.- // Note: In our impl this is always accessible-- Optional<ExportKeyResult> result;-- // 2. If format is "raw-secret":- if (format == KeyFormat::RawSecret) {- // 1. Let result be the raw bits of the key represented by [[handle]] internal slot of key.- auto data = key->handle().get<ByteBuffer>();- result = ExportKeyResult { data };- }- // 2. If format is "jwk":- else if (format == KeyFormat::Jwk) {- // 1. Let jwk be a new JsonWebKey dictionary.- JsonWebKey jwk = {};-- // 2. Set the kty attribute of jwk to the string "oct".- jwk.kty = "oct"_utf16;-- // 3. Set the k attribute of jwk to be a string containing the raw bits of the key represented by [[handle]] internal slot of key,- // encoded according to JSON Web Algorithms [JWA].- auto const& key_bytes = key->handle().get<ByteBuffer>();- jwk.k = Utf16String::from_utf8(TRY_OR_THROW_OOM(realm.vm(), encode_base64url(key_bytes, AK::OmitPadding::Yes)));-- // 4. Let keyAlgorithm be the [[algorithm]] internal slot of key.- // 5. -> If the name member of keyAlgorithm is "KMAC128":- // Set the alg attribute of jwk to the string "K128".- // -> If the name member of keyAlgorithm is "KMAC256":- // Set the alg attribute of jwk to the string "K256".- auto const& algorithm_name = key->algorithm_name();- if (algorithm_name == "KMAC128"sv) {- jwk.alg = "K128"_utf16;- } else if (algorithm_name == "KMAC256"sv) {- jwk.alg = "K256"_utf16;- }-- // 6. Set the key_ops attribute of jwk to equal the usages attribute of key.- jwk.key_ops = Vector<Utf16String> {};- jwk.key_ops->ensure_capacity(key->internal_usages().size());- for (auto const& usage : key->internal_usages()) {- jwk.key_ops->unchecked_append(Utf16String::from_utf8(key_usage_to_string(usage)));- }-- // 7. Set the ext attribute of jwk to equal the [[extractable]] internal slot of key.- jwk.ext = key->extractable();-- // 8. Let result be jwk.- return ExportKeyResult { move(jwk) };- }- // 2. Otherwise:- else {- // 1. throw a NotSupportedError.- return WebIDL::NotSupportedError::create("Cannot export to unsupported format"_utf16);- }-- // 3. Return result.- return result.release_value();-}--// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-get-key-length-WebIDL::ExceptionOr<Optional<u32>> KMAC::get_key_length(JS::Realm&, AlgorithmParams const& params)-{- auto const& normalized_algorithm = static_cast<KmacImportParams const&>(params);-- WebIDL::UnsignedLong length;-- // 1. If the length member of normalizedAlgorithm is present:- // Let length be equal to the length member of normalizedAlgorithm.- if (normalized_algorithm.length.has_value()) {- length = normalized_algorithm.length.value();- }- // 1. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC128":- // Let length be 128.- // 1. Otherwise, if the name member of normalizedAlgorithm is a case-sensitive string match for "KMAC256":- // Let length be 256.- else {- auto kind = kmac_kind_from_algorithm_name(params.name);- if (!kind.has_value())- return WebIDL::OperationError::create("Unsupported KMAC algorithm"_utf16);-- length = ::Crypto::Authentication::KMAC::default_key_length(*kind);- }-- // 2. Return length.- return length;+ ::Crypto::Authentication::KMAC kmac(kind);+ auto result = kmac.sign(key, message, output_length, customization.to_optional());+ if (result.is_error())+ return false;+ receive(state, result.value());+ return true;}}diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.hindex fce75b8a1c5..97f3119debd 100644--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h@@ -259,38 +259,6 @@ struct AesDerivedKeyParams : public AlgorithmParams {static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);};-// https://w3c.github.io/webcrypto/#hmac-importparams-struct HmacImportParams : public AlgorithmParams {- virtual ~HmacImportParams() override;-- HmacImportParams(HashAlgorithmIdentifier hash, Optional<WebIDL::UnsignedLong> length)- : hash(move(hash))- , length(length)- {- }-- HashAlgorithmIdentifier hash;- Optional<WebIDL::UnsignedLong> length;-- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);-};--// https://w3c.github.io/webcrypto/#hmac-keygen-params-struct HmacKeyGenParams : public AlgorithmParams {- virtual ~HmacKeyGenParams() override;-- HmacKeyGenParams(HashAlgorithmIdentifier hash, Optional<WebIDL::UnsignedLong> length)- : hash(move(hash))- , length(length)- {- }-- HashAlgorithmIdentifier hash;- Optional<WebIDL::UnsignedLong> length;-- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);-};-class AlgorithmMethods {public:AK_ALLOC_WITH_KMALLOC;@@ -646,24 +614,6 @@ private:X448() = default;};-class HMAC : public AlgorithmMethods {-public:- virtual WebIDL::ExceptionOr<ByteBuffer> sign(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&) override;- virtual WebIDL::ExceptionOr<bool> verify(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&, ByteBuffer const&) override;- virtual WebIDL::ExceptionOr<Variant<GC::Ref<CryptoKey>, CryptoKeyPair>> generate_key(JS::Realm& realm, AlgorithmParams const&, bool, Vector<KeyUsage> const&) override;- virtual WebIDL::ExceptionOr<GC::Ref<CryptoKey>> import_key(JS::Realm& realm, AlgorithmParams const&, KeyFormat, CryptoKey::ImportKeyData, bool, Vector<KeyUsage> const&) override;- virtual WebIDL::ExceptionOr<ExportKeyResult> export_key(JS::Realm& realm, KeyFormat, GC::Ref<CryptoKey>) override;- virtual WebIDL::ExceptionOr<Optional<u32>> get_key_length(JS::Realm& realm, AlgorithmParams const&) override;-- virtual WebIDL::ExceptionOr<void> validate_generate_key_parameters(AlgorithmParams const&) const override;- virtual WebIDL::ExceptionOr<void> validate_import_key_parameters(AlgorithmParams const&) const override;-- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new HMAC); }--private:- HMAC() = default;-};-class MLDSA : public AlgorithmMethods {public:virtual WebIDL::ExceptionOr<ByteBuffer> sign(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&) override;@@ -783,70 +733,6 @@ struct Argon2Params : public AlgorithmParams {};// https://wicg.github.io/webcrypto-modern-algos/#cshake-params-// https://wicg.github.io/webcrypto-modern-algos/#kmac-params-struct KmacParams : public AlgorithmParams {- virtual ~KmacParams() override;-- KmacParams(u32 output_length, Optional<ByteBuffer> customization)- : output_length(output_length)- , customization(move(customization))- {- }-- u32 output_length;- Optional<ByteBuffer> customization;-- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);-};--// https://wicg.github.io/webcrypto-modern-algos/#kmac-keygen-params-struct KmacKeyGenParams : public AlgorithmParams {- virtual ~KmacKeyGenParams() override;-- KmacKeyGenParams(Optional<WebIDL::UnsignedLong> length)- : length(length)- {- }-- Optional<WebIDL::UnsignedLong> length;-- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);-};--// https://wicg.github.io/webcrypto-modern-algos/#kmac-import-params-struct KmacImportParams : public AlgorithmParams {- virtual ~KmacImportParams() override;-- KmacImportParams(Optional<WebIDL::UnsignedLong> length)- : length(length)- {- }-- Optional<WebIDL::UnsignedLong> length;-- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);-};--class KMAC : public AlgorithmMethods {-public:- virtual WebIDL::ExceptionOr<ByteBuffer> sign(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&) override;- virtual WebIDL::ExceptionOr<bool> verify(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&, ByteBuffer const&) override;- virtual WebIDL::ExceptionOr<Variant<GC::Ref<CryptoKey>, CryptoKeyPair>> generate_key(JS::Realm& realm, AlgorithmParams const&, bool, Vector<KeyUsage> const&) override;- virtual WebIDL::ExceptionOr<GC::Ref<CryptoKey>> import_key(JS::Realm& realm, AlgorithmParams const&, KeyFormat, CryptoKey::ImportKeyData, bool, Vector<KeyUsage> const&) override;- virtual WebIDL::ExceptionOr<ExportKeyResult> export_key(JS::Realm& realm, KeyFormat, GC::Ref<CryptoKey>) override;- virtual WebIDL::ExceptionOr<Optional<u32>> get_key_length(JS::Realm& realm, AlgorithmParams const&) override;-- virtual WebIDL::ExceptionOr<void> validate_generate_key_parameters(AlgorithmParams const&) const override;- virtual WebIDL::ExceptionOr<void> validate_import_key_parameters(AlgorithmParams const&) const override;- virtual WebIDL::ExceptionOr<void> validate_sign_parameters(AlgorithmParams const&) const override;- virtual WebIDL::ExceptionOr<void> validate_verify_parameters(AlgorithmParams const&) const override;-- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new KMAC); }--private:- KMAC() = default;-};-// https://wicg.github.io/webcrypto-modern-algos/#dfn-AeadParams// NOTE: The AeadParams dictionary is identical to the AesGcmParamsstruct AeadParams : public AlgorithmParams {diff --git a/Libraries/LibWeb/Crypto/CryptoKey.cpp b/Libraries/LibWeb/Crypto/CryptoKey.cppindex 7ac85cfca97..3e14629c47d 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.cpp+++ b/Libraries/LibWeb/Crypto/CryptoKey.cpp@@ -62,6 +62,8 @@ void web_rust_crypto_key_with_usages(CryptoKey const*, void*, void (*)(void*, Revoid web_rust_crypto_key_set_usages(CryptoKey*, ReadonlySpan<KeyUsage>);void web_crypto_key_destroy_handle(CryptoKey::InternalKeyData*);+CryptoKey::InternalKeyData* web_crypto_key_create_byte_handle(ReadonlyBytes);+void web_crypto_key_byte_handle_bytes(CryptoKey::InternalKeyData const*, ReadonlyBytes*);void web_crypto_key_encode_handle(CryptoKey::InternalKeyData const*, void*, void (*)(void*, CryptoKeyHandleFields const*));JSCompletion web_crypto_key_decode_handle(void* realm, CryptoKeyHandleFields const*, CryptoKey::InternalKeyData** out_handle);}@@ -81,6 +83,16 @@ void web_crypto_key_destroy_handle(CryptoKey::InternalKeyData* handle)delete handle;}+CryptoKey::InternalKeyData* web_crypto_key_create_byte_handle(ReadonlyBytes bytes)+{+ return new CryptoKey::InternalKeyData(MUST(ByteBuffer::copy(bytes)));+}++void web_crypto_key_byte_handle_bytes(CryptoKey::InternalKeyData const* handle, ReadonlyBytes* bytes)+{+ *bytes = handle->get<ByteBuffer>().bytes();+}+CryptoKey::InternalKeyData const& CryptoKey::handle() const{return *web_rust_crypto_key_handle(this);diff --git a/Libraries/LibWeb/Crypto/CryptoKey.h b/Libraries/LibWeb/Crypto/CryptoKey.hindex 246bee6def3..0ef204dbbf3 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.h+++ b/Libraries/LibWeb/Crypto/CryptoKey.h@@ -122,7 +122,6 @@ public:Vector<KeyUsage> internal_usages() const;RsaHashedKeyAlgorithmData rsa_hashed_algorithm() const { return internal_algorithm().get<RsaHashedKeyAlgorithmData>(); }EcKeyAlgorithmData ec_algorithm() const { return internal_algorithm().get<EcKeyAlgorithmData>(); }- HmacKeyAlgorithmData hmac_algorithm() const { return internal_algorithm().get<HmacKeyAlgorithmData>(); }void set_extractable(bool);void set_type(KeyType);diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cppindex ca01f978c45..512c143d2f6 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp@@ -25,7 +25,6 @@ enum class AlgorithmId : u8 {AesCbc,AesGcm,AesKw,- HMAC,HKDF,PBKDF2,X25519,@@ -37,7 +36,6 @@ enum class AlgorithmId : u8 {Argon2,ChaCha20Poly1305,AesOcb,- KMAC,};enum class ParameterId : u8 {@@ -55,17 +53,12 @@ enum class ParameterId : u8 {AesDerivedKeyParams,AesCbcParams,AesGcmParams,- HmacKeyGenParams,- HmacImportParams,HKDFParams,PBKDF2Params,Ed448Params,ContextParams,Argon2Params,AeadParams,- KmacParams,- KmacKeyGenParams,- KmacImportParams,};struct RawRsaOtherPrimesInfo {@@ -252,8 +245,6 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithmreturn AesGcm::create();case AlgorithmId::AesKw:return AesKw::create();- case AlgorithmId::HMAC:- return HMAC::create();case AlgorithmId::HKDF:return HKDF::create();case AlgorithmId::PBKDF2:@@ -276,8 +267,6 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithmreturn ChaCha20Poly1305::create();case AlgorithmId::AesOcb:return AesOcb::create();- case AlgorithmId::KMAC:- return KMAC::create();}VERIFY_NOT_REACHED();}();@@ -312,10 +301,6 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithmreturn AesCbcParams::from_value(realm, object);case ParameterId::AesGcmParams:return AesGcmParams::from_value(realm, object);- case ParameterId::HmacKeyGenParams:- return HmacKeyGenParams::from_value(realm, object);- case ParameterId::HmacImportParams:- return HmacImportParams::from_value(realm, object);case ParameterId::HKDFParams:return HKDFParams::from_value(realm, object);case ParameterId::PBKDF2Params:@@ -328,12 +313,6 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithmreturn Argon2Params::from_value(realm, object);case ParameterId::AeadParams:return AeadParams::from_value(realm, object);- case ParameterId::KmacParams:- return KmacParams::from_value(realm, object);- case ParameterId::KmacKeyGenParams:- return KmacKeyGenParams::from_value(realm, object);- case ParameterId::KmacImportParams:- return KmacImportParams::from_value(realm, object);}VERIFY_NOT_REACHED();}();diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 900e727d7a1..a896b3d91eb 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -46,7 +46,7 @@ ALLOWED_REALM_MENTIONS = {"CookieStore": (2, 19, "cookie-store async callbacks and promise/value materialization still thread realms"),"Crypto": (5,- 343,+ 307,"WebCrypto algorithms still use realms for buffer/key/promise materialization and for normalizing algorithm ""dictionaries. The native CryptoKey wrapper ""uses the caller's realm and wrapper world",