Skip to content

Truly independent web browser

LibWeb: Port WebCrypto HKDF, PBKDF2 and Argon2 to Rust

Shannon Booth28fa0b162505
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index e8e0a599a1a..38cdaec1df9 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -278,6 +278,16 @@ fn to_integer_enforcing_range(vm: &Vm, value: Value, lower_bound: f64, upper_bou
/// [EnforceRange] or [Clamp].
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
+/// A JS value converted to an octet with [EnforceRange], https://webidl.spec.whatwg.org/#js-octet
+#[allow(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ reason = "the value is an integer within the bounds of the type"
+)]
+pub(crate) fn to_octet_enforcing_range(vm: &Vm, value: Value) -> ThrowCompletionOr<u8> {
+ Ok(to_integer_enforcing_range(vm, value, 0.0, f64::from(u8::MAX))? as u8)
+}
+
/// A JS value converted to a long with [EnforceRange], https://webidl.spec.whatwg.org/#js-long
#[allow(
clippy::cast_possible_truncation,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index 72b91edd391..e6165719f84 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -19,7 +19,7 @@ use libjs_rust::api::{
ErrorKind, ErrorType, Gc, Object, PropertyKey, RawNativeFunctionResult, Realm, Trace, Value, Vm,
};
-use crate::bindings::conversions::{buffer_source_type_of, to_unsigned_long_enforcing_range};
+use crate::bindings::conversions::{buffer_source_type_of, to_octet_enforcing_range, 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;
@@ -361,15 +361,12 @@ pub(crate) enum AlgorithmId {
AesCbc,
AesGcm,
AesKw,
- Hkdf,
- Pbkdf2,
X25519,
X448,
ED25519,
ED448,
MlDsa,
MlKem,
- Argon2,
ChaCha20Poly1305,
AesOcb,
}
@@ -395,11 +392,8 @@ pub(crate) enum ParameterId {
AesDerivedKeyParams,
AesCbcParams,
AesGcmParams,
- HkdfParams,
- Pbkdf2Params,
Ed448Params,
ContextParams,
- Argon2Params,
AeadParams,
}
@@ -705,7 +699,13 @@ pub(crate) trait AlgorithmMethods: Trace {
))
}
- fn derive_bits(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _length: Option<u32>) -> WebIdlResult<Bytes> {
+ fn derive_bits(
+ &self,
+ _realm: Gc<Realm>,
+ _algorithm: &AlgorithmParams,
+ _key: Ref<CryptoKey>,
+ _length: Option<u32>,
+ ) -> WebIdlResult<Bytes> {
Err(Exception::Dom(
"NotSupportedError",
Utf16String::from_utf8("deriveBits is not supported"),
@@ -917,7 +917,13 @@ impl AlgorithmMethods for CppAlgorithm {
Ok(out)
}
- fn derive_bits(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, length: Option<u32>) -> WebIdlResult<Bytes> {
+ fn derive_bits(
+ &self,
+ realm: Gc<Realm>,
+ _algorithm: &AlgorithmParams,
+ key: Ref<CryptoKey>,
+ length: Option<u32>,
+ ) -> 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 {
@@ -2742,6 +2748,705 @@ impl AlgorithmMethods for Kmac {
}
}
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct HkdfParams {
+ #[gc(untraced)]
+ hash: HashAlgorithmIdentifier,
+ salt: Bytes,
+ info: Bytes,
+}
+
+impl HkdfParams {
+ 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 salt_value = object.get(vm, &PropertyKey::from_utf8("salt"))?;
+ let Some(salt_source) = buffer_source_type_of(salt_value) else {
+ return vm
+ .throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"BufferSource"])
+ .map_err(Into::into);
+ };
+ let salt = get_a_copy_of_the_bytes(vm, salt_source)?;
+
+ let info_value = object.get(vm, &PropertyKey::from_utf8("info"))?;
+ let Some(info_source) = buffer_source_type_of(info_value) else {
+ return vm
+ .throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"BufferSource"])
+ .map_err(Into::into);
+ };
+ let info = get_a_copy_of_the_bytes(vm, info_source)?;
+
+ Ok(Self { hash, salt, info })
+ }
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Pbkdf2Params {
+ salt: Bytes,
+ iterations: u32,
+ #[gc(untraced)]
+ hash: HashAlgorithmIdentifier,
+}
+
+impl Pbkdf2Params {
+ pub(crate) fn from_value(vm: &Vm, realm: Gc<Realm>, object: Gc<Object>) -> WebIdlResult<Self> {
+ let salt_value = object.get(vm, &PropertyKey::from_utf8("salt"))?;
+
+ let Some(salt_source) = buffer_source_type_of(salt_value) else {
+ return vm
+ .throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"BufferSource"])
+ .map_err(Into::into);
+ };
+
+ let salt = get_a_copy_of_the_bytes(vm, salt_source)?;
+
+ let iterations_value = object.get(vm, &PropertyKey::from_utf8("iterations"))?;
+ let iterations = to_unsigned_long_enforcing_range(vm, iterations_value)?;
+
+ let hash_value = object.get(vm, &PropertyKey::from_utf8("hash"))?;
+ let hash = hash_algorithm_identifier_from_value(vm, realm, hash_value, None)?;
+
+ Ok(Self { salt, iterations, hash })
+ }
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Argon2Params {
+ nonce: Bytes,
+ parallelism: u32,
+ memory: u32,
+ passes: u32,
+ version: Option<u8>,
+ secret_value: Option<Bytes>,
+ associated_data: Option<Bytes>,
+}
+
+impl Argon2Params {
+ pub(crate) fn from_value(vm: &Vm, object: Gc<Object>) -> WebIdlResult<Self> {
+ let nonce_property = PropertyKey::from_utf8("nonce");
+ if !object.has_property(vm, &nonce_property)? {
+ return vm
+ .throw_completion(ErrorKind::TypeError, ErrorType::MissingRequiredProperty, &[&"nonce"])
+ .map_err(Into::into);
+ }
+ let nonce_value = object.get(vm, &nonce_property)?;
+ let Some(nonce_source) = buffer_source_type_of(nonce_value) else {
+ return vm
+ .throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"BufferSource"])
+ .map_err(Into::into);
+ };
+ let nonce = get_a_copy_of_the_bytes(vm, nonce_source)?;
+
+ let extract_u32_value = |name: &str| -> WebIdlResult<u32> {
+ let property = PropertyKey::from_utf8(name);
+ if !object.has_property(vm, &property)? {
+ return vm
+ .throw_completion(ErrorKind::TypeError, ErrorType::MissingRequiredProperty, &[&name])
+ .map_err(Into::into);
+ }
+ let key_value = object.get(vm, &property)?;
+ Ok(to_unsigned_long_enforcing_range(vm, key_value)?)
+ };
+
+ let parallelism = extract_u32_value("parallelism")?;
+ let memory = extract_u32_value("memory")?;
+ let passes = extract_u32_value("passes")?;
+
+ let mut version = None;
+ let version_property = PropertyKey::from_utf8("version");
+ if object.has_property(vm, &version_property)? {
+ let version_value = object.get(vm, &version_property)?;
+ version = Some(to_octet_enforcing_range(vm, version_value)?);
+ }
+
+ let secret_value = get_optional_buffer_source(vm, object, &PropertyKey::from_utf8("secretValue"))?;
+ let associated_data = get_optional_buffer_source(vm, object, &PropertyKey::from_utf8("associatedData"))?;
+
+ Ok(Self {
+ nonce,
+ parallelism,
+ memory,
+ passes,
+ version,
+ secret_value,
+ associated_data,
+ })
+ }
+}
+
+#[repr(i32)]
+enum Argon2Type {
+ Argon2d,
+ Argon2i,
+ Argon2id,
+}
+
+#[repr(C)]
+struct Argon2Inputs<'a> {
+ message: Span<'a, u8>,
+ nonce: Span<'a, u8>,
+ parallelism: u32,
+ memory: u32,
+ passes: u32,
+ version: u32,
+ secret_value: OptionalBytes<'a>,
+ associated_data: OptionalBytes<'a>,
+ tag_length: u32,
+}
+
+unsafe extern "C" {
+ fn web_crypto_hash_digest_size(kind: ShaHashKind) -> usize;
+ fn web_crypto_hkdf_derive_key(
+ kind: ShaHashKind,
+ salt: Span<'_, u8>,
+ key: Span<'_, u8>,
+ info: Span<'_, u8>,
+ length: u32,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ fn web_crypto_pbkdf2_derive_key(
+ kind: ShaHashKind,
+ password: Span<'_, u8>,
+ salt: Span<'_, u8>,
+ iterations: u32,
+ length: u32,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ fn web_crypto_argon2_validate_parameters(nonce: Span<'_, u8>) -> usize;
+ fn web_crypto_argon2_derive_key(
+ kind: Argon2Type,
+ inputs: &Argon2Inputs<'_>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+}
+
+fn sha_hash_kind(hash_algorithm: &Utf16String) -> Result<ShaHashKind, Utf16String> {
+ if matches!(hash_algorithm.as_units(), Utf16StringUnits::Ascii(b"SHA-1")) {
+ return Ok(ShaHashKind::Sha1);
+ }
+ if matches!(hash_algorithm.as_units(), Utf16StringUnits::Ascii(b"SHA-256")) {
+ return Ok(ShaHashKind::Sha256);
+ }
+ if matches!(hash_algorithm.as_units(), Utf16StringUnits::Ascii(b"SHA-384")) {
+ return Ok(ShaHashKind::Sha384);
+ }
+ if matches!(hash_algorithm.as_units(), Utf16StringUnits::Ascii(b"SHA-512")) {
+ return Ok(ShaHashKind::Sha512);
+ }
+ Err(libjs_rust::api::utf16_formatted(
+ "Invalid hash function '{}'",
+ &[hash_algorithm],
+ ))
+}
+
+/// # Safety
+///
+/// The string is live and the output is writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_crypto_sha_hash_kind(raw: usize, out: &mut i32) -> usize {
+ // SAFETY: The caller lends a live string and we take our own reference.
+ let hash_algorithm = unsafe {
+ ak::reference_utf16_string(raw);
+ Utf16String::from_raw_owned(raw)
+ };
+ match sha_hash_kind(&hash_algorithm) {
+ Ok(kind) => {
+ *out = kind as i32;
+ 0
+ }
+ Err(message) => message.into_raw(),
+ }
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Hkdf;
+
+impl AlgorithmMethods for Hkdf {
+ // https://w3c.github.io/webcrypto/#hkdf-operations-import-key
+ fn import_key(
+ &self,
+ cx: &CallContext,
+ _: &AlgorithmParams,
+ format: KeyFormat,
+ key_data: ImportKeyData,
+ extractable: bool,
+ key_usages: &[KeyUsage],
+ ) -> WebIdlResult<Ref<CryptoKey>> {
+ // 1. Let keyData be the key data to be imported.
+
+ // 2. If format is "raw":
+ // (… see below …)
+ // Otherwise:
+ // throw a NotSupportedError.
+ // 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".
+ if format != KeyFormat::Raw && format != KeyFormat::RawSecret {
+ return Err(dom_error("NotSupportedError", b"Only raw format is supported"));
+ }
+
+ // 1. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
+ for &usage in key_usages {
+ if usage != KeyUsage::DeriveKey && usage != KeyUsage::DeriveBits {
+ return Err(Exception::Dom(
+ "SyntaxError",
+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),
+ ));
+ }
+ }
+
+ // 2. If extractable is not false, then throw a SyntaxError.
+ if extractable {
+ return Err(dom_error("SyntaxError", b"extractable must be false"));
+ }
+
+ // 3. Let key be a new CryptoKey representing the key data provided in keyData.
+ let ImportKeyData::Bytes(data) = key_data else {
+ unreachable!("raw key data contains bytes")
+ };
+ let key = CryptoKey::from_byte_handle(cx.vm(), data.as_slice());
+
+ // 4. Set the [[type]] internal slot of key to "secret".
+ key.set_type(KeyType::Secret);
+
+ // 5. Let algorithm be a new KeyAlgorithm object.
+ // 6. Set the name attribute of algorithm to "HKDF".
+ // 7. Set the [[algorithm]] internal slot of key to algorithm.
+ key.set_algorithm(InternalAlgorithmData::Key {
+ name: Utf16String::from_ascii(b"HKDF"),
+ });
+
+ // 8. Return key.
+ Ok(key)
+ }
+
+ // https://w3c.github.io/webcrypto/#hkdf-operations-get-key-length
+ fn get_key_length(&self, _: Gc<Realm>, _: &AlgorithmParams) -> WebIdlResult<Option<u32>> {
+ // 1. Return null.
+ Ok(None)
+ }
+}
+
+impl AlgorithmMethods for HkdfParams {
+ // https://w3c.github.io/webcrypto/#hkdf-operations-derive-bits
+ fn validate_derive_bits_parameters(&self, _: Gc<Realm>, length_optional: Option<u32>) -> WebIdlResult<()> {
+ let normalized_algorithm = self;
+
+ // 1. If length is null or is not a multiple of 8, then throw an OperationError.
+ let Some(length) = length_optional.filter(|length| length.is_multiple_of(8)) else {
+ return Err(dom_error(
+ "OperationError",
+ b"Length must be specified and divisible by 8",
+ ));
+ };
+
+ // 2. Let hashLength be the length in bits of the output of the hash function identified by the hash member of
+ // normalizedAlgorithm.
+ let hash_kind = sha_hash_kind(&normalized_algorithm.hash.name)
+ .map_err(|message| Exception::Dom("NotSupportedError", message))?;
+ // SAFETY: The hash kind is one of the native SHA algorithms.
+ let hash_length = unsafe { web_crypto_hash_digest_size(hash_kind) } * 8;
+
+ // 3. If length is greater than 255 * hashLength, then throw an OperationError.
+ if length as usize > 255 * hash_length {
+ return Err(dom_error(
+ "OperationError",
+ b"Length is too large for the hash function",
+ ));
+ }
+
+ Ok(())
+ }
+
+ // https://w3c.github.io/webcrypto/#hkdf-operations-derive-bits
+ fn derive_bits(
+ &self,
+ realm: Gc<Realm>,
+ _: &AlgorithmParams,
+ key: Ref<CryptoKey>,
+ length_optional: Option<u32>,
+ ) -> WebIdlResult<Bytes> {
+ let normalized_algorithm = self;
+
+ // NB: Steps 1 to 3 are performed by validate_derive_bits_parameters().
+ self.validate_derive_bits_parameters(realm, length_optional)?;
+ let hash_kind = sha_hash_kind(&normalized_algorithm.hash.name)
+ .map_err(|message| Exception::Dom("NotSupportedError", message))?;
+
+ // 4. Let keyDerivationKey be the secret represented by [[handle]] internal slot of key as the message.
+ let key_derivation_key = key.byte_handle_bytes();
+
+ // 5. Let result be the result of performing the HKDF extract and then the HKDF expand step described in Section 2 of [RFC5869] using:
+ // * the hash member of normalizedAlgorithm as Hash,
+ // * keyDerivationKey as the input keying material, IKM,
+ // * the contents of the salt member of normalizedAlgorithm as salt,
+ // * the contents of the info member of normalizedAlgorithm as info,
+ // * length divided by 8 as the value of L,
+ // Note: Although HKDF technically supports absent salt (treating it as hashLen many NUL bytes),
+ // all major browsers instead raise a TypeError, for example:
+ // "Failed to execute 'deriveBits' on 'SubtleCrypto': HkdfParams: salt: Not a BufferSource"
+ // Because we are forced by neither peer pressure nor the spec, we don't support it either.
+
+ // Note: Check for zero length early because our implementation doesn't support it.
+ let length = length_optional.expect("validation requires a length");
+ if length == 0 {
+ return Ok(Bytes::new(Vec::new()));
+ }
+
+ let mut result: Option<Bytes> = None;
+ // SAFETY: The inputs and output are lent for this call.
+ let success = unsafe {
+ web_crypto_hkdf_derive_key(
+ hash_kind,
+ Span::new(normalized_algorithm.salt.as_slice()),
+ Span::new(key_derivation_key),
+ Span::new(normalized_algorithm.info.as_slice()),
+ length / 8,
+ core::ptr::from_mut(&mut result).cast(),
+ receive_bytes,
+ )
+ };
+
+ // 6. If the key derivation operation fails, then throw an OperationError.
+ if !success {
+ return Err(dom_error("OperationError", b"Failed to derive key"));
+ }
+
+ // 7. Return result
+ Ok(result.expect("LibCrypto returns the derived bytes"))
+ }
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Pbkdf2;
+
+impl AlgorithmMethods for Pbkdf2Params {
+ // https://w3c.github.io/webcrypto/#pbkdf2-operations-derive-bits
+ fn validate_derive_bits_parameters(&self, _: Gc<Realm>, length_optional: Option<u32>) -> WebIdlResult<()> {
+ let normalized_algorithm = self;
+
+ // 1. If length is null or is not a multiple of 8, then throw an OperationError.
+ if length_optional.is_none_or(|length| !length.is_multiple_of(8)) {
+ return Err(dom_error(
+ "OperationError",
+ b"Length must be greater than 0 and divisible by 8",
+ ));
+ }
+
+ // 2. If the iterations member of normalizedAlgorithm is zero, then throw an OperationError.
+ if normalized_algorithm.iterations == 0 {
+ return Err(dom_error("OperationError", b"Iterations must be greater than 0"));
+ }
+
+ // NB: Step 4 fails for the hash functions that our PBKDF2 does not support.
+ sha_hash_kind(&normalized_algorithm.hash.name)
+ .map_err(|message| Exception::Dom("NotSupportedError", message))?;
+
+ Ok(())
+ }
+
+ // https://w3c.github.io/webcrypto/#pbkdf2-operations-derive-bits
+ fn derive_bits(
+ &self,
+ realm: Gc<Realm>,
+ _: &AlgorithmParams,
+ key: Ref<CryptoKey>,
+ length_optional: Option<u32>,
+ ) -> WebIdlResult<Bytes> {
+ let normalized_algorithm = self;
+
+ // NB: Steps 1 and 2 are performed by validate_derive_bits_parameters().
+ self.validate_derive_bits_parameters(realm, length_optional)?;
+
+ // 3. Let prf be the MAC Generation function described in Section 4 of [FIPS-198-1] using the hash function described by the hash member of normalizedAlgorithm.
+ let hash_algorithm = &normalized_algorithm.hash.name;
+
+ // 4. Let result be the result of performing the PBKDF2 operation defined in Section 5.2 of [RFC8018]
+ // using prf as the pseudo-random function, PRF,
+ // the password represented by [[handle]] internal slot of key as the password, P,
+ // the contents of the salt attribute of normalizedAlgorithm as the salt, S,
+ // the value of the iterations attribute of normalizedAlgorithm as the iteration count, c,
+ // and length divided by 8 as the intended key length, dkLen.
+ let password = key.byte_handle_bytes();
+ let salt = &normalized_algorithm.salt;
+ let iterations = normalized_algorithm.iterations;
+ let derived_key_length_bytes = length_optional.expect("validation requires a length") / 8;
+
+ let hash_kind =
+ sha_hash_kind(hash_algorithm).map_err(|message| Exception::Dom("NotSupportedError", message))?;
+
+ let mut result: Option<Bytes> = None;
+ // SAFETY: The inputs and output are lent for this call.
+ let success = unsafe {
+ web_crypto_pbkdf2_derive_key(
+ hash_kind,
+ Span::new(password),
+ Span::new(salt.as_slice()),
+ iterations,
+ derived_key_length_bytes,
+ core::ptr::from_mut(&mut result).cast(),
+ receive_bytes,
+ )
+ };
+
+ // 5. If the key derivation operation fails, then throw an OperationError.
+ if !success {
+ return Err(dom_error("OperationError", b"Failed to derive key"));
+ }
+
+ // 6. Return result
+ Ok(result.expect("LibCrypto returns the derived bytes"))
+ }
+}
+
+impl AlgorithmMethods for Pbkdf2 {
+ // https://w3c.github.io/webcrypto/#pbkdf2-operations-get-key-length
+ fn get_key_length(&self, _: Gc<Realm>, _: &AlgorithmParams) -> WebIdlResult<Option<u32>> {
+ // 1. Return null.
+ Ok(None)
+ }
+
+ // https://w3c.github.io/webcrypto/#pbkdf2-operations-import-key
+ fn import_key(
+ &self,
+ cx: &CallContext,
+ _: &AlgorithmParams,
+ format: KeyFormat,
+ key_data: ImportKeyData,
+ extractable: bool,
+ key_usages: &[KeyUsage],
+ ) -> WebIdlResult<Ref<CryptoKey>> {
+ // 1. If format is not "raw", throw a NotSupportedError
+ // 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".
+ if format != KeyFormat::Raw && format != KeyFormat::RawSecret {
+ return Err(dom_error("NotSupportedError", b"Only raw format is supported"));
+ }
+
+ // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
+ for &usage in key_usages {
+ if usage != KeyUsage::DeriveKey && usage != KeyUsage::DeriveBits {
+ return Err(Exception::Dom(
+ "SyntaxError",
+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),
+ ));
+ }
+ }
+
+ // 3. If extractable is not false, then throw a SyntaxError.
+ if extractable {
+ return Err(dom_error("SyntaxError", b"extractable must be false"));
+ }
+
+ // 4. Let key be a new CryptoKey representing keyData.
+ let ImportKeyData::Bytes(data) = key_data else {
+ unreachable!("raw key data contains bytes")
+ };
+ let key = CryptoKey::from_byte_handle(cx.vm(), data.as_slice());
+
+ // 5. Set the [[type]] internal slot of key to "secret".
+ key.set_type(KeyType::Secret);
+
+ // 6. Let algorithm be a new KeyAlgorithm object.
+ // 7. Set the name attribute of algorithm to "PBKDF2".
+ // 8. Set the [[algorithm]] internal slot of key to algorithm.
+ key.set_algorithm(InternalAlgorithmData::Key {
+ name: Utf16String::from_ascii(b"PBKDF2"),
+ });
+
+ // 9. Return key.
+ Ok(key)
+ }
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Argon2;
+
+impl AlgorithmMethods for Argon2 {
+ // https://wicg.github.io/webcrypto-modern-algos/#argon2-operations-import-key
+ fn import_key(
+ &self,
+ cx: &CallContext,
+ algorithm: &AlgorithmParams,
+ format: KeyFormat,
+ key_data: ImportKeyData,
+ extractable: bool,
+ usages: &[KeyUsage],
+ ) -> WebIdlResult<Ref<CryptoKey>> {
+ // 1. Let keyData be the key data to be imported.
+ // 2. If format is not "raw-secret", throw a NotSupportedError
+ if format != KeyFormat::RawSecret {
+ return Err(dom_error("NotSupportedError", b"Invalid key format"));
+ }
+
+ // 3. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
+ for &usage in usages {
+ if !(usage == KeyUsage::DeriveKey || usage == KeyUsage::DeriveBits) {
+ return Err(dom_error("SyntaxError", b"Invalid key usage"));
+ }
+ }
+
+ // 4. If extractable is not false, then throw a SyntaxError.
+ if extractable {
+ return Err(dom_error("SyntaxError", b"Key cannot be extractable"));
+ }
+
+ // 5. Let key be a new CryptoKey representing keyData.
+ let ImportKeyData::Bytes(data) = key_data else {
+ unreachable!("raw key data contains bytes")
+ };
+ let key = CryptoKey::from_byte_handle(cx.vm(), data.as_slice());
+
+ // 6. Set the [[type]] internal slot of key to "secret".
+ key.set_type(KeyType::Secret);
+
+ // 7. Let algorithm be a new KeyAlgorithm object.
+ // 8. Set the name attribute of algorithm to the name member of normalizedAlgorithm.
+ // 9. Set the [[algorithm]] internal slot of key to algorithm.
+ key.set_algorithm(InternalAlgorithmData::Key {
+ name: algorithm.name.clone(),
+ });
+
+ // 10. Return key.
+ Ok(key)
+ }
+
+ // https://wicg.github.io/webcrypto-modern-algos/#argon2-operations-get-key-length
+ fn get_key_length(&self, _: Gc<Realm>, _: &AlgorithmParams) -> WebIdlResult<Option<u32>> {
+ // 1. Return null.
+ Ok(None)
+ }
+}
+
+impl AlgorithmMethods for Argon2Params {
+ // https://wicg.github.io/webcrypto-modern-algos/#argon2-operations-derive-bits
+ fn validate_derive_bits_parameters(&self, _: Gc<Realm>, length: Option<u32>) -> WebIdlResult<()> {
+ let normalized_algorithm = self;
+
+ // 1. If length is null, or is less than 32 (4*8), or is not a multiple of 8, then throw an OperationError.
+ if length.is_none_or(|length| length < 32 || !length.is_multiple_of(8)) {
+ return Err(dom_error("OperationError", b"Length must be equal or greater than 32"));
+ }
+
+ // 2. If the version member of normalizedAlgorithm is present and is not 19 (0x13), then throw an OperationError.
+ if normalized_algorithm.version.is_some_and(|version| version != 19) {
+ return Err(dom_error("OperationError", b"Invalid algorithm version"));
+ }
+
+ // 3. If the parallelism member of normalizedAlgorithm is zero, or greater than 16777215 (2^24-1), then throw an OperationError.
+ if normalized_algorithm.parallelism == 0 || normalized_algorithm.parallelism > (1 << 24) - 1 {
+ return Err(dom_error("OperationError", b"Invalid parallelism"));
+ }
+
+ // 4. If the memory member of normalizedAlgorithm is less than 8 times the parallelism member of normalizedAlgorithm, then throw an OperationError.
+ if normalized_algorithm.memory < 8 * normalized_algorithm.parallelism {
+ return Err(dom_error(
+ "OperationError",
+ b"Memory is too low for the parallelism level",
+ ));
+ }
+
+ // 5. If the passes member of normalizedAlgorithm is zero, then throw an OperationError.
+ if normalized_algorithm.passes == 0 {
+ return Err(dom_error("OperationError", b"Invalid passes"));
+ }
+
+ // NB: Our Argon2 rejects short nonces.
+ // SAFETY: The nonce is lent to the validation service.
+ let result = unsafe { web_crypto_argon2_validate_parameters(Span::new(normalized_algorithm.nonce.as_slice())) };
+ if result != 0 {
+ // SAFETY: LibCrypto transfers an ownership reference.
+ let detail = unsafe { Utf16String::from_raw_owned(result) };
+ return Err(Exception::Dom(
+ "OperationError",
+ libjs_rust::api::utf16_formatted("Hashing function failed: {}", &[&detail]),
+ ));
+ }
+
+ Ok(())
+ }
+
+ // https://wicg.github.io/webcrypto-modern-algos/#argon2-operations-derive-bits
+ fn derive_bits(
+ &self,
+ realm: Gc<Realm>,
+ algorithm: &AlgorithmParams,
+ key: Ref<CryptoKey>,
+ length: Option<u32>,
+ ) -> WebIdlResult<Bytes> {
+ let normalized_algorithm = self;
+ // NB: Steps 1 to 5 are performed by validate_derive_bits_parameters().
+ self.validate_derive_bits_parameters(realm, length)?;
+
+ // 6 => If the name member of normalizedAlgorithm is a case-sensitive string match for "Argon2d":
+ // Let type be 0.
+ let kind = if matches!(algorithm.name.as_units(), Utf16StringUnits::Ascii(b"Argon2d")) {
+ Argon2Type::Argon2d
+ // => If the name member of normalizedAlgorithm is a case-sensitive string match for "Argon2i":
+ // Let type be 1.
+ } else if matches!(algorithm.name.as_units(), Utf16StringUnits::Ascii(b"Argon2i")) {
+ Argon2Type::Argon2i
+ // => If the name member of normalizedAlgorithm is a case-sensitive string match for "Argon2id":
+ // Let type be 2.
+ } else if matches!(algorithm.name.as_units(), Utf16StringUnits::Ascii(b"Argon2id")) {
+ Argon2Type::Argon2id
+ } else {
+ unreachable!("the name identifies an Argon2 variant");
+ };
+
+ // 7. Let secretValue be the secretValue member of normalizedAlgorithm, if present.
+ let secret_value = normalized_algorithm.secret_value.as_ref();
+
+ // 8. Let associatedData be the associatedData member of normalizedAlgorithm, if present.
+ let associated_data = normalized_algorithm.associated_data.as_ref();
+
+ // 9. Let result be the result of performing the Argon2 function defined in Section 3 of [RFC9106] using the
+ // password represented by [[handle]] internal slot of key as the message, P, the nonce attribute of
+ // normalizedAlgorithm as the nonce, S, the value of the parallelism attribute of normalizedAlgorithm as the
+ // degree of parallelism, p, the value of the memory attribute of normalizedAlgorithm as the memory size, m, the
+ // value of the passes attribute of normalizedAlgorithm as the number of passes, t, 0x13 as the version number,
+ // v, secretValue (if present) as the secret value, K, associatedData (if present) as the associated data, X, type
+ // as the type, y, and length divided by 8 as the tag length, T.
+ let inputs = Argon2Inputs {
+ message: Span::new(key.byte_handle_bytes()),
+ nonce: Span::new(normalized_algorithm.nonce.as_slice()),
+ parallelism: normalized_algorithm.parallelism,
+ memory: normalized_algorithm.memory,
+ passes: normalized_algorithm.passes,
+ version: 0x13,
+ secret_value: secret_value.into(),
+ associated_data: associated_data.into(),
+ tag_length: length.expect("validation requires a length") / 8,
+ };
+ let mut result: Option<Bytes> = None;
+ // SAFETY: The inputs and output are lent for this call.
+ let maybe_result = unsafe {
+ web_crypto_argon2_derive_key(kind, &inputs, core::ptr::from_mut(&mut result).cast(), receive_bytes)
+ };
+
+ // 10. If the key derivation operation fails, then throw an OperationError.
+ if maybe_result != 0 {
+ // SAFETY: LibCrypto transfers an ownership reference.
+ let detail = unsafe { Utf16String::from_raw_owned(maybe_result) };
+ return Err(Exception::Dom(
+ "OperationError",
+ libjs_rust::api::utf16_formatted("Hashing function failed: {}", &[&detail]),
+ ));
+ }
+
+ Ok(result.expect("LibCrypto returns the derived bytes"))
+ }
+}
+
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/subtle_crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
index b690a1796ee..a65f3cd1f07 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
@@ -31,9 +31,10 @@ use crate::bindings::promise::{
};
use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};
use crate::crypto::crypto_algorithms::{
- AlgorithmId, AlgorithmMethods, AlgorithmParams, Bytes, CShakeParams, CppAlgorithm, EncapsulatedKeyData,
- ExportKeyResult, Hmac, HmacImportParams, HmacKeyGenParams, ImportKeyData, Kmac, KmacImportParams, KmacKeyGenParams,
- KmacParams, ParameterId, Sha, normalized_key_usages, public_key_for_private_key,
+ AlgorithmId, AlgorithmMethods, AlgorithmParams, Argon2, Argon2Params, Bytes, CShakeParams, CppAlgorithm,
+ EncapsulatedKeyData, ExportKeyResult, Hkdf, HkdfParams, Hmac, HmacImportParams, HmacKeyGenParams, ImportKeyData,
+ Kmac, KmacImportParams, KmacKeyGenParams, KmacParams, ParameterId, Pbkdf2, Pbkdf2Params, Sha,
+ normalized_key_usages, public_key_for_private_key,
};
#[allow(
unused_imports,
@@ -95,6 +96,12 @@ enum RegisteredAlgorithm {
KmacSignOrVerify,
KmacKeyGen,
KmacImport,
+ Hkdf,
+ HkdfParams,
+ Pbkdf2,
+ Pbkdf2Params,
+ Argon2,
+ Argon2Params,
CShake,
}
@@ -113,6 +120,12 @@ enum AlgorithmImplementation {
KmacSignOrVerify(KmacParams),
KmacKeyGen(KmacKeyGenParams),
KmacImport(KmacImportParams),
+ Hkdf(Hkdf),
+ HkdfParams(HkdfParams),
+ Pbkdf2(Pbkdf2),
+ Pbkdf2Params(Pbkdf2Params),
+ Argon2(Argon2),
+ Argon2Params(Argon2Params),
CShake(CShakeParams),
}
@@ -130,6 +143,12 @@ impl Deref for AlgorithmImplementation {
Self::KmacSignOrVerify(algorithm) => algorithm,
Self::KmacKeyGen(algorithm) => algorithm,
Self::KmacImport(algorithm) => algorithm,
+ Self::Hkdf(algorithm) => algorithm,
+ Self::HkdfParams(algorithm) => algorithm,
+ Self::Pbkdf2(algorithm) => algorithm,
+ Self::Pbkdf2Params(algorithm) => algorithm,
+ Self::Argon2(algorithm) => algorithm,
+ Self::Argon2Params(algorithm) => algorithm,
Self::CShake(algorithm) => algorithm,
}
}
@@ -329,6 +348,18 @@ pub(crate) fn normalize_an_algorithm(
RegisteredAlgorithm::KmacImport => {
AlgorithmImplementation::KmacImport(KmacImportParams::from_value(vm, *algorithm)?)
}
+ RegisteredAlgorithm::Hkdf => AlgorithmImplementation::Hkdf(Hkdf),
+ RegisteredAlgorithm::HkdfParams => {
+ AlgorithmImplementation::HkdfParams(HkdfParams::from_value(vm, realm, *algorithm)?)
+ }
+ RegisteredAlgorithm::Pbkdf2 => AlgorithmImplementation::Pbkdf2(Pbkdf2),
+ RegisteredAlgorithm::Pbkdf2Params => {
+ AlgorithmImplementation::Pbkdf2Params(Pbkdf2Params::from_value(vm, realm, *algorithm)?)
+ }
+ RegisteredAlgorithm::Argon2 => AlgorithmImplementation::Argon2(Argon2),
+ RegisteredAlgorithm::Argon2Params => {
+ AlgorithmImplementation::Argon2Params(Argon2Params::from_value(vm, *algorithm)?)
+ }
RegisteredAlgorithm::CShake => AlgorithmImplementation::CShake(CShakeParams::from_value(vm, *algorithm)?),
};
@@ -1208,9 +1239,12 @@ impl SubtleCrypto {
}
// 9. Let result be the result of creating an ArrayBuffer containing the result of performing the derive bits operation specified by normalizedAlgorithm using baseKey, algorithm and length.
- let result = normalized_algorithm
- .methods
- .derive_bits(realm, base_key, length_optional);
+ let result = normalized_algorithm.methods.derive_bits(
+ realm,
+ &normalized_algorithm.parameter,
+ base_key,
+ length_optional,
+ );
if let Err(error) = result {
reject_promise_with_exception(vm, promise, error);
return;
@@ -1329,7 +1363,12 @@ impl SubtleCrypto {
let length = length_result.must();
// 14. Let secret be the result of performing the derive bits operation specified by normalizedAlgorithm using key, algorithm and length.
- let secret = normalized_algorithm.methods.derive_bits(realm, base_key, length);
+ let secret = normalized_algorithm.methods.derive_bits(
+ realm,
+ &normalized_algorithm.parameter,
+ base_key,
+ length,
+ );
if let Err(error) = secret {
reject_promise_with_exception(vm, promise, error);
return;
@@ -3132,19 +3171,14 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"deriveBits",
"HKDF",
- RegisteredAlgorithm::Cpp(AlgorithmId::Hkdf, ParameterId::HkdfParams),
- );
- define_an_algorithm(
- &mut internal_object,
- "importKey",
- "HKDF",
- RegisteredAlgorithm::Cpp(AlgorithmId::Hkdf, ParameterId::AlgorithmParams),
+ RegisteredAlgorithm::HkdfParams,
);
+ define_an_algorithm(&mut internal_object, "importKey", "HKDF", RegisteredAlgorithm::Hkdf);
define_an_algorithm(
&mut internal_object,
"get key length",
"HKDF",
- RegisteredAlgorithm::Cpp(AlgorithmId::Hkdf, ParameterId::AlgorithmParams),
+ RegisteredAlgorithm::Hkdf,
);
// https://w3c.github.io/webcrypto/#pbkdf2-registration
@@ -3152,19 +3186,14 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"deriveBits",
"PBKDF2",
- RegisteredAlgorithm::Cpp(AlgorithmId::Pbkdf2, ParameterId::Pbkdf2Params),
- );
- define_an_algorithm(
- &mut internal_object,
- "importKey",
- "PBKDF2",
- RegisteredAlgorithm::Cpp(AlgorithmId::Pbkdf2, ParameterId::AlgorithmParams),
+ RegisteredAlgorithm::Pbkdf2Params,
);
+ define_an_algorithm(&mut internal_object, "importKey", "PBKDF2", RegisteredAlgorithm::Pbkdf2);
define_an_algorithm(
&mut internal_object,
"get key length",
"PBKDF2",
- RegisteredAlgorithm::Cpp(AlgorithmId::Pbkdf2, ParameterId::AlgorithmParams),
+ RegisteredAlgorithm::Pbkdf2,
);
// https://wicg.github.io/webcrypto-secure-curves/#x25519-registration
@@ -3363,19 +3392,19 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"importKey",
algorithm,
- RegisteredAlgorithm::Cpp(AlgorithmId::Argon2, ParameterId::AlgorithmParams),
+ RegisteredAlgorithm::Argon2,
);
define_an_algorithm(
&mut internal_object,
"deriveBits",
algorithm,
- RegisteredAlgorithm::Cpp(AlgorithmId::Argon2, ParameterId::Argon2Params),
+ RegisteredAlgorithm::Argon2Params,
);
define_an_algorithm(
&mut internal_object,
"get key length",
algorithm,
- RegisteredAlgorithm::Cpp(AlgorithmId::Argon2, ParameterId::AlgorithmParams),
+ RegisteredAlgorithm::Argon2,
);
}
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
index 1a2675d99cc..941fbc1ab19 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
@@ -81,17 +81,15 @@ static JS::ThrowCompletionOr<HashAlgorithmIdentifier> hash_algorithm_identifier_
return HashAlgorithmIdentifier { Utf16String::adopt_raw(name) };
}
+extern "C" FlatPtr web_rust_crypto_sha_hash_kind(FlatPtr, i32*);
+
static WebIDL::ExceptionOr<::Crypto::Hash::HashKind> sha_hash_kind(Utf16String const& hash_algorithm)
{
- if (hash_algorithm == "SHA-1"sv)
- return ::Crypto::Hash::HashKind::SHA1;
- if (hash_algorithm == "SHA-256"sv)
- return ::Crypto::Hash::HashKind::SHA256;
- if (hash_algorithm == "SHA-384"sv)
- return ::Crypto::Hash::HashKind::SHA384;
- if (hash_algorithm == "SHA-512"sv)
- return ::Crypto::Hash::HashKind::SHA512;
- return WebIDL::NotSupportedError::create(Utf16String::formatted("Invalid hash function '{}'", hash_algorithm));
+ i32 kind = 0;
+ auto error = web_rust_crypto_sha_hash_kind(hash_algorithm.raw_identity(), &kind);
+ if (error != 0)
+ return WebIDL::NotSupportedError::create(Utf16String::adopt_raw(error));
+ return static_cast<::Crypto::Hash::HashKind>(kind);
}
static WebIDL::ExceptionOr<ByteBuffer> export_public_exponent(JS::VM& vm, ::Crypto::UnsignedBigInteger const& exponent)
@@ -517,52 +515,6 @@ JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AesGcmParams::from_value(J
return adopt_own<AlgorithmParams>(*new AesGcmParams { iv, maybe_additional_data, maybe_tag_length });
}
-HKDFParams::~HKDFParams() = default;
-
-JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> HKDFParams::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 salt_value = TRY(object.get("salt"_utf16_fly_string));
- if (!salt_value.is_object() || !(is<JS::TypedArrayBase>(salt_value.as_object()) || is<JS::ArrayBuffer>(salt_value.as_object()) || is<JS::DataView>(salt_value.as_object())))
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
- auto salt = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(salt_value.as_object()));
-
- auto info_value = TRY(object.get("info"_utf16_fly_string));
- if (!info_value.is_object() || !(is<JS::TypedArrayBase>(info_value.as_object()) || is<JS::ArrayBuffer>(info_value.as_object()) || is<JS::DataView>(info_value.as_object())))
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
- auto info = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(info_value.as_object()));
-
- return adopt_own<AlgorithmParams>(*new HKDFParams { hash, salt, info });
-}
-
-PBKDF2Params::~PBKDF2Params() = default;
-
-JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> PBKDF2Params::from_value(JS::Realm& realm, JS::Value value)
-{
- auto& vm = realm.vm();
- auto& object = value.as_object();
-
- auto salt_value = TRY(object.get("salt"_utf16_fly_string));
-
- if (!salt_value.is_object() || !(is<JS::TypedArrayBase>(salt_value.as_object()) || is<JS::ArrayBuffer>(salt_value.as_object()) || is<JS::DataView>(salt_value.as_object())))
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
-
- auto salt = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(salt_value.as_object()));
-
- auto iterations_value = TRY(object.get("iterations"_utf16_fly_string));
- auto iterations = TRY(WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, iterations_value, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No));
-
- auto hash_value = TRY(object.get("hash"_utf16_fly_string));
- auto hash = TRY(hash_algorithm_identifier_from_value(realm, hash_value));
-
- return adopt_own<AlgorithmParams>(*new PBKDF2Params { salt, iterations, hash });
-}
-
RsaKeyGenParams::~RsaKeyGenParams() = default;
JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaKeyGenParams::from_value(JS::Realm& realm, JS::Value value)
@@ -748,59 +700,6 @@ JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> Ed448Params::from_value(JS
return adopt_own<AlgorithmParams>(*new Ed448Params { maybe_context });
}
-static inline JS::ThrowCompletionOr<Optional<ByteBuffer>> get_optional_buffer_source(JS::VM& vm, JS::Object const& object, JS::PropertyKey const& name)
-{
- if (!TRY(object.has_property(name)))
- return OptionalNone {};
-
- auto value = TRY(object.get(name));
-
- if (!WebIDL::is_buffer_source_type(value))
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
-
- return TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(value.as_object()));
-}
-
-Argon2Params::~Argon2Params() = default;
-
-JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> Argon2Params::from_value(JS::Realm& realm, JS::Value value)
-{
- auto& vm = realm.vm();
- VERIFY(value.is_object());
- auto& object = value.as_object();
-
- if (!TRY(object.has_property("nonce"_utf16_fly_string))) {
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::MissingRequiredProperty, "nonce");
- }
- auto nonce_value = TRY(object.get("nonce"_utf16_fly_string));
- if (!nonce_value.is_object() || !(is<JS::TypedArrayBase>(nonce_value.as_object()) || is<JS::ArrayBuffer>(nonce_value.as_object()) || is<JS::DataView>(nonce_value.as_object())))
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
- auto const nonce = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(nonce_value.as_object()));
-
- auto const extract_u32_value = [&](auto const& name) -> JS::ThrowCompletionOr<WebIDL::UnsignedLong> {
- if (!TRY(object.has_property(name))) {
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::MissingRequiredProperty, name);
- }
- auto key_value = TRY(object.get(name));
- return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, key_value, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No);
- };
-
- auto const parallelism = TRY(extract_u32_value("parallelism"_utf16_fly_string));
- auto const memory = TRY(extract_u32_value("memory"_utf16_fly_string));
- auto const passes = TRY(extract_u32_value("passes"_utf16_fly_string));
-
- auto maybe_version = Optional<u8> {};
- if (TRY(object.has_property("version"_utf16_fly_string))) {
- auto version_value = TRY(object.get("version"_utf16_fly_string));
- maybe_version = TRY(WebIDL::convert_to_int<WebIDL::Octet>(vm, version_value, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No));
- }
-
- auto const secret_value = TRY(get_optional_buffer_source(vm, object, "secretValue"_utf16_fly_string));
- auto const associated_data = TRY(get_optional_buffer_source(vm, object, "associatedData"_utf16_fly_string));
-
- return adopt_own<AlgorithmParams>(*new Argon2Params { nonce, parallelism, memory, passes, maybe_version, secret_value, associated_data });
-}
-
// https://w3c.github.io/webcrypto/#rsa-oaep-operations-encrypt
WebIDL::ExceptionOr<ByteBuffer> RSAOAEP::encrypt(JS::Realm&, AlgorithmParams const& params, GC::Ref<CryptoKey> key, ByteBuffer const& plaintext)
{
@@ -3892,47 +3791,6 @@ WebIDL::ExceptionOr<ByteBuffer> AesKw::unwrap_key(JS::Realm&, AlgorithmParams co
return maybe_plaintext.release_value();
}
-// https://w3c.github.io/webcrypto/#hkdf-operations-import-key
-WebIDL::ExceptionOr<GC::Ref<CryptoKey>> HKDF::import_key(JS::Realm&, AlgorithmParams const&, KeyFormat format, CryptoKey::ImportKeyData key_data, bool extractable, Vector<KeyUsage> const& key_usages)
-{
- // 1. Let keyData be the key data to be imported.
-
- // 2. If format is "raw":
- // (… see below …)
- // Otherwise:
- // throw a NotSupportedError.
- // 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".
- if (format != KeyFormat::Raw && format != KeyFormat::RawSecret) {
- return WebIDL::NotSupportedError::create("Only raw format is supported"_utf16);
- }
-
- // 1. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
- for (auto& usage : key_usages) {
- if (usage != KeyUsage::DeriveKey && usage != KeyUsage::DeriveBits) {
- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));
- }
- }
-
- // 2. If extractable is not false, then throw a SyntaxError.
- if (extractable)
- return WebIDL::SyntaxError::create("extractable must be false"_utf16);
-
- // 3. Let key be a new CryptoKey representing the key data provided in keyData.
- auto key = CryptoKey::create(move(key_data.get<ByteBuffer>()));
-
- // 4. Set the [[type]] internal slot of key to "secret".
- key->set_type(KeyType::Secret);
-
- // 5. Let algorithm be a new KeyAlgorithm object.
- // 6. Set the name attribute of algorithm to "HKDF".
- // 7. Set the [[algorithm]] internal slot of key to algorithm.
- key->set_algorithm(CryptoKey::KeyAlgorithmData { "HKDF"_utf16 });
-
- // 8. Return key.
- return key;
-}
-
static_assert(to_underlying(::Crypto::Hash::HashKind::SHA1) == 4);
static_assert(to_underlying(::Crypto::Hash::HashKind::SHA256) == 5);
static_assert(to_underlying(::Crypto::Hash::HashKind::SHA384) == 6);
@@ -7003,168 +6861,6 @@ WebIDL::ExceptionOr<bool> ED448::verify(JS::Realm&, AlgorithmParams const& param
return maybe_verified.release_value();
}
-// https://w3c.github.io/webcrypto/#hkdf-operations-derive-bits
-WebIDL::ExceptionOr<void> HKDF::validate_derive_bits_parameters(AlgorithmParams const& params, Optional<u32> length_optional) const
-{
- auto const& normalized_algorithm = static_cast<HKDFParams const&>(params);
-
- // 1. If length is null or is not a multiple of 8, then throw an OperationError.
- if (!length_optional.has_value() || *length_optional % 8 != 0)
- return WebIDL::OperationError::create("Length must be specified and divisible by 8"_utf16);
-
- // 2. Let hashLength be the length in bits of the output of the hash function identified by the hash member of
- // normalizedAlgorithm.
- auto hash_kind = TRY(sha_hash_kind(normalized_algorithm.hash.name));
- auto hash_length = ::Crypto::Hash::Manager { hash_kind }.digest_size() * 8;
-
- // 3. If length is greater than 255 * hashLength, then throw an OperationError.
- if (*length_optional > 255 * hash_length)
- return WebIDL::OperationError::create("Length is too large for the hash function"_utf16);
-
- return {};
-}
-
-// https://w3c.github.io/webcrypto/#hkdf-operations-derive-bits
-WebIDL::ExceptionOr<ByteBuffer> HKDF::derive_bits(JS::Realm&, AlgorithmParams const& params, GC::Ref<CryptoKey> key, Optional<u32> length_optional)
-{
- auto const& normalized_algorithm = static_cast<HKDFParams const&>(params);
-
- // NB: Steps 1 to 3 are performed by validate_derive_bits_parameters().
- TRY(validate_derive_bits_parameters(params, length_optional));
- auto hash_kind = TRY(sha_hash_kind(normalized_algorithm.hash.name));
-
- // 4. Let keyDerivationKey be the secret represented by [[handle]] internal slot of key as the message.
- auto key_derivation_key = key->handle().get<ByteBuffer>();
-
- // 5. Let result be the result of performing the HKDF extract and then the HKDF expand step described in Section 2 of [RFC5869] using:
- // * the hash member of normalizedAlgorithm as Hash,
- // * keyDerivationKey as the input keying material, IKM,
- // * the contents of the salt member of normalizedAlgorithm as salt,
- // * the contents of the info member of normalizedAlgorithm as info,
- // * length divided by 8 as the value of L,
- // Note: Although HKDF technically supports absent salt (treating it as hashLen many NUL bytes),
- // all major browsers instead raise a TypeError, for example:
- // "Failed to execute 'deriveBits' on 'SubtleCrypto': HkdfParams: salt: Not a BufferSource"
- // Because we are forced by neither peer pressure nor the spec, we don't support it either.
-
- // Note: Check for zero length early because our implementation doesn't support it.
- if (*length_optional == 0) {
- return ByteBuffer {};
- }
-
- ::Crypto::Hash::HKDF hkdf(hash_kind);
- auto maybe_result = hkdf.derive_key(Optional<ReadonlyBytes>(normalized_algorithm.salt), key_derivation_key, normalized_algorithm.info, *length_optional / 8);
-
- // 6. If the key derivation operation fails, then throw an OperationError.
- if (maybe_result.is_error())
- return WebIDL::OperationError::create("Failed to derive key"_utf16);
-
- // 7. Return result
- return maybe_result.release_value();
-}
-
-// https://w3c.github.io/webcrypto/#hkdf-operations-get-key-length
-WebIDL::ExceptionOr<Optional<u32>> HKDF::get_key_length(JS::Realm&, AlgorithmParams const&)
-{
- // 1. Return null.
- return Optional<u32> {};
-}
-
-// https://w3c.github.io/webcrypto/#pbkdf2-operations-derive-bits
-WebIDL::ExceptionOr<void> PBKDF2::validate_derive_bits_parameters(AlgorithmParams const& params, Optional<u32> length_optional) const
-{
- auto const& normalized_algorithm = static_cast<PBKDF2Params const&>(params);
-
- // 1. If length is null or is not a multiple of 8, then throw an OperationError.
- if (!length_optional.has_value() || *length_optional % 8 != 0)
- return WebIDL::OperationError::create("Length must be greater than 0 and divisible by 8"_utf16);
-
- // 2. If the iterations member of normalizedAlgorithm is zero, then throw an OperationError.
- if (normalized_algorithm.iterations == 0)
- return WebIDL::OperationError::create("Iterations must be greater than 0"_utf16);
-
- // NB: Step 4 fails for the hash functions that our PBKDF2 does not support.
- TRY(sha_hash_kind(normalized_algorithm.hash.name));
-
- return {};
-}
-
-// https://w3c.github.io/webcrypto/#pbkdf2-operations-derive-bits
-WebIDL::ExceptionOr<ByteBuffer> PBKDF2::derive_bits(JS::Realm&, AlgorithmParams const& params, GC::Ref<CryptoKey> key, Optional<u32> length_optional)
-{
- auto const& normalized_algorithm = static_cast<PBKDF2Params const&>(params);
-
- // NB: Steps 1 and 2 are performed by validate_derive_bits_parameters().
- TRY(validate_derive_bits_parameters(params, length_optional));
-
- // 3. Let prf be the MAC Generation function described in Section 4 of [FIPS-198-1] using the hash function described by the hash member of normalizedAlgorithm.
- auto const& hash_algorithm = normalized_algorithm.hash.name;
-
- // 4. Let result be the result of performing the PBKDF2 operation defined in Section 5.2 of [RFC8018]
- // using prf as the pseudo-random function, PRF,
- // the password represented by [[handle]] internal slot of key as the password, P,
- // the contents of the salt attribute of normalizedAlgorithm as the salt, S,
- // the value of the iterations attribute of normalizedAlgorithm as the iteration count, c,
- // and length divided by 8 as the intended key length, dkLen.
- auto password = key->handle().get<ByteBuffer>();
- auto salt = normalized_algorithm.salt;
- auto iterations = normalized_algorithm.iterations;
- auto derived_key_length_bytes = *length_optional / 8;
-
- auto hash_kind = TRY(sha_hash_kind(hash_algorithm));
-
- ::Crypto::Hash::PBKDF2 pbkdf2(hash_kind);
- auto maybe_result = pbkdf2.derive_key(password, salt, iterations, derived_key_length_bytes);
-
- // 5. If the key derivation operation fails, then throw an OperationError.
- if (maybe_result.is_error())
- return WebIDL::OperationError::create("Failed to derive key"_utf16);
-
- // 6. Return result
- return maybe_result.release_value();
-}
-
-// https://w3c.github.io/webcrypto/#pbkdf2-operations-get-key-length
-WebIDL::ExceptionOr<Optional<u32>> PBKDF2::get_key_length(JS::Realm&, AlgorithmParams const&)
-{
- // 1. Return null.
- return Optional<u32> {};
-}
-
-// https://w3c.github.io/webcrypto/#pbkdf2-operations-import-key
-WebIDL::ExceptionOr<GC::Ref<CryptoKey>> PBKDF2::import_key(JS::Realm&, AlgorithmParams const&, KeyFormat format, CryptoKey::ImportKeyData key_data, bool extractable, Vector<KeyUsage> const& key_usages)
-{
- // 1. If format is not "raw", throw a NotSupportedError
- // 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".
- if (format != KeyFormat::Raw && format != KeyFormat::RawSecret)
- return WebIDL::NotSupportedError::create("Only raw format is supported"_utf16);
-
- // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
- for (auto& usage : key_usages) {
- if (usage != KeyUsage::DeriveKey && usage != KeyUsage::DeriveBits)
- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));
- }
-
- // 3. If extractable is not false, then throw a SyntaxError.
- if (extractable)
- return WebIDL::SyntaxError::create("extractable must be false"_utf16);
-
- // 4. Let key be a new CryptoKey representing keyData.
- auto key = CryptoKey::create(move(key_data.get<ByteBuffer>()));
-
- // 5. Set the [[type]] internal slot of key to "secret".
- key->set_type(KeyType::Secret);
-
- // 6. Let algorithm be a new KeyAlgorithm object.
- // 7. Set the name attribute of algorithm to "PBKDF2".
- // 8. Set the [[algorithm]] internal slot of key to algorithm.
- key->set_algorithm(CryptoKey::KeyAlgorithmData { "PBKDF2"_utf16 });
-
- // 9. Return key.
- return key;
-}
-
// https://w3c.github.io/webcrypto/#x25519-operations-derive-bits
WebIDL::ExceptionOr<void> X25519::validate_derive_bits_parameters(AlgorithmParams const& params, Optional<u32> length_optional) const
{
@@ -9352,142 +9048,82 @@ WebIDL::ExceptionOr<u32> MLKEM::get_shared_key_length(AlgorithmParams const&) co
return 256;
}
-// https://wicg.github.io/webcrypto-modern-algos/#argon2-operations-import-key
-WebIDL::ExceptionOr<GC::Ref<CryptoKey>> Argon2::import_key(JS::Realm&, AlgorithmParams const& params, KeyFormat format, CryptoKey::ImportKeyData key_data, bool extractable, Vector<KeyUsage> const& usages)
-{
- // 1. Let keyData be the key data to be imported.
- // 2. If format is not "raw-secret", throw a NotSupportedError
- if (format != KeyFormat::RawSecret)
- return WebIDL::NotSupportedError::create("Invalid key format"_utf16);
-
- // 3. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
- for (auto const usage : usages) {
- if (!(usage == KeyUsage::DeriveKey || usage == KeyUsage::DeriveBits))
- return WebIDL::SyntaxError::create("Invalid key usage"_utf16);
- }
-
- // 4. If extractable is not false, then throw a SyntaxError.
- if (extractable) {
- return WebIDL::SyntaxError::create("Key cannot be extractable"_utf16);
- }
-
- // 5. Let key be a new CryptoKey representing keyData.
- auto key = CryptoKey::create(move(key_data.get<ByteBuffer>()));
+struct OptionalBytes {
+ bool has_value;
+ ReadonlyBytes bytes;
- // 6. Set the [[type]] internal slot of key to "secret".
- key->set_type(KeyType::Secret);
+ Optional<ReadonlyBytes> to_optional() const { return has_value ? Optional<ReadonlyBytes> { bytes } : Optional<ReadonlyBytes> {}; }
+};
- // 7. Let algorithm be a new KeyAlgorithm object.
- // 8. Set the name attribute of algorithm to the name member of normalizedAlgorithm.
- // 9. Set the [[algorithm]] internal slot of key to algorithm.
- key->set_algorithm(CryptoKey::KeyAlgorithmData { params.name });
+struct Argon2Inputs {
+ ReadonlyBytes message;
+ ReadonlyBytes nonce;
+ u32 parallelism;
+ u32 memory;
+ u32 passes;
+ u32 version;
+ OptionalBytes secret_value;
+ OptionalBytes associated_data;
+ u32 tag_length;
+};
- // 10. Return key.
- return key;
+extern "C" {
+size_t web_crypto_hash_digest_size(::Crypto::Hash::HashKind);
+bool web_crypto_hkdf_derive_key(::Crypto::Hash::HashKind, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, u32, void*, ReceiveEncodedBytes);
+bool web_crypto_pbkdf2_derive_key(::Crypto::Hash::HashKind, ReadonlyBytes, ReadonlyBytes, u32, u32, void*, ReceiveEncodedBytes);
+FlatPtr web_crypto_argon2_validate_parameters(ReadonlyBytes);
+FlatPtr web_crypto_argon2_derive_key(::Crypto::Hash::Argon2Type, Argon2Inputs const*, void*, ReceiveEncodedBytes);
}
-// https://wicg.github.io/webcrypto-modern-algos/#argon2-operations-derive-bits
-WebIDL::ExceptionOr<void> Argon2::validate_derive_bits_parameters(AlgorithmParams const& params, Optional<u32> length) const
+size_t web_crypto_hash_digest_size(::Crypto::Hash::HashKind hash_kind)
{
- auto const& normalized_algorithm = static_cast<Argon2Params const&>(params);
-
- // 1. If length is null, or is less than 32 (4*8), or is not a multiple of 8, then throw an OperationError.
- if (!length.has_value() || length.value() < 32u || length.value() % 8 != 0)
- return WebIDL::OperationError::create("Length must be equal or greater than 32"_utf16);
-
- // 2. If the version member of normalizedAlgorithm is present and is not 19 (0x13), then throw an OperationError.
- if (normalized_algorithm.version.has_value() && normalized_algorithm.version != 19)
- return WebIDL::OperationError::create("Invalid algorithm version"_utf16);
-
- // 3. If the parallelism member of normalizedAlgorithm is zero, or greater than 16777215 (2^24-1), then throw an OperationError.
- if (normalized_algorithm.parallelism == 0 || normalized_algorithm.parallelism > (1 << 24) - 1)
- return WebIDL::OperationError::create("Invalid parallelism"_utf16);
-
- // 4. If the memory member of normalizedAlgorithm is less than 8 times the parallelism member of normalizedAlgorithm, then throw an OperationError.
- if (normalized_algorithm.memory < 8 * normalized_algorithm.parallelism)
- return WebIDL::OperationError::create("Memory is too low for the parallelism level"_utf16);
-
- // 5. If the passes member of normalizedAlgorithm is zero, then throw an OperationError.
- if (normalized_algorithm.passes == 0)
- return WebIDL::OperationError::create("Invalid passes"_utf16);
-
- // NB: Our Argon2 rejects short nonces.
- if (auto result = ::Crypto::Hash::Argon2::validate_parameters(normalized_algorithm.nonce); result.is_error())
- return WebIDL::OperationError::create(Utf16String::formatted("Hashing function failed: {}", result.error()));
-
- return {};
+ return ::Crypto::Hash::Manager { hash_kind }.digest_size();
}
-// https://wicg.github.io/webcrypto-modern-algos/#argon2-operations-derive-bits
-WebIDL::ExceptionOr<ByteBuffer> Argon2::derive_bits(JS::Realm&, AlgorithmParams const& params, GC::Ref<CryptoKey> key, Optional<u32> length)
+bool web_crypto_hkdf_derive_key(::Crypto::Hash::HashKind kind, ReadonlyBytes salt, ReadonlyBytes key_derivation_key, ReadonlyBytes info, u32 length, void* state, ReceiveEncodedBytes receive)
{
- auto const& normalized_algorithm = static_cast<Argon2Params const&>(params);
- // NB: Steps 1 to 5 are performed by validate_derive_bits_parameters().
- TRY(validate_derive_bits_parameters(params, length));
-
- auto const algorithm = [&]() {
- // 6 => If the name member of normalizedAlgorithm is a case-sensitive string match for "Argon2d":
- // Let type be 0.
- if (normalized_algorithm.name == "Argon2d"sv)
- return ::Crypto::Hash::Argon2(::Crypto::Hash::Argon2Type::Argon2d);
- // => If the name member of normalizedAlgorithm is a case-sensitive string match for "Argon2i":
- // Let type be 1.
- if (normalized_algorithm.name == "Argon2i"sv)
- return ::Crypto::Hash::Argon2(::Crypto::Hash::Argon2Type::Argon2i);
- // => If the name member of normalizedAlgorithm is a case-sensitive string match for "Argon2id":
- // Let type be 2.
- if (normalized_algorithm.name == "Argon2id"sv)
- return ::Crypto::Hash::Argon2(::Crypto::Hash::Argon2Type::Argon2id);
-
- VERIFY_NOT_REACHED();
- }();
-
- // 7. Let secretValue be the secretValue member of normalizedAlgorithm, if present.
- auto const& secret_value = normalized_algorithm.secret_value;
+ ::Crypto::Hash::HKDF hkdf(kind);
+ auto result = hkdf.derive_key(salt, key_derivation_key, info, length);
+ if (result.is_error())
+ return false;
+ receive(state, result.value());
+ return true;
+}
- // 8. Let associatedData be the associatedData member of normalizedAlgorithm, if present.
- auto const& associated_data = normalized_algorithm.associated_data;
+bool web_crypto_pbkdf2_derive_key(::Crypto::Hash::HashKind kind, ReadonlyBytes password, ReadonlyBytes salt, u32 iterations, u32 length, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Hash::PBKDF2 pbkdf2(kind);
+ auto result = pbkdf2.derive_key(password, salt, iterations, length);
+ if (result.is_error())
+ return false;
+ receive(state, result.value());
+ return true;
+}
- // 9. Let result be the result of performing the Argon2 function defined in Section 3 of [RFC9106] using the
- // password represented by [[handle]] internal slot of key as the message, P, the nonce attribute of
- // normalizedAlgorithm as the nonce, S, the value of the parallelism attribute of normalizedAlgorithm as the
- // degree of parallelism, p, the value of the memory attribute of normalizedAlgorithm as the memory size, m, the
- // value of the passes attribute of normalizedAlgorithm as the number of passes, t, 0x13 as the version number,
- // v, secretValue (if present) as the secret value, K, associatedData (if present) as the associated data, X, type
- // as the type, y, and length divided by 8 as the tag length, T.
- VERIFY(key->handle().has<ByteBuffer>());
- auto const maybe_result = algorithm.derive_key(
- key->handle().get<ByteBuffer>(),
- normalized_algorithm.nonce,
- normalized_algorithm.parallelism,
- normalized_algorithm.memory,
- normalized_algorithm.passes,
- 0x13,
- secret_value.map([](auto const& value) { return value.span(); }),
- associated_data.map([](auto const& value) { return value.span(); }),
- length.value() / 8);
-
- // 10. If the key derivation operation fails, then throw an OperationError.
- if (maybe_result.is_error())
- return WebIDL::OperationError::create(Utf16String::formatted("Hashing function failed: {}", maybe_result.error()));
+static_assert(to_underlying(::Crypto::Hash::Argon2Type::Argon2d) == 0);
+static_assert(to_underlying(::Crypto::Hash::Argon2Type::Argon2i) == 1);
+static_assert(to_underlying(::Crypto::Hash::Argon2Type::Argon2id) == 2);
- return maybe_result.value();
+FlatPtr web_crypto_argon2_validate_parameters(ReadonlyBytes nonce)
+{
+ auto result = ::Crypto::Hash::Argon2::validate_parameters(nonce);
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ return 0;
}
-// https://wicg.github.io/webcrypto-modern-algos/#argon2-operations-get-key-length
-WebIDL::ExceptionOr<Optional<u32>> Argon2::get_key_length(JS::Realm&, AlgorithmParams const&)
+FlatPtr web_crypto_argon2_derive_key(::Crypto::Hash::Argon2Type kind, Argon2Inputs const* inputs, void* state, ReceiveEncodedBytes receive)
{
- // 1. Return null.
- return Optional<u32> {};
+ ::Crypto::Hash::Argon2 algorithm(kind);
+ auto result = algorithm.derive_key(inputs->message, inputs->nonce, inputs->parallelism, inputs->memory,
+ inputs->passes, inputs->version, inputs->secret_value.to_optional(), inputs->associated_data.to_optional(),
+ inputs->tag_length);
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ receive(state, result.value());
+ return 0;
}
-struct OptionalBytes {
- bool has_value;
- ReadonlyBytes bytes;
-
- Optional<ReadonlyBytes> to_optional() const { return has_value ? Optional<ReadonlyBytes> { bytes } : Optional<ReadonlyBytes> {}; }
-};
-
static_assert(to_underlying(::Crypto::Hash::SHAKEKind::CSHAKE128) == 0);
static_assert(to_underlying(::Crypto::Hash::SHAKEKind::CSHAKE256) == 1);
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
index 97f3119debd..726c8f74ecc 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
@@ -95,40 +95,6 @@ struct AesGcmParams : public AlgorithmParams {
static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);
};
-// https://w3c.github.io/webcrypto/#hkdf-params
-struct HKDFParams : public AlgorithmParams {
- virtual ~HKDFParams() override;
- HKDFParams(HashAlgorithmIdentifier hash, ByteBuffer salt, ByteBuffer info)
- : hash(move(hash))
- , salt(move(salt))
- , info(move(info))
- {
- }
-
- HashAlgorithmIdentifier hash;
- ByteBuffer salt;
- ByteBuffer info;
-
- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);
-};
-
-// https://w3c.github.io/webcrypto/#pbkdf2-params
-struct PBKDF2Params : public AlgorithmParams {
- virtual ~PBKDF2Params() override;
- PBKDF2Params(ByteBuffer salt, u32 iterations, HashAlgorithmIdentifier hash)
- : salt(move(salt))
- , iterations(iterations)
- , hash(move(hash))
- {
- }
-
- ByteBuffer salt;
- u32 iterations;
- HashAlgorithmIdentifier hash;
-
- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);
-};
-
// https://w3c.github.io/webcrypto/#dfn-RsaKeyGenParams
struct RsaKeyGenParams : public AlgorithmParams {
virtual ~RsaKeyGenParams() override;
@@ -482,34 +448,6 @@ private:
AesKw() = default;
};
-class HKDF : public AlgorithmMethods {
-public:
- virtual WebIDL::ExceptionOr<GC::Ref<CryptoKey>> import_key(JS::Realm& realm, AlgorithmParams const&, KeyFormat, CryptoKey::ImportKeyData, bool, Vector<KeyUsage> const&) override;
- virtual WebIDL::ExceptionOr<ByteBuffer> derive_bits(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, Optional<u32>) override;
- virtual WebIDL::ExceptionOr<Optional<u32>> get_key_length(JS::Realm& realm, AlgorithmParams const&) override;
-
- virtual WebIDL::ExceptionOr<void> validate_derive_bits_parameters(AlgorithmParams const&, Optional<u32>) const override;
-
- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new HKDF); }
-
-private:
- HKDF() = default;
-};
-
-class PBKDF2 : public AlgorithmMethods {
-public:
- virtual WebIDL::ExceptionOr<GC::Ref<CryptoKey>> import_key(JS::Realm& realm, AlgorithmParams const&, KeyFormat, CryptoKey::ImportKeyData, bool, Vector<KeyUsage> const&) override;
- virtual WebIDL::ExceptionOr<ByteBuffer> derive_bits(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, Optional<u32>) override;
- virtual WebIDL::ExceptionOr<Optional<u32>> get_key_length(JS::Realm& realm, AlgorithmParams const&) override;
-
- virtual WebIDL::ExceptionOr<void> validate_derive_bits_parameters(AlgorithmParams const&, Optional<u32>) const override;
-
- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new PBKDF2); }
-
-private:
- PBKDF2() = default;
-};
-
class ECDSA : public AlgorithmMethods {
public:
virtual WebIDL::ExceptionOr<ByteBuffer> sign(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&) override;
@@ -649,20 +587,6 @@ private:
MLKEM() = default;
};
-class Argon2 : public AlgorithmMethods {
-public:
- virtual WebIDL::ExceptionOr<GC::Ref<CryptoKey>> import_key(JS::Realm& realm, AlgorithmParams const&, KeyFormat, CryptoKey::ImportKeyData, bool, Vector<KeyUsage> const&) override;
- virtual WebIDL::ExceptionOr<ByteBuffer> derive_bits(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, Optional<u32>) override;
- virtual WebIDL::ExceptionOr<Optional<u32>> get_key_length(JS::Realm& realm, AlgorithmParams const&) override;
-
- virtual WebIDL::ExceptionOr<void> validate_derive_bits_parameters(AlgorithmParams const&, Optional<u32>) const override;
-
- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new Argon2); }
-
-private:
- Argon2() = default;
-};
-
struct EcdhKeyDeriveParams : public AlgorithmParams {
virtual ~EcdhKeyDeriveParams() override;
@@ -706,32 +630,6 @@ struct Ed448Params : public AlgorithmParams {
// https://wicg.github.io/webcrypto-modern-algos/#dfn-ContextParams
using ContextParams = Ed448Params;
-// https://wicg.github.io/webcrypto-modern-algos/#argon2-params
-struct Argon2Params : public AlgorithmParams {
- virtual ~Argon2Params() override;
-
- Argon2Params(ByteBuffer nonce, u32 parallelism, u32 memory, u32 passes, Optional<u8> version, Optional<ByteBuffer> secret_value, Optional<ByteBuffer> associated_data)
- : nonce(move(nonce))
- , parallelism(parallelism)
- , memory(memory)
- , passes(passes)
- , version(version)
- , secret_value(secret_value)
- , associated_data(associated_data)
- {
- }
-
- ByteBuffer nonce;
- u32 parallelism;
- u32 memory;
- u32 passes;
- Optional<u8> version;
- Optional<ByteBuffer> secret_value;
- Optional<ByteBuffer> associated_data;
-
- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);
-};
-
// https://wicg.github.io/webcrypto-modern-algos/#cshake-params
// https://wicg.github.io/webcrypto-modern-algos/#dfn-AeadParams
// NOTE: The AeadParams dictionary is identical to the AesGcmParams
diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
index 512c143d2f6..b9d31f2f78f 100644
--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
@@ -25,15 +25,12 @@ enum class AlgorithmId : u8 {
AesCbc,
AesGcm,
AesKw,
- HKDF,
- PBKDF2,
X25519,
X448,
ED25519,
ED448,
MLDSA,
MLKEM,
- Argon2,
ChaCha20Poly1305,
AesOcb,
};
@@ -53,11 +50,8 @@ enum class ParameterId : u8 {
AesDerivedKeyParams,
AesCbcParams,
AesGcmParams,
- HKDFParams,
- PBKDF2Params,
Ed448Params,
ContextParams,
- Argon2Params,
AeadParams,
};
@@ -245,10 +239,6 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithm
return AesGcm::create();
case AlgorithmId::AesKw:
return AesKw::create();
- case AlgorithmId::HKDF:
- return HKDF::create();
- case AlgorithmId::PBKDF2:
- return PBKDF2::create();
case AlgorithmId::X25519:
return X25519::create();
case AlgorithmId::X448:
@@ -261,8 +251,6 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithm
return MLDSA::create();
case AlgorithmId::MLKEM:
return MLKEM::create();
- case AlgorithmId::Argon2:
- return Argon2::create();
case AlgorithmId::ChaCha20Poly1305:
return ChaCha20Poly1305::create();
case AlgorithmId::AesOcb:
@@ -301,16 +289,10 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithm
return AesCbcParams::from_value(realm, object);
case ParameterId::AesGcmParams:
return AesGcmParams::from_value(realm, object);
- case ParameterId::HKDFParams:
- return HKDFParams::from_value(realm, object);
- case ParameterId::PBKDF2Params:
- return PBKDF2Params::from_value(realm, object);
case ParameterId::Ed448Params:
return Ed448Params::from_value(realm, object);
case ParameterId::ContextParams:
return ContextParams::from_value(realm, object);
- case ParameterId::Argon2Params:
- return Argon2Params::from_value(realm, object);
case ParameterId::AeadParams:
return AeadParams::from_value(realm, object);
}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index a896b3d91eb..bf0076b0e17 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,
- 307,
+ 283,
"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",