Skip to content

Truly independent web browser

LibWeb: Port WebCrypto SHA and cSHAKE algorithms to Rust

Shannon Boothc58d4cdefb4c
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index 33314779c2c..3707b03c06c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -14,13 +14,18 @@ use core::ptr::{NonNull, null, null_mut};
use std::rc::Rc;
use ak::{Span, Utf16String, Utf16StringUnits};
-use libjs_rust::api::{Gc, RawNativeFunctionResult, Realm, Trace, Value, Vm};
+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::interface::{Ref, cell_from_abi, cell_into_abi, realm_arguments};
-use crate::bindings::{CallContext, WebIdlResult};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
use crate::crypto::crypto_bindings::{CryptoKeyPair, JsonWebKey, RawJsonWebKey};
use crate::crypto::crypto_key::{CryptoKey, KeyUsage};
-use crate::crypto::subtle_crypto::{AlgorithmIdentifier, CryptoKeyOrCryptoKeyPair, KeyFormat, normalize_an_algorithm};
+use crate::crypto::subtle_crypto::{
+ AlgorithmIdentifier, CryptoKeyOrCryptoKeyPair, KeyFormat, get_a_copy_of_the_bytes, normalize_an_algorithm,
+};
// https://w3c.github.io/webcrypto/#algorithm-overview
#[derive(Clone, Trace)]
@@ -344,8 +349,6 @@ pub(crate) enum AlgorithmId {
AesGcm,
AesKw,
Hmac,
- Sha,
- CShake,
Hkdf,
Pbkdf2,
X25519,
@@ -383,7 +386,6 @@ pub(crate) enum ParameterId {
AesGcmParams,
HmacKeyGenParams,
HmacImportParams,
- CShakeParams,
HkdfParams,
Pbkdf2Params,
Ed448Params,
@@ -499,13 +501,6 @@ unsafe extern "C" {
data: Span<'_, u8>,
out: &mut bool,
) -> RawNativeFunctionResult;
- fn web_crypto_algorithm_digest(
- realm: *mut c_void,
- algorithm: *mut c_void,
- data: Span<'_, u8>,
- state: *mut c_void,
- receive: ReceiveBytes,
- ) -> RawNativeFunctionResult;
fn web_crypto_algorithm_derive_bits(
realm: *mut c_void,
algorithm: *mut c_void,
@@ -600,10 +595,6 @@ unsafe extern "C" {
realm: *mut c_void,
algorithm: *mut c_void,
) -> RawNativeFunctionResult;
- fn web_crypto_algorithm_validate_digest_parameters(
- realm: *mut c_void,
- algorithm: *mut c_void,
- ) -> RawNativeFunctionResult;
fn web_crypto_algorithm_validate_generate_key_parameters(
realm: *mut c_void,
algorithm: *mut c_void,
@@ -619,7 +610,9 @@ unsafe extern "C" {
) -> RawNativeFunctionResult;
}
-pub(crate) struct CppAlgorithm(NonNull<c_void>);
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CppAlgorithm(#[gc(untraced)] NonNull<c_void>);
impl Drop for CppAlgorithm {
fn drop(&mut self) {
@@ -651,8 +644,165 @@ impl CppAlgorithm {
.into_completion()?;
Ok(Self(NonNull::new(out).expect("LibWeb returns an algorithm")))
}
+}
+
+pub(crate) trait AlgorithmMethods: Trace {
+ fn public_key_usages(&self) -> Option<Vec<KeyUsage>> {
+ None
+ }
+
+ fn encrypt(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _data: &Bytes) -> WebIdlResult<Bytes> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("encrypt is not supported"),
+ ))
+ }
+
+ fn decrypt(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _data: &Bytes) -> WebIdlResult<Bytes> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("decrypt is not supported"),
+ ))
+ }
+
+ fn sign(&self, _realm: Gc<Realm>, _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> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("verify is not supported"),
+ ))
+ }
+
+ fn digest(&self, _realm: Gc<Realm>, _algorithm: &AlgorithmParams, _data: &Bytes) -> WebIdlResult<Bytes> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("digest is not supported"),
+ ))
+ }
+
+ fn derive_bits(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _length: Option<u32>) -> WebIdlResult<Bytes> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("deriveBits is not supported"),
+ ))
+ }
+
+ fn import_key(
+ &self,
+ _realm: Gc<Realm>,
+ _format: KeyFormat,
+ _key_data: ImportKeyData,
+ _extractable: bool,
+ _usages: &[KeyUsage],
+ ) -> WebIdlResult<Ref<CryptoKey>> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("importKey is not supported"),
+ ))
+ }
+
+ fn generate_key(
+ &self,
+ _realm: Gc<Realm>,
+ _extractable: bool,
+ _usages: &[KeyUsage],
+ ) -> WebIdlResult<CryptoKeyOrCryptoKeyPair> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("generateKey is not supported"),
+ ))
+ }
+
+ fn export_key(&self, _realm: Gc<Realm>, _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>> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("getKeyLength is not supported"),
+ ))
+ }
+
+ fn get_shared_key_length(&self, _realm: Gc<Realm>) -> WebIdlResult<u32> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("getSharedKeyLength is not supported"),
+ ))
+ }
+
+ fn wrap_key(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _data: &Bytes) -> WebIdlResult<Bytes> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("wrapKey is not supported"),
+ ))
+ }
+
+ fn unwrap_key(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _data: &Bytes) -> WebIdlResult<Bytes> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("unwwrapKey is not supported"),
+ ))
+ }
+
+ fn encapsulate(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>) -> WebIdlResult<EncapsulatedBitsData> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("encapsulate is not supported"),
+ ))
+ }
- pub(crate) fn public_key_usages(&self) -> Option<Vec<KeyUsage>> {
+ fn decapsulate(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _data: &Bytes) -> WebIdlResult<Bytes> {
+ Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("decalpsulate is not supported"),
+ ))
+ }
+
+ fn validate_encrypt_parameters(&self, _realm: Gc<Realm>) -> WebIdlResult<()> {
+ Ok(())
+ }
+
+ fn validate_decrypt_parameters(&self, _realm: Gc<Realm>) -> WebIdlResult<()> {
+ Ok(())
+ }
+
+ fn validate_sign_parameters(&self, _realm: Gc<Realm>) -> WebIdlResult<()> {
+ Ok(())
+ }
+
+ fn validate_verify_parameters(&self, _realm: Gc<Realm>) -> WebIdlResult<()> {
+ Ok(())
+ }
+
+ fn validate_digest_parameters(&self, _realm: Gc<Realm>) -> WebIdlResult<()> {
+ Ok(())
+ }
+
+ fn validate_generate_key_parameters(&self, _realm: Gc<Realm>) -> WebIdlResult<()> {
+ Ok(())
+ }
+
+ fn validate_import_key_parameters(&self, _realm: Gc<Realm>) -> WebIdlResult<()> {
+ Ok(())
+ }
+
+ fn validate_derive_bits_parameters(&self, _realm: Gc<Realm>, _length: Option<u32>) -> WebIdlResult<()> {
+ Ok(())
+ }
+}
+
+impl AlgorithmMethods for CppAlgorithm {
+ fn public_key_usages(&self) -> Option<Vec<KeyUsage>> {
let mut usages = None;
// SAFETY: This object owns the algorithm and the state is writable for the call.
unsafe {
@@ -665,7 +815,7 @@ impl CppAlgorithm {
usages
}
- pub(crate) fn encrypt(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {
+ fn encrypt(&self, realm: Gc<Realm>, 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 {
@@ -682,7 +832,7 @@ impl CppAlgorithm {
Ok(out.expect("LibWeb returns bytes"))
}
- pub(crate) fn decrypt(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {
+ fn decrypt(&self, realm: Gc<Realm>, 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 {
@@ -699,7 +849,7 @@ impl CppAlgorithm {
Ok(out.expect("LibWeb returns bytes"))
}
- pub(crate) fn sign(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {
+ fn sign(&self, realm: Gc<Realm>, 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 {
@@ -716,13 +866,7 @@ impl CppAlgorithm {
Ok(out.expect("LibWeb returns bytes"))
}
- pub(crate) fn verify(
- &self,
- realm: Gc<Realm>,
- key: Ref<CryptoKey>,
- signature: &Bytes,
- data: &Bytes,
- ) -> WebIdlResult<bool> {
+ fn verify(&self, realm: Gc<Realm>, 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 {
@@ -739,28 +883,7 @@ impl CppAlgorithm {
Ok(out)
}
- pub(crate) fn digest(&self, realm: Gc<Realm>, 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 {
- web_crypto_algorithm_digest(
- realm.as_ptr().cast(),
- self.0.as_ptr(),
- Span::new(data.as_slice()),
- core::ptr::from_mut(&mut out).cast(),
- receive_bytes,
- )
- }
- .into_completion()?;
- Ok(out.expect("LibWeb returns bytes"))
- }
-
- pub(crate) fn derive_bits(
- &self,
- realm: Gc<Realm>,
- key: Ref<CryptoKey>,
- length: Option<u32>,
- ) -> WebIdlResult<Bytes> {
+ fn derive_bits(&self, realm: Gc<Realm>, 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 {
@@ -777,7 +900,7 @@ impl CppAlgorithm {
Ok(out.expect("LibWeb returns bytes"))
}
- pub(crate) fn import_key(
+ fn import_key(
&self,
realm: Gc<Realm>,
format: KeyFormat,
@@ -812,7 +935,7 @@ impl CppAlgorithm {
Ok(unsafe { cell_from_abi(out) })
}
- pub(crate) fn generate_key(
+ fn generate_key(
&self,
realm: Gc<Realm>,
extractable: bool,
@@ -845,12 +968,7 @@ impl CppAlgorithm {
}
}
- pub(crate) fn export_key(
- &self,
- realm: Gc<Realm>,
- format: KeyFormat,
- key: Ref<CryptoKey>,
- ) -> WebIdlResult<ExportKeyResult> {
+ fn export_key(&self, realm: Gc<Realm>, format: KeyFormat, key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {
let mut out: Option<ExportKeyResult> = None;
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe {
@@ -868,7 +986,7 @@ impl CppAlgorithm {
Ok(out.expect("LibWeb returns an export result"))
}
- pub(crate) fn get_key_length(&self, realm: Gc<Realm>) -> WebIdlResult<Option<u32>> {
+ fn get_key_length(&self, realm: Gc<Realm>) -> 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) }
@@ -876,7 +994,7 @@ impl CppAlgorithm {
Ok(out.has_value.then_some(out.value))
}
- pub(crate) fn get_shared_key_length(&self, realm: Gc<Realm>) -> WebIdlResult<u32> {
+ fn get_shared_key_length(&self, realm: Gc<Realm>) -> WebIdlResult<u32> {
let mut out = 0;
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe { web_crypto_algorithm_get_shared_key_length(realm.as_ptr().cast(), self.0.as_ptr(), &mut out) }
@@ -884,7 +1002,7 @@ impl CppAlgorithm {
Ok(out)
}
- pub(crate) fn wrap_key(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {
+ fn wrap_key(&self, realm: Gc<Realm>, 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 {
@@ -901,7 +1019,7 @@ impl CppAlgorithm {
Ok(out.expect("LibWeb returns bytes"))
}
- pub(crate) fn unwrap_key(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {
+ fn unwrap_key(&self, realm: Gc<Realm>, 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 {
@@ -918,7 +1036,7 @@ impl CppAlgorithm {
Ok(out.expect("LibWeb returns bytes"))
}
- pub(crate) fn encapsulate(&self, realm: Gc<Realm>, key: Ref<CryptoKey>) -> WebIdlResult<EncapsulatedBitsData> {
+ fn encapsulate(&self, realm: Gc<Realm>, key: Ref<CryptoKey>) -> WebIdlResult<EncapsulatedBitsData> {
let (mut shared_key, mut ciphertext): (Option<Bytes>, Option<Bytes>) = (None, None);
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe {
@@ -935,7 +1053,7 @@ impl CppAlgorithm {
Ok(EncapsulatedBitsData { shared_key, ciphertext })
}
- pub(crate) fn decapsulate(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {
+ fn decapsulate(&self, realm: Gc<Realm>, 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 {
@@ -952,56 +1070,49 @@ impl CppAlgorithm {
Ok(out.expect("LibWeb returns bytes"))
}
- pub(crate) fn validate_encrypt_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
+ fn validate_encrypt_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe { web_crypto_algorithm_validate_encrypt_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }
.into_completion()?;
Ok(())
}
- pub(crate) fn validate_decrypt_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
+ fn validate_decrypt_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe { web_crypto_algorithm_validate_decrypt_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }
.into_completion()?;
Ok(())
}
- pub(crate) fn validate_sign_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
+ fn validate_sign_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe { web_crypto_algorithm_validate_sign_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }
.into_completion()?;
Ok(())
}
- pub(crate) fn validate_verify_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
+ fn validate_verify_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe { web_crypto_algorithm_validate_verify_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }
.into_completion()?;
Ok(())
}
- pub(crate) fn validate_digest_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
- unsafe { web_crypto_algorithm_validate_digest_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }
- .into_completion()?;
- Ok(())
- }
-
- pub(crate) fn validate_generate_key_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
+ fn validate_generate_key_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe { web_crypto_algorithm_validate_generate_key_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }
.into_completion()?;
Ok(())
}
- pub(crate) fn validate_import_key_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
+ fn validate_import_key_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe { web_crypto_algorithm_validate_import_key_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }
.into_completion()?;
Ok(())
}
- pub(crate) fn validate_derive_bits_parameters(&self, realm: Gc<Realm>, length: Option<u32>) -> WebIdlResult<()> {
+ fn validate_derive_bits_parameters(&self, realm: Gc<Realm>, length: Option<u32>) -> WebIdlResult<()> {
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe {
web_crypto_algorithm_validate_derive_bits_parameters(realm.as_ptr().cast(), self.0.as_ptr(), length.into())
@@ -1011,6 +1122,241 @@ impl CppAlgorithm {
}
}
+#[repr(i32)]
+enum ShaHashKind {
+ Sha1 = 4,
+ Sha256,
+ Sha384,
+ Sha512,
+ Sha3_256,
+ Sha3_384,
+ Sha3_512,
+}
+
+#[repr(i32)]
+enum CShakeKind {
+ CShake128,
+ CShake256,
+}
+
+#[repr(C)]
+struct OptionalBytes<'a> {
+ has_value: bool,
+ bytes: Span<'a, u8>,
+}
+
+impl<'a> From<Option<&'a Bytes>> for OptionalBytes<'a> {
+ fn from(value: Option<&'a Bytes>) -> Self {
+ Self {
+ has_value: value.is_some(),
+ bytes: Span::new(value.map_or(&[], Bytes::as_slice)),
+ }
+ }
+}
+
+unsafe extern "C" {
+ fn web_crypto_sha_digest(kind: ShaHashKind, data: Span<'_, u8>, state: *mut c_void, receive: ReceiveBytes) -> bool;
+ fn web_crypto_cshake_validate_parameters(
+ output_length: u32,
+ customization: OptionalBytes<'_>,
+ function_name: OptionalBytes<'_>,
+ ) -> usize;
+ fn web_crypto_cshake_digest(
+ kind: CShakeKind,
+ data: Span<'_, u8>,
+ output_length: u32,
+ customization: OptionalBytes<'_>,
+ function_name: OptionalBytes<'_>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+}
+
+fn get_optional_buffer_source(vm: &Vm, object: Gc<Object>, name: &PropertyKey) -> WebIdlResult<Option<Bytes>> {
+ if !object.has_property(vm, name)? {
+ return Ok(None);
+ }
+
+ let value = object.get(vm, name)?;
+ let Some(buffer_source) = buffer_source_type_of(value) else {
+ return vm
+ .throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"BufferSource"])
+ .map_err(Into::into);
+ };
+
+ Ok(Some(get_a_copy_of_the_bytes(vm, buffer_source)?))
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CShakeParams {
+ output_length: u32,
+ function_name: Option<Bytes>,
+ customization: Option<Bytes>,
+}
+
+impl CShakeParams {
+ pub(crate) fn from_value(vm: &Vm, object: Gc<Object>) -> WebIdlResult<Self> {
+ 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)?;
+
+ let function_name = get_optional_buffer_source(vm, object, &PropertyKey::from_utf8("functionName"))?;
+
+ let customization = get_optional_buffer_source(vm, object, &PropertyKey::from_utf8("customization"))?;
+
+ Ok(Self {
+ output_length: length,
+ function_name,
+ customization,
+ })
+ }
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Sha;
+
+impl AlgorithmMethods for Sha {
+ // https://w3c.github.io/webcrypto/#sha-operations-digest
+ fn digest(&self, _: Gc<Realm>, algorithm: &AlgorithmParams, data: &Bytes) -> WebIdlResult<Bytes> {
+ let algorithm_name = &algorithm.name;
+
+ let hash_kind = if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"SHA-1")) {
+ ShaHashKind::Sha1
+ } else if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"SHA-256")) {
+ ShaHashKind::Sha256
+ } else if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"SHA-384")) {
+ ShaHashKind::Sha384
+ } else if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"SHA-512")) {
+ ShaHashKind::Sha512
+ } else if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"SHA3-256")) {
+ ShaHashKind::Sha3_256
+ } else if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"SHA3-384")) {
+ ShaHashKind::Sha3_384
+ } else if matches!(algorithm_name.as_units(), Utf16StringUnits::Ascii(b"SHA3-512")) {
+ ShaHashKind::Sha3_512
+ } else {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ libjs_rust::api::utf16_formatted("Invalid hash function '{}'", &[algorithm_name]),
+ ));
+ };
+
+ let mut result_buffer: Option<Bytes> = None;
+ // SAFETY: The input and the output slot live for the call.
+ let success = unsafe {
+ web_crypto_sha_digest(
+ hash_kind,
+ Span::new(data.as_slice()),
+ core::ptr::from_mut(&mut result_buffer).cast(),
+ receive_bytes,
+ )
+ };
+ if !success {
+ return Err(Exception::Dom(
+ "OperationError",
+ Utf16String::from_utf8("Failed to create result buffer"),
+ ));
+ }
+
+ Ok(result_buffer.expect("LibCrypto returns the digest"))
+ }
+}
+
+impl AlgorithmMethods for CShakeParams {
+ // https://wicg.github.io/webcrypto-modern-algos/#cshake-operations-digest
+ fn validate_digest_parameters(&self, _: Gc<Realm>) -> WebIdlResult<()> {
+ // NB: Step 5 throws an OperationError for the parameters that our cSHAKE does not support.
+ let normalized_algorithm = self;
+ // SAFETY: The parameters live for the call.
+ let result = unsafe {
+ web_crypto_cshake_validate_parameters(
+ normalized_algorithm.output_length,
+ normalized_algorithm.customization.as_ref().into(),
+ normalized_algorithm.function_name.as_ref().into(),
+ )
+ };
+ 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("Hash function failed: {}", &[&detail]),
+ ));
+ }
+
+ Ok(())
+ }
+
+ // https://wicg.github.io/webcrypto-modern-algos/#cshake-operations-digest
+ fn digest(&self, _: Gc<Realm>, algorithm: &AlgorithmParams, data: &Bytes) -> WebIdlResult<Bytes> {
+ let normalized_algorithm = self;
+
+ // 1. Let outputLength be the outputLength member of normalizedAlgorithm.
+ let output_length = normalized_algorithm.output_length;
+
+ // 2. Let functionName be the functionName member of normalizedAlgorithm if present or the empty octet string otherwise.
+ let function_name = normalized_algorithm.function_name.as_ref();
+
+ // 3. Let customization be the customization member of normalizedAlgorithm if present or the empty octet string otherwise.
+ let customization = normalized_algorithm.customization.as_ref();
+
+ // 4. If the name member of normalizedAlgorithm is a case-sensitive string match for "cSHAKE128":
+ let kind = if matches!(algorithm.name.as_units(), Utf16StringUnits::Ascii(b"cSHAKE128")) {
+ CShakeKind::CShake128
+ // 4. If the name member of normalizedAlgorithm is a case-sensitive string match for "cSHAKE256":
+ } else if matches!(algorithm.name.as_units(), Utf16StringUnits::Ascii(b"cSHAKE256")) {
+ CShakeKind::CShake256
+ } else {
+ unreachable!("the algorithm is cSHAKE128 or cSHAKE256");
+ };
+
+ // 4. Let result be the result of performing the cSHAKE128/cSHAKE256 function defined in Section 3 of [NIST-SP800-185]
+ // using message as the X input parameter,
+ // outputLength as the L input parameter,
+ // functionName as the N input parameter,
+ // and customization as the S input parameter.
+ let mut result: Option<Bytes> = None;
+ // SAFETY: The input and the output slot live for the call.
+ let maybe_result = unsafe {
+ web_crypto_cshake_digest(
+ kind,
+ Span::new(data.as_slice()),
+ output_length,
+ customization.into(),
+ function_name.into(),
+ core::ptr::from_mut(&mut result).cast(),
+ receive_bytes,
+ )
+ };
+
+ // 5. If performing the operation results in an error, 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("Hash function failed: {}", &[&detail]),
+ ));
+ }
+
+ // 6. Return result.
+ Ok(result.expect("LibCrypto returns the digest"))
+ }
+}
+
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 361592aa980..a7511e4d0c1 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
@@ -7,6 +7,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+use core::ops::Deref;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::LazyLock;
@@ -30,8 +31,8 @@ use crate::bindings::promise::{
};
use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};
use crate::crypto::crypto_algorithms::{
- AlgorithmId, AlgorithmParams, Bytes, CppAlgorithm, EncapsulatedKeyData, ExportKeyResult, ImportKeyData,
- ParameterId, normalized_key_usages, public_key_for_private_key,
+ AlgorithmId, AlgorithmMethods, AlgorithmParams, Bytes, CShakeParams, CppAlgorithm, EncapsulatedKeyData,
+ ExportKeyResult, ImportKeyData, ParameterId, Sha, normalized_key_usages, public_key_for_private_key,
};
#[allow(
unused_imports,
@@ -83,24 +84,44 @@ pub(crate) enum KeyFormat {
}
#[derive(Clone, Copy)]
-struct RegisteredAlgorithm {
- method_id: AlgorithmId,
- parameter_id: ParameterId,
+enum RegisteredAlgorithm {
+ Cpp(AlgorithmId, ParameterId),
+ Sha,
+ CShake,
}
type RegisteredAlgorithms = HashMap<&'static str, RegisteredAlgorithm>;
type SupportedAlgorithmsMap = HashMap<&'static str, RegisteredAlgorithms>;
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+enum AlgorithmImplementation {
+ Cpp(#[gc(untraced)] Rc<CppAlgorithm>),
+ Sha(Sha),
+ CShake(CShakeParams),
+}
+
+impl Deref for AlgorithmImplementation {
+ type Target = dyn AlgorithmMethods;
+
+ fn deref(&self) -> &Self::Target {
+ match self {
+ Self::Cpp(algorithm) => algorithm.as_ref(),
+ Self::Sha(algorithm) => algorithm,
+ Self::CShake(algorithm) => algorithm,
+ }
+ }
+}
+
#[derive(Clone, Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct NormalizedAlgorithmAndParameter {
pub(crate) parameter: AlgorithmParams,
- #[gc(untraced)]
- pub(crate) methods: Rc<CppAlgorithm>,
+ methods: AlgorithmImplementation,
}
// NB: Getting a copy of the bytes held by a buffer source can only fail when allocating the copy fails.
-fn get_a_copy_of_the_bytes(vm: &Vm, buffer_source: BufferSource) -> WebIdlResult<Bytes> {
+pub(super) fn get_a_copy_of_the_bytes(vm: &Vm, buffer_source: BufferSource) -> WebIdlResult<Bytes> {
// SAFETY: Copying the bytes neither runs script nor allocates a cell.
let data = unsafe {
buffer_source.with_bytes(|bytes| {
@@ -258,13 +279,19 @@ pub(crate) fn normalize_an_algorithm(
// and all of desiredType's inherited dictionaries, in order from least to most derived.
// 12. For each dictionary dictionary in dictionaries:
// Note: All of these steps are handled by the create_methods and parameter_from_value methods.
- let methods = Rc::new(CppAlgorithm::from_value(
- realm,
- desired_type.method_id,
- desired_type.parameter_id,
- Value::from_object(*algorithm),
- &algorithm_name,
- )?);
+ let methods = match desired_type {
+ RegisteredAlgorithm::Cpp(method_id, parameter_id) => {
+ AlgorithmImplementation::Cpp(Rc::new(CppAlgorithm::from_value(
+ realm,
+ method_id,
+ parameter_id,
+ Value::from_object(*algorithm),
+ &algorithm_name,
+ )?))
+ }
+ RegisteredAlgorithm::Sha => AlgorithmImplementation::Sha(Sha),
+ RegisteredAlgorithm::CShake => AlgorithmImplementation::CShake(CShakeParams::from_value(vm, *algorithm)?),
+ };
// 9. Set the name attribute of normalizedAlgorithm to algName.
let normalized_algorithm = NormalizedAlgorithmAndParameter {
@@ -528,7 +555,9 @@ impl SubtleCrypto {
};
// 9. Let digest be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.
- let digest = algorithm_object.methods.digest(realm, &data_buffer);
+ let digest = algorithm_object
+ .methods
+ .digest(realm, &algorithm_object.parameter, &data_buffer);
if let Err(error) = digest {
throw_in_this_context(error);
@@ -2679,36 +2708,31 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"sign",
"RSASSA-PKCS1-v1_5",
- AlgorithmId::RsassaPkcs1,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsassaPkcs1, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"verify",
"RSASSA-PKCS1-v1_5",
- AlgorithmId::RsassaPkcs1,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsassaPkcs1, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"RSASSA-PKCS1-v1_5",
- AlgorithmId::RsassaPkcs1,
- ParameterId::RsaHashedKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsassaPkcs1, ParameterId::RsaHashedKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"RSASSA-PKCS1-v1_5",
- AlgorithmId::RsassaPkcs1,
- ParameterId::RsaHashedImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsassaPkcs1, ParameterId::RsaHashedImportParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"RSASSA-PKCS1-v1_5",
- AlgorithmId::RsassaPkcs1,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsassaPkcs1, ParameterId::AlgorithmParams),
);
// https://w3c.github.io/webcrypto/#rsa-pss-registration
@@ -2716,36 +2740,31 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"sign",
"RSA-PSS",
- AlgorithmId::RsaPss,
- ParameterId::RsaPssParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaPss, ParameterId::RsaPssParams),
);
define_an_algorithm(
&mut internal_object,
"verify",
"RSA-PSS",
- AlgorithmId::RsaPss,
- ParameterId::RsaPssParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaPss, ParameterId::RsaPssParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"RSA-PSS",
- AlgorithmId::RsaPss,
- ParameterId::RsaHashedKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaPss, ParameterId::RsaHashedKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"RSA-PSS",
- AlgorithmId::RsaPss,
- ParameterId::RsaHashedImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaPss, ParameterId::RsaHashedImportParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"RSA-PSS",
- AlgorithmId::RsaPss,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaPss, ParameterId::AlgorithmParams),
);
// https://w3c.github.io/webcrypto/#rsa-oaep-registration
@@ -2753,36 +2772,31 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"encrypt",
"RSA-OAEP",
- AlgorithmId::RsaOaep,
- ParameterId::RsaOaepParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaOaep, ParameterId::RsaOaepParams),
);
define_an_algorithm(
&mut internal_object,
"decrypt",
"RSA-OAEP",
- AlgorithmId::RsaOaep,
- ParameterId::RsaOaepParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaOaep, ParameterId::RsaOaepParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"RSA-OAEP",
- AlgorithmId::RsaOaep,
- ParameterId::RsaHashedKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaOaep, ParameterId::RsaHashedKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"RSA-OAEP",
- AlgorithmId::RsaOaep,
- ParameterId::RsaHashedImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaOaep, ParameterId::RsaHashedImportParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"RSA-OAEP",
- AlgorithmId::RsaOaep,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::RsaOaep, ParameterId::AlgorithmParams),
);
// https://w3c.github.io/webcrypto/#ecdsa-registration
@@ -2790,36 +2804,31 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"sign",
"ECDSA",
- AlgorithmId::Ecdsa,
- ParameterId::EcdsaParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdsa, ParameterId::EcdsaParams),
);
define_an_algorithm(
&mut internal_object,
"verify",
"ECDSA",
- AlgorithmId::Ecdsa,
- ParameterId::EcdsaParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdsa, ParameterId::EcdsaParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"ECDSA",
- AlgorithmId::Ecdsa,
- ParameterId::EcKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdsa, ParameterId::EcKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"ECDSA",
- AlgorithmId::Ecdsa,
- ParameterId::EcKeyImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdsa, ParameterId::EcKeyImportParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"ECDSA",
- AlgorithmId::Ecdsa,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdsa, ParameterId::AlgorithmParams),
);
// https://w3c.github.io/webcrypto/#ecdh-registration
@@ -2827,29 +2836,25 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"importKey",
"ECDH",
- AlgorithmId::Ecdh,
- ParameterId::EcKeyImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdh, ParameterId::EcKeyImportParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"ECDH",
- AlgorithmId::Ecdh,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdh, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"deriveBits",
"ECDH",
- AlgorithmId::Ecdh,
- ParameterId::EcdhKeyDeriveParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdh, ParameterId::EcdhKeyDeriveParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"ECDH",
- AlgorithmId::Ecdh,
- ParameterId::EcKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Ecdh, ParameterId::EcKeyGenParams),
);
// https://w3c.github.io/webcrypto/#aes-ctr-registration
@@ -2857,43 +2862,37 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"encrypt",
"AES-CTR",
- AlgorithmId::AesCtr,
- ParameterId::AesCtrParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCtr, ParameterId::AesCtrParams),
);
define_an_algorithm(
&mut internal_object,
"decrypt",
"AES-CTR",
- AlgorithmId::AesCtr,
- ParameterId::AesCtrParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCtr, ParameterId::AesCtrParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"AES-CTR",
- AlgorithmId::AesCtr,
- ParameterId::AesKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCtr, ParameterId::AesKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"AES-CTR",
- AlgorithmId::AesCtr,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCtr, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"AES-CTR",
- AlgorithmId::AesCtr,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCtr, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"AES-CTR",
- AlgorithmId::AesCtr,
- ParameterId::AesDerivedKeyParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCtr, ParameterId::AesDerivedKeyParams),
);
// https://w3c.github.io/webcrypto/#aes-cbc-registration
@@ -2901,43 +2900,37 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"encrypt",
"AES-CBC",
- AlgorithmId::AesCbc,
- ParameterId::AesCbcParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCbc, ParameterId::AesCbcParams),
);
define_an_algorithm(
&mut internal_object,
"decrypt",
"AES-CBC",
- AlgorithmId::AesCbc,
- ParameterId::AesCbcParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCbc, ParameterId::AesCbcParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"AES-CBC",
- AlgorithmId::AesCbc,
- ParameterId::AesKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCbc, ParameterId::AesKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"AES-CBC",
- AlgorithmId::AesCbc,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCbc, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"AES-CBC",
- AlgorithmId::AesCbc,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCbc, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"AES-CBC",
- AlgorithmId::AesCbc,
- ParameterId::AesDerivedKeyParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesCbc, ParameterId::AesDerivedKeyParams),
);
// https://w3c.github.io/webcrypto/#aes-gcm-registration
@@ -2945,43 +2938,37 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"encrypt",
"AES-GCM",
- AlgorithmId::AesGcm,
- ParameterId::AesGcmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesGcm, ParameterId::AesGcmParams),
);
define_an_algorithm(
&mut internal_object,
"decrypt",
"AES-GCM",
- AlgorithmId::AesGcm,
- ParameterId::AesGcmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesGcm, ParameterId::AesGcmParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"AES-GCM",
- AlgorithmId::AesGcm,
- ParameterId::AesKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesGcm, ParameterId::AesKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"AES-GCM",
- AlgorithmId::AesGcm,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesGcm, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"AES-GCM",
- AlgorithmId::AesGcm,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesGcm, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"AES-GCM",
- AlgorithmId::AesGcm,
- ParameterId::AesDerivedKeyParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesGcm, ParameterId::AesDerivedKeyParams),
);
// https://w3c.github.io/webcrypto/#aes-kw-registration
@@ -2989,43 +2976,37 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"wrapKey",
"AES-KW",
- AlgorithmId::AesKw,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesKw, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"unwrapKey",
"AES-KW",
- AlgorithmId::AesKw,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesKw, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"AES-KW",
- AlgorithmId::AesKw,
- ParameterId::AesKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesKw, ParameterId::AesKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"AES-KW",
- AlgorithmId::AesKw,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesKw, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"AES-KW",
- AlgorithmId::AesKw,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesKw, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"AES-KW",
- AlgorithmId::AesKw,
- ParameterId::AesDerivedKeyParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesKw, ParameterId::AesDerivedKeyParams),
);
// https://w3c.github.io/webcrypto/#hmac-registration
@@ -3033,135 +3014,72 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"sign",
"HMAC",
- AlgorithmId::Hmac,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"verify",
"HMAC",
- AlgorithmId::Hmac,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"HMAC",
- AlgorithmId::Hmac,
- ParameterId::HmacKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::HmacKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"HMAC",
- AlgorithmId::Hmac,
- ParameterId::HmacImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::HmacImportParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"HMAC",
- AlgorithmId::Hmac,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"HMAC",
- AlgorithmId::Hmac,
- ParameterId::HmacImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hmac, ParameterId::HmacImportParams),
);
// https://w3c.github.io/webcrypto/#sha-registration
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "SHA-1",
- AlgorithmId::Sha,
- ParameterId::AlgorithmParams,
- );
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "SHA-256",
- AlgorithmId::Sha,
- ParameterId::AlgorithmParams,
- );
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "SHA-384",
- AlgorithmId::Sha,
- ParameterId::AlgorithmParams,
- );
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "SHA-512",
- AlgorithmId::Sha,
- ParameterId::AlgorithmParams,
- );
+ define_an_algorithm(&mut internal_object, "digest", "SHA-1", RegisteredAlgorithm::Sha);
+ define_an_algorithm(&mut internal_object, "digest", "SHA-256", RegisteredAlgorithm::Sha);
+ define_an_algorithm(&mut internal_object, "digest", "SHA-384", RegisteredAlgorithm::Sha);
+ define_an_algorithm(&mut internal_object, "digest", "SHA-512", RegisteredAlgorithm::Sha);
// https://wicg.github.io/webcrypto-modern-algos/#sha3-registration
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "SHA3-256",
- AlgorithmId::Sha,
- ParameterId::AlgorithmParams,
- );
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "SHA3-384",
- AlgorithmId::Sha,
- ParameterId::AlgorithmParams,
- );
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "SHA3-512",
- AlgorithmId::Sha,
- ParameterId::AlgorithmParams,
- );
+ define_an_algorithm(&mut internal_object, "digest", "SHA3-256", RegisteredAlgorithm::Sha);
+ define_an_algorithm(&mut internal_object, "digest", "SHA3-384", RegisteredAlgorithm::Sha);
+ define_an_algorithm(&mut internal_object, "digest", "SHA3-512", RegisteredAlgorithm::Sha);
// https://wicg.github.io/webcrypto-modern-algos/#cshake-registration
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "cSHAKE128",
- AlgorithmId::CShake,
- ParameterId::CShakeParams,
- );
- define_an_algorithm(
- &mut internal_object,
- "digest",
- "cSHAKE256",
- AlgorithmId::CShake,
- ParameterId::CShakeParams,
- );
+ define_an_algorithm(&mut internal_object, "digest", "cSHAKE128", RegisteredAlgorithm::CShake);
+ define_an_algorithm(&mut internal_object, "digest", "cSHAKE256", RegisteredAlgorithm::CShake);
// https://w3c.github.io/webcrypto/#hkdf-registration
define_an_algorithm(
&mut internal_object,
"deriveBits",
"HKDF",
- AlgorithmId::Hkdf,
- ParameterId::HkdfParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hkdf, ParameterId::HkdfParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"HKDF",
- AlgorithmId::Hkdf,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hkdf, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"HKDF",
- AlgorithmId::Hkdf,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Hkdf, ParameterId::AlgorithmParams),
);
// https://w3c.github.io/webcrypto/#pbkdf2-registration
@@ -3169,22 +3087,19 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"deriveBits",
"PBKDF2",
- AlgorithmId::Pbkdf2,
- ParameterId::Pbkdf2Params,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Pbkdf2, ParameterId::Pbkdf2Params),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"PBKDF2",
- AlgorithmId::Pbkdf2,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Pbkdf2, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"PBKDF2",
- AlgorithmId::Pbkdf2,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Pbkdf2, ParameterId::AlgorithmParams),
);
// https://wicg.github.io/webcrypto-secure-curves/#x25519-registration
@@ -3192,29 +3107,25 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"deriveBits",
"X25519",
- AlgorithmId::X25519,
- ParameterId::EcdhKeyDeriveParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::X25519, ParameterId::EcdhKeyDeriveParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"X25519",
- AlgorithmId::X25519,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::X25519, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"X25519",
- AlgorithmId::X25519,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::X25519, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"X25519",
- AlgorithmId::X25519,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::X25519, ParameterId::AlgorithmParams),
);
// https://wicg.github.io/webcrypto-secure-curves/#x448-registration
@@ -3222,29 +3133,25 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"deriveBits",
"X448",
- AlgorithmId::X448,
- ParameterId::EcdhKeyDeriveParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::X448, ParameterId::EcdhKeyDeriveParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"X448",
- AlgorithmId::X448,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::X448, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"X448",
- AlgorithmId::X448,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::X448, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"X448",
- AlgorithmId::X448,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::X448, ParameterId::AlgorithmParams),
);
// https://wicg.github.io/webcrypto-secure-curves/#ed25519-registration
@@ -3252,36 +3159,31 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"sign",
"Ed25519",
- AlgorithmId::ED25519,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED25519, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"verify",
"Ed25519",
- AlgorithmId::ED25519,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED25519, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"Ed25519",
- AlgorithmId::ED25519,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED25519, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"Ed25519",
- AlgorithmId::ED25519,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED25519, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"Ed25519",
- AlgorithmId::ED25519,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED25519, ParameterId::AlgorithmParams),
);
// https://wicg.github.io/webcrypto-secure-curves/#ed448-registration
@@ -3289,36 +3191,31 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"sign",
"Ed448",
- AlgorithmId::ED448,
- ParameterId::Ed448Params,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED448, ParameterId::Ed448Params),
);
define_an_algorithm(
&mut internal_object,
"verify",
"Ed448",
- AlgorithmId::ED448,
- ParameterId::Ed448Params,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED448, ParameterId::Ed448Params),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"Ed448",
- AlgorithmId::ED448,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED448, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"Ed448",
- AlgorithmId::ED448,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED448, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"Ed448",
- AlgorithmId::ED448,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ED448, ParameterId::AlgorithmParams),
);
// https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-registration
@@ -3327,36 +3224,31 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"sign",
name,
- AlgorithmId::MlDsa,
- ParameterId::ContextParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlDsa, ParameterId::ContextParams),
);
define_an_algorithm(
&mut internal_object,
"verify",
name,
- AlgorithmId::MlDsa,
- ParameterId::ContextParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlDsa, ParameterId::ContextParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
name,
- AlgorithmId::MlDsa,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlDsa, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
name,
- AlgorithmId::MlDsa,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlDsa, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
name,
- AlgorithmId::MlDsa,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlDsa, ParameterId::AlgorithmParams),
);
}
@@ -3366,43 +3258,37 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"generateKey",
name,
- AlgorithmId::MlKem,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
name,
- AlgorithmId::MlKem,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
name,
- AlgorithmId::MlKem,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"encapsulate",
name,
- AlgorithmId::MlKem,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"decapsulate",
name,
- AlgorithmId::MlKem,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get shared key length",
name,
- AlgorithmId::MlKem,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
);
}
@@ -3412,22 +3298,19 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"importKey",
algorithm,
- AlgorithmId::Argon2,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Argon2, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"deriveBits",
algorithm,
- AlgorithmId::Argon2,
- ParameterId::Argon2Params,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Argon2, ParameterId::Argon2Params),
);
define_an_algorithm(
&mut internal_object,
"get key length",
algorithm,
- AlgorithmId::Argon2,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Argon2, ParameterId::AlgorithmParams),
);
}
@@ -3436,43 +3319,37 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"encrypt",
"ChaCha20-Poly1305",
- AlgorithmId::ChaCha20Poly1305,
- ParameterId::AeadParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ChaCha20Poly1305, ParameterId::AeadParams),
);
define_an_algorithm(
&mut internal_object,
"decrypt",
"ChaCha20-Poly1305",
- AlgorithmId::ChaCha20Poly1305,
- ParameterId::AeadParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ChaCha20Poly1305, ParameterId::AeadParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"ChaCha20-Poly1305",
- AlgorithmId::ChaCha20Poly1305,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ChaCha20Poly1305, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"ChaCha20-Poly1305",
- AlgorithmId::ChaCha20Poly1305,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ChaCha20Poly1305, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"ChaCha20-Poly1305",
- AlgorithmId::ChaCha20Poly1305,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ChaCha20Poly1305, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"ChaCha20-Poly1305",
- AlgorithmId::ChaCha20Poly1305,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::ChaCha20Poly1305, ParameterId::AlgorithmParams),
);
// https://wicg.github.io/webcrypto-modern-algos/#aes-ocb-registration
@@ -3480,43 +3357,37 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"encrypt",
"AES-OCB",
- AlgorithmId::AesOcb,
- ParameterId::AeadParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesOcb, ParameterId::AeadParams),
);
define_an_algorithm(
&mut internal_object,
"decrypt",
"AES-OCB",
- AlgorithmId::AesOcb,
- ParameterId::AeadParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesOcb, ParameterId::AeadParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
"AES-OCB",
- AlgorithmId::AesOcb,
- ParameterId::AesKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesOcb, ParameterId::AesKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
"AES-OCB",
- AlgorithmId::AesOcb,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesOcb, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
"AES-OCB",
- AlgorithmId::AesOcb,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesOcb, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
"AES-OCB",
- AlgorithmId::AesOcb,
- ParameterId::AesDerivedKeyParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::AesOcb, ParameterId::AesDerivedKeyParams),
);
// https://wicg.github.io/webcrypto-modern-algos/#kmac-registration
@@ -3525,43 +3396,37 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
&mut internal_object,
"sign",
algorithm,
- AlgorithmId::Kmac,
- ParameterId::KmacParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacParams),
);
define_an_algorithm(
&mut internal_object,
"verify",
algorithm,
- AlgorithmId::Kmac,
- ParameterId::KmacParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacParams),
);
define_an_algorithm(
&mut internal_object,
"generateKey",
algorithm,
- AlgorithmId::Kmac,
- ParameterId::KmacKeyGenParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacKeyGenParams),
);
define_an_algorithm(
&mut internal_object,
"importKey",
algorithm,
- AlgorithmId::Kmac,
- ParameterId::KmacImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacImportParams),
);
define_an_algorithm(
&mut internal_object,
"exportKey",
algorithm,
- AlgorithmId::Kmac,
- ParameterId::AlgorithmParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::AlgorithmParams),
);
define_an_algorithm(
&mut internal_object,
"get key length",
algorithm,
- AlgorithmId::Kmac,
- ParameterId::KmacImportParams,
+ RegisteredAlgorithm::Cpp(AlgorithmId::Kmac, ParameterId::KmacImportParams),
);
}
@@ -3575,21 +3440,14 @@ fn define_an_algorithm(
internal_object: &mut SupportedAlgorithmsMap,
op: &'static str,
algorithm: &'static str,
- method_id: AlgorithmId,
- parameter_id: ParameterId,
+ registered_algorithm: RegisteredAlgorithm,
) {
// 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.
// NOTE: There should always be a container at the op key.
let registered_algorithms = internal_object.get_mut(op).expect("the operation has a container");
// 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.
- registered_algorithms.insert(
- algorithm,
- RegisteredAlgorithm {
- method_id,
- parameter_id,
- },
- );
+ registered_algorithms.insert(algorithm, registered_algorithm);
}
fn create_algorithm_dictionary(vm: &Vm, realm: Gc<Realm>, name: &Utf16String) -> WebIdlResult<Gc<Object>> {
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
index d384ad5df35..f44283b1856 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
@@ -847,29 +847,6 @@ JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> Argon2Params::from_value(J
return adopt_own<AlgorithmParams>(*new Argon2Params { nonce, parallelism, memory, passes, maybe_version, secret_value, associated_data });
}
-CShakeParams::~CShakeParams() = default;
-
-JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> CShakeParams::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("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));
-
- auto const function_name = TRY(get_optional_buffer_source(vm, object, "functionName"_utf16_fly_string));
-
- auto const customization = TRY(get_optional_buffer_source(vm, object, "customization"_utf16_fly_string));
-
- return adopt_own<AlgorithmParams>(*new CShakeParams { length, function_name, customization });
-}
-
KmacParams::~KmacParams() = default;
// https://wicg.github.io/webcrypto-modern-algos/#kmac-params
@@ -4063,39 +4040,28 @@ WebIDL::ExceptionOr<GC::Ref<CryptoKey>> HKDF::import_key(JS::Realm&, AlgorithmPa
return key;
}
-// https://w3c.github.io/webcrypto/#sha-operations-digest
-WebIDL::ExceptionOr<ByteBuffer> SHA::digest(JS::Realm&, AlgorithmParams const& algorithm, ByteBuffer const& data)
-{
- auto& algorithm_name = algorithm.name;
+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);
+static_assert(to_underlying(::Crypto::Hash::HashKind::SHA512) == 7);
+static_assert(to_underlying(::Crypto::Hash::HashKind::SHA3_256) == 8);
+static_assert(to_underlying(::Crypto::Hash::HashKind::SHA3_384) == 9);
+static_assert(to_underlying(::Crypto::Hash::HashKind::SHA3_512) == 10);
- ::Crypto::Hash::HashKind hash_kind;
- if (algorithm_name == "SHA-1"sv) {
- hash_kind = ::Crypto::Hash::HashKind::SHA1;
- } else if (algorithm_name == "SHA-256"sv) {
- hash_kind = ::Crypto::Hash::HashKind::SHA256;
- } else if (algorithm_name == "SHA-384"sv) {
- hash_kind = ::Crypto::Hash::HashKind::SHA384;
- } else if (algorithm_name == "SHA-512"sv) {
- hash_kind = ::Crypto::Hash::HashKind::SHA512;
- } else if (algorithm_name == "SHA3-256"sv) {
- hash_kind = ::Crypto::Hash::HashKind::SHA3_256;
- } else if (algorithm_name == "SHA3-384"sv) {
- hash_kind = ::Crypto::Hash::HashKind::SHA3_384;
- } else if (algorithm_name == "SHA3-512"sv) {
- hash_kind = ::Crypto::Hash::HashKind::SHA3_512;
- } else {
- return WebIDL::NotSupportedError::create(Utf16String::formatted("Invalid hash function '{}'", algorithm_name));
- }
+extern "C" bool web_crypto_sha_digest(::Crypto::Hash::HashKind, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool web_crypto_sha_digest(::Crypto::Hash::HashKind hash_kind, ReadonlyBytes data, void* state, ReceiveEncodedBytes receive)
+{
::Crypto::Hash::Manager hash { hash_kind };
hash.update(data);
auto digest = hash.digest();
auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
if (result_buffer.is_error())
- return WebIDL::OperationError::create("Failed to create result buffer"_utf16);
+ return false;
- return result_buffer.release_value();
+ receive(state, result_buffer.value());
+ return true;
}
// https://w3c.github.io/webcrypto/#ecdsa-operations-generate-key
@@ -10026,62 +9992,34 @@ WebIDL::ExceptionOr<Optional<u32>> Argon2::get_key_length(JS::Realm&, AlgorithmP
return Optional<u32> {};
}
-// https://wicg.github.io/webcrypto-modern-algos/#cshake-operations-digest
-WebIDL::ExceptionOr<void> CShake::validate_digest_parameters(AlgorithmParams const& params) const
-{
- // NB: Step 5 throws an OperationError for the parameters that our cSHAKE does not support.
- auto const& normalized_algorithm = static_cast<CShakeParams const&>(params);
- auto result = ::Crypto::Hash::SHAKE::validate_parameters(
- normalized_algorithm.output_length,
- normalized_algorithm.customization.map([](auto const& value) { return value.span(); }),
- normalized_algorithm.function_name.map([](auto const& value) { return value.span(); }));
- if (result.is_error())
- return WebIDL::OperationError::create(Utf16String::formatted("Hash function failed: {}", result.error()));
-
- return {};
-}
+struct OptionalBytes {
+ bool has_value;
+ ReadonlyBytes bytes;
-// https://wicg.github.io/webcrypto-modern-algos/#cshake-operations-digest
-WebIDL::ExceptionOr<ByteBuffer> CShake::digest(JS::Realm&, AlgorithmParams const& params, ByteBuffer const& data)
-{
- auto const& normalized_algorithm = static_cast<CShakeParams const&>(params);
-
- // 1. Let outputLength be the outputLength member of normalizedAlgorithm.
- auto const& output_length = normalized_algorithm.output_length;
+ Optional<ReadonlyBytes> to_optional() const { return has_value ? Optional<ReadonlyBytes> { bytes } : Optional<ReadonlyBytes> {}; }
+};
- // 2. Let functionName be the functionName member of normalizedAlgorithm if present or the empty octet string otherwise.
- auto const& function_name = normalized_algorithm.function_name;
+static_assert(to_underlying(::Crypto::Hash::SHAKEKind::CSHAKE128) == 0);
+static_assert(to_underlying(::Crypto::Hash::SHAKEKind::CSHAKE256) == 1);
- // 3. Let customization be the customization member of normalizedAlgorithm if present or the empty octet string otherwise.
- auto const& customization = normalized_algorithm.customization;
+extern "C" FlatPtr web_crypto_cshake_validate_parameters(u32, OptionalBytes, OptionalBytes);
+extern "C" FlatPtr web_crypto_cshake_digest(::Crypto::Hash::SHAKEKind, ReadonlyBytes, u32, OptionalBytes, OptionalBytes, void*, ReceiveEncodedBytes);
- auto const algorithm = [&]() {
- // 4. If the name member of normalizedAlgorithm is a case-sensitive string match for "cSHAKE128":
- if (normalized_algorithm.name == "cSHAKE128"sv)
- return ::Crypto::Hash::SHAKE(::Crypto::Hash::SHAKEKind::CSHAKE128);
- // 4. If the name member of normalizedAlgorithm is a case-sensitive string match for "cSHAKE256":
- if (normalized_algorithm.name == "cSHAKE256"sv)
- return ::Crypto::Hash::SHAKE(::Crypto::Hash::SHAKEKind::CSHAKE256);
- VERIFY_NOT_REACHED();
- }();
-
- // 4. Let result be the result of performing the cSHAKE128/cSHAKE256 function defined in Section 3 of [NIST-SP800-185]
- // using message as the X input parameter,
- // outputLength as the L input parameter,
- // functionName as the N input parameter,
- // and customization as the S input parameter.
- auto maybe_result = algorithm.digest(
- data,
- output_length,
- customization.map([](auto const& value) { return value.span(); }),
- function_name.map([](auto const& value) { return value.span(); }));
+FlatPtr web_crypto_cshake_validate_parameters(u32 output_length, OptionalBytes customization, OptionalBytes function_name)
+{
+ auto result = ::Crypto::Hash::SHAKE::validate_parameters(output_length, customization.to_optional(), function_name.to_optional());
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ return 0;
+}
- // 5. If performing the operation results in an error, then throw an OperationError.
+FlatPtr web_crypto_cshake_digest(::Crypto::Hash::SHAKEKind kind, ReadonlyBytes data, u32 output_length, OptionalBytes customization, OptionalBytes function_name, void* state, ReceiveEncodedBytes receive)
+{
+ auto maybe_result = ::Crypto::Hash::SHAKE(kind).digest(data, output_length, customization.to_optional(), function_name.to_optional());
if (maybe_result.is_error())
- return WebIDL::OperationError::create(Utf16String::formatted("Hash function failed: {}", maybe_result.error()));
-
- // 6. Return result.
- return maybe_result.release_value();
+ return Utf16String::formatted("{}", maybe_result.error()).into_raw();
+ receive(state, maybe_result.value());
+ return 0;
}
AeadParams::~AeadParams() = default;
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
index fc3aa51ff6e..fce75b8a1c5 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
@@ -317,11 +317,6 @@ public:
return WebIDL::NotSupportedError::create("verify is not supported"_utf16);
}
- virtual WebIDL::ExceptionOr<ByteBuffer> digest(JS::Realm&, AlgorithmParams const&, ByteBuffer const&)
- {
- return WebIDL::NotSupportedError::create("digest is not supported"_utf16);
- }
-
virtual WebIDL::ExceptionOr<ByteBuffer> derive_bits(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, Optional<u32>)
{
return WebIDL::NotSupportedError::create("deriveBits is not supported"_utf16);
@@ -376,7 +371,6 @@ public:
virtual WebIDL::ExceptionOr<void> validate_decrypt_parameters(AlgorithmParams const&) const { return {}; }
virtual WebIDL::ExceptionOr<void> validate_sign_parameters(AlgorithmParams const&) const { return {}; }
virtual WebIDL::ExceptionOr<void> validate_verify_parameters(AlgorithmParams const&) const { return {}; }
- virtual WebIDL::ExceptionOr<void> validate_digest_parameters(AlgorithmParams const&) const { return {}; }
virtual WebIDL::ExceptionOr<void> validate_generate_key_parameters(AlgorithmParams const&) const { return {}; }
virtual WebIDL::ExceptionOr<void> validate_import_key_parameters(AlgorithmParams const&) const { return {}; }
virtual WebIDL::ExceptionOr<void> validate_derive_bits_parameters(AlgorithmParams const&, Optional<u32>) const { return {}; }
@@ -548,16 +542,6 @@ private:
PBKDF2() = default;
};
-class SHA : public AlgorithmMethods {
-public:
- virtual WebIDL::ExceptionOr<ByteBuffer> digest(JS::Realm& realm, AlgorithmParams const&, ByteBuffer const&) override;
-
- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new SHA); }
-
-private:
- SHA() = default;
-};
-
class ECDSA : public AlgorithmMethods {
public:
virtual WebIDL::ExceptionOr<ByteBuffer> sign(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&) override;
@@ -729,18 +713,6 @@ private:
Argon2() = default;
};
-class CShake : public AlgorithmMethods {
-public:
- virtual WebIDL::ExceptionOr<ByteBuffer> digest(JS::Realm& realm, AlgorithmParams const&, ByteBuffer const&) override;
-
- virtual WebIDL::ExceptionOr<void> validate_digest_parameters(AlgorithmParams const&) const override;
-
- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new CShake); }
-
-private:
- CShake() = default;
-};
-
struct EcdhKeyDeriveParams : public AlgorithmParams {
virtual ~EcdhKeyDeriveParams() override;
@@ -811,24 +783,6 @@ struct Argon2Params : public AlgorithmParams {
};
// https://wicg.github.io/webcrypto-modern-algos/#cshake-params
-struct CShakeParams : public AlgorithmParams {
- virtual ~CShakeParams() override;
-
- CShakeParams(u32 output_length, Optional<ByteBuffer> function_name, Optional<ByteBuffer> customization)
- : output_length(output_length)
- , function_name(move(function_name))
- , customization(move(customization))
-
- {
- }
-
- u32 output_length;
- Optional<ByteBuffer> function_name;
- Optional<ByteBuffer> customization;
-
- static JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> from_value(JS::Realm&, JS::Value);
-};
-
// https://wicg.github.io/webcrypto-modern-algos/#kmac-params
struct KmacParams : public AlgorithmParams {
virtual ~KmacParams() override;
diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
index d9b219cfd87..ca01f978c45 100644
--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
@@ -26,8 +26,6 @@ enum class AlgorithmId : u8 {
AesGcm,
AesKw,
HMAC,
- SHA,
- CShake,
HKDF,
PBKDF2,
X25519,
@@ -59,7 +57,6 @@ enum class ParameterId : u8 {
AesGcmParams,
HmacKeyGenParams,
HmacImportParams,
- CShakeParams,
HKDFParams,
PBKDF2Params,
Ed448Params,
@@ -127,7 +124,6 @@ JSCompletion web_crypto_algorithm_encrypt(JS::Realm* realm_pointer, NormalizedAl
JSCompletion web_crypto_algorithm_decrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);
JSCompletion web_crypto_algorithm_sign(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);
JSCompletion web_crypto_algorithm_verify(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes signature, ReadonlyBytes data, bool* out);
-JSCompletion web_crypto_algorithm_digest(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, ReadonlyBytes data, void* state, ReceiveBytes receive);
JSCompletion web_crypto_algorithm_derive_bits(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, OptionalLength length, void* state, ReceiveBytes receive);
JSCompletion web_crypto_algorithm_import_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, ReadonlyBytes key_data, RawJsonWebKey const* jwk, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out);
JSCompletion web_crypto_algorithm_generate_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out_key, CryptoKey** out_public_key, CryptoKey** out_private_key);
@@ -142,7 +138,6 @@ JSCompletion web_crypto_algorithm_validate_encrypt_parameters(JS::Realm* realm_p
JSCompletion web_crypto_algorithm_validate_decrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);
JSCompletion web_crypto_algorithm_validate_sign_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);
JSCompletion web_crypto_algorithm_validate_verify_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);
-JSCompletion web_crypto_algorithm_validate_digest_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);
JSCompletion web_crypto_algorithm_validate_generate_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);
JSCompletion web_crypto_algorithm_validate_import_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);
JSCompletion web_crypto_algorithm_validate_derive_bits_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength length);
@@ -259,10 +254,6 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithm
return AesKw::create();
case AlgorithmId::HMAC:
return HMAC::create();
- case AlgorithmId::SHA:
- return SHA::create();
- case AlgorithmId::CShake:
- return CShake::create();
case AlgorithmId::HKDF:
return HKDF::create();
case AlgorithmId::PBKDF2:
@@ -325,8 +316,6 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, Algorithm
return HmacKeyGenParams::from_value(realm, object);
case ParameterId::HmacImportParams:
return HmacImportParams::from_value(realm, object);
- case ParameterId::CShakeParams:
- return CShakeParams::from_value(realm, object);
case ParameterId::HKDFParams:
return HKDFParams::from_value(realm, object);
case ParameterId::PBKDF2Params:
@@ -465,16 +454,6 @@ JSCompletion web_crypto_algorithm_verify(JS::Realm* realm_pointer, NormalizedAlg
return JS::HostABI::normal_completion_to_abi(0);
}
-JSCompletion web_crypto_algorithm_digest(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, ReadonlyBytes data, void* state, ReceiveBytes receive)
-{
- auto& realm = *realm_pointer;
- auto result = algorithm->methods->digest(realm, *algorithm->parameter, MUST(ByteBuffer::copy(data)));
- if (result.is_exception())
- return Bindings::completion_to_abi(realm, result.release_error());
- receive(state, result.value().span());
- return JS::HostABI::normal_completion_to_abi(0);
-}
-
JSCompletion web_crypto_algorithm_derive_bits(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, OptionalLength length, void* state, ReceiveBytes receive)
{
auto& realm = *realm_pointer;
@@ -626,15 +605,6 @@ JSCompletion web_crypto_algorithm_validate_verify_parameters(JS::Realm* realm_po
return JS::HostABI::normal_completion_to_abi(0);
}
-JSCompletion web_crypto_algorithm_validate_digest_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)
-{
- auto& realm = *realm_pointer;
- auto result = algorithm->methods->validate_digest_parameters(*algorithm->parameter);
- if (result.is_exception())
- return Bindings::completion_to_abi(realm, result.release_error());
- return JS::HostABI::normal_completion_to_abi(0);
-}
-
JSCompletion web_crypto_algorithm_validate_generate_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)
{
auto& realm = *realm_pointer;
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index f5e642b2707..900e727d7a1 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,
- 354,
+ 343,
"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",