Skip to content

Truly independent web browser

LibWeb: Port WebCrypto ML-KEM to Rust

Shannon Boothb786e838c329
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index 23d4ab9e881..ea9f2a74a79 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -325,12 +325,14 @@ pub unsafe extern "C" fn web_rust_crypto_parse_an_asn1_structure(
#[derive(Clone, Copy)]
#[repr(u8)]
+#[allow(dead_code, reason = "the temporary native algorithm bridge is removed separately")]
pub(crate) enum AlgorithmId {
MlKem = 1,
}
#[derive(Clone, Copy)]
#[repr(u8)]
+#[allow(dead_code, reason = "the temporary native algorithm bridge is removed separately")]
pub(crate) enum ParameterId {
AlgorithmParams,
}
@@ -713,14 +715,25 @@ pub(crate) trait AlgorithmMethods: Trace {
))
}
- fn encapsulate(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>) -> WebIdlResult<EncapsulatedBitsData> {
+ fn encapsulate(
+ &self,
+ _realm: Gc<Realm>,
+ _params: &AlgorithmParams,
+ _key: Ref<CryptoKey>,
+ ) -> WebIdlResult<EncapsulatedBitsData> {
Err(Exception::Dom(
"NotSupportedError",
Utf16String::from_utf8("encapsulate is not supported"),
))
}
- fn decapsulate(&self, _realm: Gc<Realm>, _key: Ref<CryptoKey>, _data: &Bytes) -> WebIdlResult<Bytes> {
+ fn decapsulate(
+ &self,
+ _realm: Gc<Realm>,
+ _params: &AlgorithmParams,
+ _key: Ref<CryptoKey>,
+ _data: &Bytes,
+ ) -> WebIdlResult<Bytes> {
Err(Exception::Dom(
"NotSupportedError",
Utf16String::from_utf8("decalpsulate is not supported"),
@@ -1029,7 +1042,12 @@ impl AlgorithmMethods for CppAlgorithm {
Ok(out.expect("LibWeb returns bytes"))
}
- fn encapsulate(&self, realm: Gc<Realm>, key: Ref<CryptoKey>) -> WebIdlResult<EncapsulatedBitsData> {
+ fn encapsulate(
+ &self,
+ realm: Gc<Realm>,
+ _params: &AlgorithmParams,
+ 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 {
@@ -1046,7 +1064,13 @@ impl AlgorithmMethods for CppAlgorithm {
Ok(EncapsulatedBitsData { shared_key, ciphertext })
}
- fn decapsulate(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {
+ fn decapsulate(
+ &self,
+ realm: Gc<Realm>,
+ _params: &AlgorithmParams,
+ key: Ref<CryptoKey>,
+ data: &Bytes,
+ ) -> WebIdlResult<Bytes> {
let mut out: Option<Bytes> = None;
// SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.
unsafe {
@@ -14990,6 +15014,729 @@ impl AlgorithmMethods for MlDsa {
}
}
+#[derive(Clone, Copy)]
+#[repr(i32)]
+enum MlKemSize {
+ MlKem512,
+ MlKem768,
+ MlKem1024,
+}
+
+const ML_KEM_512_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 1];
+const ML_KEM_768_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 2];
+const ML_KEM_1024_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 3];
+
+unsafe extern "C" {
+ fn web_crypto_mlkem_generate_key_pair(
+ size: MlKemSize,
+ seed: Span<'_, u8>,
+ public_key: &mut *mut c_void,
+ private_key: &mut *mut c_void,
+ ) -> usize;
+ fn web_crypto_mlkem_key_info_read_private_key(key_info: *const c_void) -> *mut c_void;
+ fn web_crypto_mlkem_read_public_key(bytes: Span<'_, u8>) -> *mut c_void;
+ fn web_crypto_mlkem_public_bytes(key: *const c_void, state: *mut c_void, receive: ReceiveBytes);
+ fn web_crypto_mlkem_seed_bytes(key: *const c_void, bytes: &mut Span<'_, u8>);
+ fn web_crypto_mlkem_export_der(
+ key: *const c_void,
+ is_public: bool,
+ oid: Span<'_, u32>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ fn web_crypto_mlkem_encapsulate(
+ size: MlKemSize,
+ key: *const c_void,
+ shared_key: *mut c_void,
+ ciphertext: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+ fn web_crypto_mlkem_decapsulate(
+ size: MlKemSize,
+ key: *const c_void,
+ ciphertext: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+}
+
+impl Asn1KeyInfo {
+ fn mlkem_private_key(&self) -> UninstalledKey {
+ assert!(matches!(self.structure, Asn1Structure::PrivateKeyInfo));
+ // SAFETY: This object owns a live PrivateKeyInfo.
+ let key = unsafe { web_crypto_mlkem_key_info_read_private_key(self.key_info.as_ptr()) };
+ UninstalledKey(NonNull::new(key).expect("LibCrypto returns an ML-KEM private key"))
+ }
+}
+
+fn mlkem_read_public_key(vm: &Vm, bytes: &[u8]) -> Ref<CryptoKey> {
+ // SAFETY: The input bytes are lent for the call.
+ let key = unsafe { web_crypto_mlkem_read_public_key(Span::new(bytes)) };
+ // SAFETY: The service transfers ownership of the live key.
+ unsafe { CryptoKey::create_with_handle(vm, NonNull::new(key).expect("LibCrypto returns an ML-KEM public key")) }
+}
+
+fn mlkem_generate_key_pair(size: MlKemSize, seed: &[u8]) -> Result<NativeKeyPair, Utf16String> {
+ let mut public_key = null_mut();
+ let mut private_key = null_mut();
+ // SAFETY: The seed and output slots are lent for the call.
+ let error = unsafe { web_crypto_mlkem_generate_key_pair(size, Span::new(seed), &mut public_key, &mut private_key) };
+ if error != 0 {
+ // SAFETY: LibCrypto transfers ownership of the error message.
+ return Err(unsafe { Utf16String::from_raw_owned(error) });
+ }
+ Ok(NativeKeyPair {
+ public_key: UninstalledKey(NonNull::new(public_key).expect("LibCrypto returns a public key")),
+ private_key: UninstalledKey(NonNull::new(private_key).expect("LibCrypto returns a private key")),
+ })
+}
+
+fn mlkem_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, oid: &[u32]) -> WebIdlResult<Bytes> {
+ let mut result: Option<Bytes> = None;
+ // SAFETY: The key handle, OID and output slot are lent for the call.
+ if !unsafe {
+ web_crypto_mlkem_export_der(
+ key.handle().as_ptr(),
+ is_public,
+ Span::new(oid),
+ core::ptr::from_mut(&mut result).cast(),
+ receive_bytes,
+ )
+ } {
+ return Err(out_of_memory(vm));
+ }
+ Ok(result.expect("LibCrypto returns the DER bytes"))
+}
+
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct MlKem;
+
+impl AlgorithmMethods for MlKem {
+ // https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-generate-key
+ fn generate_key(
+ &self,
+ cx: &CallContext,
+ params: &AlgorithmParams,
+ extractable: bool,
+ usages: &[KeyUsage],
+ ) -> WebIdlResult<CryptoKeyOrCryptoKeyPair> {
+ // 1. If usages contains an entry which is not one of "encapsulateKey", "encapsulateBits", "decapsulateKey" or
+ // "decapsulateBits", then throw a SyntaxError.
+ for &usage in usages {
+ if usage != KeyUsage::EncapsulateKey
+ && usage != KeyUsage::EncapsulateBits
+ && usage != KeyUsage::DecapsulateKey
+ && usage != KeyUsage::DecapsulateBits
+ {
+ return Err(dom_error("SyntaxError", b"Invalid key usage"));
+ }
+ }
+
+ // 2. Generate an ML-KEM key pair, as described in Section 7.1 of [FIPS-203], with the parameter set indicated
+ // by the name member of normalizedAlgorithm.
+ let size = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
+ MlKemSize::MlKem512
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
+ MlKemSize::MlKem768
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
+ MlKemSize::MlKem1024
+ } else {
+ unreachable!("the name identifies an ML-KEM parameter set")
+ };
+ let maybe_key_pair = mlkem_generate_key_pair(size, &[]);
+
+ // 3. If the key generation step fails, then throw an OperationError.
+ let key_pair = maybe_key_pair.map_err(|error| {
+ Exception::Dom(
+ "OperationError",
+ libjs_rust::api::utf16_formatted("Key generation failed: {}", &[&error]),
+ )
+ })?;
+
+ // 6. Let publicKey be a new CryptoKey representing the encapsulation key of the generated key pair.
+ let public_key = key_pair.public_key.install(cx.vm());
+
+ // 7. Set the [[type]] internal slot of publicKey to "public".
+ public_key.set_type(KeyType::Public);
+
+ // 4. Let algorithm be a new KeyAlgorithm object.
+ // 5. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
+ // 8. Set the [[algorithm]] internal slot of publicKey to algorithm.
+ public_key.set_algorithm(InternalAlgorithmData::Key {
+ name: params.name.clone(),
+ });
+
+ // 9. Set the [[extractable]] internal slot of publicKey to true.
+ public_key.set_extractable(true);
+
+ // 10. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encapsulateKey",
+ // "encapsulateBits" ].
+ public_key.set_usages(usage_intersection(
+ usages,
+ &[KeyUsage::EncapsulateKey, KeyUsage::EncapsulateBits],
+ ));
+
+ // 11. Let privateKey be a new CryptoKey representing the decapsulation key of the generated key pair.
+ let private_key = key_pair.private_key.install(cx.vm());
+
+ // 12. Set the [[type]] internal slot of privateKey to "private".
+ private_key.set_type(KeyType::Private);
+
+ // 13. Set the [[algorithm]] internal slot of privateKey to algorithm.
+ private_key.set_algorithm(InternalAlgorithmData::Key {
+ name: params.name.clone(),
+ });
+
+ // 14. Set the [[extractable]] internal slot of privateKey to extractable.
+ private_key.set_extractable(extractable);
+
+ // 15. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decapsulateKey",
+ // "decapsulateBits" ].
+ private_key.set_usages(usage_intersection(
+ usages,
+ &[KeyUsage::DecapsulateKey, KeyUsage::DecapsulateBits],
+ ));
+
+ // 16. Let result be a new CryptoKeyPair dictionary.
+ // 17. Set the publicKey attribute of result to be publicKey.
+ // 18. Set the privateKey attribute of result to be privateKey.
+ let result = CryptoKeyPair {
+ public_key: Some(public_key),
+ private_key: Some(private_key),
+ };
+
+ // 19. Return result.
+ Ok(CryptoKeyOrCryptoKeyPair::CryptoKeyPair(result))
+ }
+
+ // https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-import-key
+ fn import_key(
+ &self,
+ cx: &CallContext,
+ params: &AlgorithmParams,
+ format: KeyFormat,
+ key_data: ImportKeyData,
+ _: bool,
+ usages: &[KeyUsage],
+ ) -> WebIdlResult<Ref<CryptoKey>> {
+ let key;
+
+ // 1. Let keyData be the key data to be imported.
+ // 2. -> If format is "spki":
+ if format == KeyFormat::Spki {
+ // 1. If usages contains an entry which is not "encapsulateKey" or "encapsulateBits" then throw
+ // a SyntaxError.
+ for &usage in usages {
+ if usage != KeyUsage::EncapsulateKey && usage != KeyUsage::EncapsulateBits {
+ return Err(Exception::Dom(
+ "SyntaxError",
+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),
+ ));
+ }
+ }
+
+ // 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
+ // 3. If an error occurred while parsing, then throw a DataError.
+ let ImportKeyData::Bytes(key_data) = key_data else {
+ unreachable!("DER key data contains bytes")
+ };
+ let spki = Asn1KeyInfo::parse(&key_data, Asn1Structure::SubjectPublicKeyInfo)?;
+
+ // 4. If the name member of normalizedAlgorithm is "ML-KEM-512":
+ let expected_oid = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
+ // Let expectedOid be id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1).
+ ML_KEM_512_OID
+ }
+ // If the name member of normalizedAlgorithm is "ML-KEM-768":
+ else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
+ // Let expectedOid be id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2).
+ ML_KEM_768_OID
+ }
+ // If the name member of normalizedAlgorithm is "ML-KEM-1024":
+ else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
+ // Let expectedOid be id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3).
+ ML_KEM_1024_OID
+ }
+ // Otherwise:
+ else {
+ // throw a NotSupportedError.
+ return Err(dom_error("NotSupportedError", b"Invalid key format"));
+ };
+
+ // 5. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equal
+ // to expectedOid, then throw a DataError.
+ if spki.identifier() != expected_oid {
+ return Err(dom_error("DataError", b"Invalid algorithm"));
+ }
+
+ // 6. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError.
+ if spki.ec_parameters().is_some() {
+ return Err(dom_error("DataError", b"Invalid algorithm parameters"));
+ }
+
+ // 7. Let publicKey be the ML-KEM public key identified by the subjectPublicKey field of spki.
+ let public_key = spki.raw_key();
+
+ // 8. Let key be a new CryptoKey that represents publicKey.
+ key = mlkem_read_public_key(cx.vm(), public_key);
+
+ // 9. Set the [[type]] internal slot of key to "public"
+ key.set_type(KeyType::Public);
+
+ // 10. Let algorithm be a new KeyAlgorithm.
+ // 11. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
+ // 12. Set the [[algorithm]] internal slot of key to algorithm.
+ key.set_algorithm(InternalAlgorithmData::Key {
+ name: params.name.clone(),
+ });
+ }
+ // -> If format is "pkcs8":
+ else if format == KeyFormat::Pkcs8 {
+ // 1. If usages contains an entry which is not "decapsulateKey" or "decapsulateBits" then throw a SyntaxError.
+ for &usage in usages {
+ if usage != KeyUsage::DecapsulateKey && usage != KeyUsage::DecapsulateBits {
+ return Err(Exception::Dom(
+ "SyntaxError",
+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),
+ ));
+ }
+ }
+
+ // 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
+ // 3. If an error occurred while parsing, then throw a DataError.
+ let ImportKeyData::Bytes(key_data) = key_data else {
+ unreachable!("DER key data contains bytes")
+ };
+ let private_key_info = Asn1KeyInfo::parse(&key_data, Asn1Structure::PrivateKeyInfo)?;
+
+ // 4. => If the name member of normalizedAlgorithm is "ML-KEM-512":
+ // Let expectedOid be id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1).
+ // Let asn1Structure be the ASN.1 ML-KEM-512-PrivateKey structure.
+ // => If the name member of normalizedAlgorithm is "ML-KEM-768":
+ // Let expectedOid be id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2).
+ // Let asn1Structure be the ASN.1 ML-KEM-768-PrivateKey structure.
+ // => If the name member of normalizedAlgorithm is "ML-KEM-1024":
+ // Let expectedOid be id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3).
+ // Let asn1Structure be the ASN.1 ML-KEM-1024-PrivateKey structure.
+ // => Otherwise:
+ // throw a NotSupportedError.
+ let expected_oid = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
+ ML_KEM_512_OID
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
+ ML_KEM_768_OID
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
+ ML_KEM_1024_OID
+ } else {
+ return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
+ };
+
+ // 5. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of
+ // privateKeyInfo is not equal to expectedOid, then throw a DataError.
+ if private_key_info.identifier() != expected_oid {
+ return Err(dom_error("DataError", b"Invalid algorithm"));
+ }
+
+ // 6. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of
+ // privateKeyInfo is present, then throw a DataError.
+ if private_key_info.ec_parameters().is_some() {
+ return Err(dom_error("DataError", b"Invalid algorithm parameters"));
+ }
+
+ // 7. Let mlKemPrivateKey be the result of performing the parse an ASN.1 structure algorithm, with
+ // data as the privateKey field of privateKeyInfo, structure as asn1Structure, and exactData set to
+ // true.
+ // NOTE: We already did this in parse_a_private_key_info
+ // 8. If an error occurred while parsing, then throw a DataError.
+ let ml_kem_private_key = private_key_info.mlkem_private_key();
+
+ // 9. Let key be a new CryptoKey that represents the ML-KEM private key identified by
+ // mlKemPrivateKey.
+ key = ml_kem_private_key.install(cx.vm());
+
+ // 10. Set the [[type]] internal slot of key to "private"
+ key.set_type(KeyType::Private);
+
+ // 11. Let algorithm be a new KeyAlgorithm.
+ // 12. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
+ // 13. Set the [[algorithm]] internal slot of key to algorithm.
+ key.set_algorithm(InternalAlgorithmData::Key {
+ name: params.name.clone(),
+ });
+ }
+ // -> If format is "raw-public":
+ else if format == KeyFormat::RawPublic {
+ // 1. If usages contains an entry which is not "encapsulateKey" or "encapsulateBits" then throw a SyntaxError.
+ for &usage in usages {
+ if usage != KeyUsage::EncapsulateKey && usage != KeyUsage::EncapsulateBits {
+ return Err(Exception::Dom(
+ "SyntaxError",
+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),
+ ));
+ }
+ }
+
+ // 2. Let data be keyData.
+ let ImportKeyData::Bytes(data) = key_data else {
+ unreachable!("raw key data contains bytes")
+ };
+
+ // 3. Let key be a new CryptoKey that represents the ML-KEM public key data in data.
+ key = mlkem_read_public_key(cx.vm(), data.as_slice());
+
+ // 4. Set the [[type]] internal slot of key to "public"
+ key.set_type(KeyType::Public);
+
+ // 5. Let algorithm be a new KeyAlgorithm object.
+ // 6. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
+ // 6. Set the [[algorithm]] internal slot of key to algorithm.
+ key.set_algorithm(InternalAlgorithmData::Key {
+ name: params.name.clone(),
+ });
+ }
+ // -> If format is "raw-seed":
+ else if format == KeyFormat::RawSeed {
+ // 1. If usages contains an entry which is not "decapsulateKey" or "decapsulateBits" then throw a SyntaxError.
+ for &usage in usages {
+ if usage != KeyUsage::DecapsulateKey && usage != KeyUsage::DecapsulateBits {
+ return Err(Exception::Dom(
+ "SyntaxError",
+ libjs_rust::api::utf16_formatted("Invalid key usage '{}'", &[&key_usage_to_string(usage)]),
+ ));
+ }
+ }
+
+ // 2. Let data be keyData.
+ let ImportKeyData::Bytes(data) = key_data else {
+ unreachable!("raw key data contains bytes")
+ };
+
+ // 3. If the length in bits of data is not 512 then throw a DataError.
+ if data.as_slice().len() * 8 != 512 {
+ return Err(dom_error("DataError", b"Invalid key format"));
+ }
+
+ // 4. Let privateKey be the result of performing the ML-KEM.KeyGen_internal function described in
+ // Section 6.1 of [FIPS-203] with the parameter set indicated by the name member of
+ // normalizedAlgorithm, using the first 256 bits of data as d and the last 256 bits of data as z.
+ let size = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
+ MlKemSize::MlKem512
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
+ MlKemSize::MlKem768
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
+ MlKemSize::MlKem1024
+ } else {
+ unreachable!("the name identifies an ML-KEM parameter set")
+ };
+ let maybe_key_pair = mlkem_generate_key_pair(size, data.as_slice());
+ let key_pair = maybe_key_pair.map_err(|error| {
+ Exception::Dom(
+ "OperationError",
+ libjs_rust::api::utf16_formatted("Key generation failed: {}", &[&error]),
+ )
+ })?;
+
+ // 5. Let key be a new CryptoKey that represents the ML-KEM private key identified by privateKey.
+ key = key_pair.private_key.install(cx.vm());
+
+ // 6. Set the [[type]] internal slot of key to "private"
+ key.set_type(KeyType::Private);
+
+ // 7. Let algorithm be a new KeyAlgorithm.
+ // 8. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
+ // 9. Set the [[algorithm]] internal slot of key to algorithm.
+ key.set_algorithm(InternalAlgorithmData::Key {
+ name: params.name.clone(),
+ });
+ }
+ // FIXME: -> If format is "jwk":
+ // -> Otherwise:
+ else {
+ // throw a NotSupportedError.
+ return Err(dom_error("NotSupportedError", b"Invalid key format"));
+ }
+
+ // 3. Return key.
+ Ok(key)
+ }
+
+ // https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-export-key
+ fn export_key(&self, cx: &CallContext, format: KeyFormat, key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {
+ let vm = cx.vm();
+
+ // 1. Let key be the CryptoKey to be exported.
+
+ // 2. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be
+ // accessed, then throw an OperationError.
+ // Note: In our impl this is always accessible
+ let handle = key.handle();
+
+ // 3. -> If format is "spki":
+ let result = if format == KeyFormat::Spki {
+ // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
+ if key.key_type() != KeyType::Public {
+ return Err(dom_error("InvalidAccessError", b"Key is not a public key"));
+ }
+
+ // 2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
+
+ // 3. Let data be an instance of the SubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:
+ // * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
+ // * -> If the name member of keyAlgorithm is "ML-KEM-512":
+ // Set the algorithm object identifier to the id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1) OID.
+ // -> If the name member of keyAlgorithm is "ML-KEM-768":
+ // Set the algorithm object identifier to the id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2) OID.
+ // -> If the name member of keyAlgorithm is "ML-KEM-1024":
+ // Set the algorithm object identifier to the id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3) OID.
+ // -> Otherwise:
+ // throw a NotSupportedError.
+ // * Set the subjectPublicKey field to keyData.
+ let algorithm_oid = if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
+ ML_KEM_512_OID
+ } else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
+ ML_KEM_768_OID
+ } else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
+ ML_KEM_1024_OID
+ } else {
+ return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
+ };
+
+ let data = mlkem_export_der(vm, key, true, &algorithm_oid)?;
+
+ // 4. Let result be the result of DER-encoding data.
+ ExportKeyResult::Bytes(data)
+ }
+ // -> If format is "pkcs8":
+ else if format == KeyFormat::Pkcs8 {
+ // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
+ if key.key_type() != KeyType::Private {
+ return Err(dom_error("InvalidAccessError", b"Key is not a private key"));
+ }
+
+ // 2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
+
+ // 3. Let data be an instance of the PrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:
+ // * Set the version field to 0.
+ // * Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:
+ // * => If the name member of keyAlgorithm is "ML-KEM-512":
+ // Set the algorithm object identifier to the id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1) OID.
+ // * => If the name member of keyAlgorithm is "ML-KEM-768":
+ // Set the algorithm object identifier to the id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2) OID.
+ // * => If the name member of keyAlgorithm is "ML-KEM-1024":
+ // Set the algorithm object identifier to the id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3) OID.
+ // * => Otherwise:
+ // throw a NotSupportedError.
+ // * Set the privateKey field as follows:
+ // * => If the name member of keyAlgorithm is "ML-KEM-512":
+ // Set the privateKey field to the result of DER-encoding a ML-KEM-512-PrivateKey
+ // ASN.1 type that represents the ML-KEM private key seed represented by the
+ // [[handle]] internal slot of key using the seed-only format (using a context-
+ // specific [0] primitive tag with an implicit encoding of OCTET STRING).
+ // * => If the name member of keyAlgorithm is "ML-KEM-768":
+ // Set the privateKey field to the result of DER-encoding a ML-KEM-65-PrivateKey
+ // ASN.1 type that represents the ML-KEM private key seed represented by the
+ // [[handle]] internal slot of key using the seed-only format (using a context-
+ // specific [0] primitive tag with an implicit encoding of OCTET STRING).
+ // * => If the name member of keyAlgorithm is "ML-KEM-1024":
+ // Set the privateKey field to the result of DER-encoding a ML-KEM-1024-PrivateKey
+ // ASN.1 type that represents the ML-KEM private key seed represented by the
+ // [[handle]] internal slot of key using the seed-only format (using a context-
+ // specific [0] primitive tag with an implicit encoding of OCTET STRING).
+ // * => Otherwise:
+ // throw a NotSupportedError.
+ let algorithm_oid = if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
+ ML_KEM_512_OID
+ } else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
+ ML_KEM_768_OID
+ } else if matches!(key.algorithm_name().as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
+ ML_KEM_1024_OID
+ } else {
+ return Err(dom_error("NotSupportedError", b"Invalid algorithm"));
+ };
+
+ let data = mlkem_export_der(vm, key, false, &algorithm_oid)?;
+
+ // 4. Let result be the result of DER-encoding data.
+ ExportKeyResult::Bytes(data)
+ }
+ // -> If format is "raw-public":
+ else if format == KeyFormat::RawPublic {
+ // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
+ if key.key_type() != KeyType::Public {
+ return Err(dom_error("InvalidAccessError", b"Key is not a public key"));
+ }
+
+ // 2. Let data be a byte sequence containing the raw octets of the key represented by the [[handle]] internal slot of key.
+ let mut data: Option<Bytes> = None;
+ // SAFETY: The handle and output slot are lent for the call.
+ unsafe {
+ web_crypto_mlkem_public_bytes(handle.as_ptr(), core::ptr::from_mut(&mut data).cast(), receive_bytes);
+ };
+ let data = data.expect("LibCrypto returns the public key bytes");
+
+ // 3. Let result be data.
+ ExportKeyResult::Bytes(data)
+ }
+ // -> If format is "raw-seed":
+ else if format == KeyFormat::RawSeed {
+ // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
+ if key.key_type() != KeyType::Private {
+ return Err(dom_error("InvalidAccessError", b"Key is not a private key"));
+ }
+
+ // 2. Let data be a byte sequence containing the concatenation of the d and z seed variables of the
+ // key represented by the [[handle]] internal slot of key.
+ let mut seed = Span::new(&[]);
+ // SAFETY: The key owns the seed through the copy.
+ unsafe { web_crypto_mlkem_seed_bytes(handle.as_ptr(), &mut seed) };
+ let data = Bytes::new(copy_bytes(vm, seed.as_slice())?);
+
+ // 3. Let result be data.
+ ExportKeyResult::Bytes(data)
+ }
+ // FIXME: -> If format is "jwk":
+ // -> Otherwise:
+ else {
+ // throw a NotSupportedError.
+ return Err(dom_error("NotSupportedError", b"Invalid key format"));
+ };
+
+ // 4. Return result.
+ Ok(result)
+ }
+
+ fn public_key_usages(&self) -> Option<Vec<KeyUsage>> {
+ Some(vec![KeyUsage::EncapsulateKey, KeyUsage::EncapsulateBits])
+ }
+
+ // https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-encapsulate
+ fn encapsulate(
+ &self,
+ _: Gc<Realm>,
+ params: &AlgorithmParams,
+ key: Ref<CryptoKey>,
+ ) -> WebIdlResult<EncapsulatedBitsData> {
+ // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
+ if key.key_type() != KeyType::Public {
+ return Err(dom_error("InvalidAccessError", b"Invalid key type"));
+ }
+
+ // 2. Perform the encapsulation key check described in Section 7.2 of [FIPS-203] with the parameter set indicated
+ // by the name member of algorithm, using the key represented by the [[handle]] internal slot of key as the ek
+ // input parameter.
+ // 3. If the encapsulation key check failed, return an OperationError.
+ // NOTE: Presumably done by OpenSSL for us
+
+ // 4. Let sharedKey and ciphertext be the outputs that result from performing the ML-KEM.Encaps function
+ // described in Section 7.2 of [FIPS-203] with the parameter set indicated by the name member of algorithm,
+ // using the key represented by the [[handle]] internal slot of key as the ek input parameter.
+ let size = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
+ MlKemSize::MlKem512
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
+ MlKemSize::MlKem768
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
+ MlKemSize::MlKem1024
+ } else {
+ unreachable!("the name identifies an ML-KEM parameter set")
+ };
+ let mut shared_key: Option<Bytes> = None;
+ let mut ciphertext: Option<Bytes> = None;
+ // SAFETY: The handle and output slots are lent for the call.
+ let maybe_encapsulation = unsafe {
+ web_crypto_mlkem_encapsulate(
+ size,
+ key.handle().as_ptr(),
+ core::ptr::from_mut(&mut shared_key).cast(),
+ core::ptr::from_mut(&mut ciphertext).cast(),
+ receive_bytes,
+ )
+ };
+
+ // 5. If the ML-KEM.Encaps function returned an error, return an OperationError.
+ if maybe_encapsulation != 0 {
+ // SAFETY: LibCrypto transfers ownership of the error message.
+ let error = unsafe { Utf16String::from_raw_owned(maybe_encapsulation) };
+ return Err(Exception::Dom(
+ "OperationError",
+ libjs_rust::api::utf16_formatted("Key encapsulation failed: {}", &[&error]),
+ ));
+ }
+
+ // 6. Let result be a new EncapsulatedBits dictionary.
+ // 7. Set the sharedKey attribute of result to the result of creating an ArrayBuffer containing sharedKey.
+ // 8. Set the ciphertext attribute of result to the result of creating an ArrayBuffer containing ciphertext.
+ let result = EncapsulatedBitsData { shared_key, ciphertext };
+
+ // 9. Return result.
+ Ok(result)
+ }
+
+ // https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-decapsulate
+ fn decapsulate(
+ &self,
+ _: Gc<Realm>,
+ params: &AlgorithmParams,
+ key: Ref<CryptoKey>,
+ ciphertext: &Bytes,
+ ) -> WebIdlResult<Bytes> {
+ // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
+ if key.key_type() != KeyType::Private {
+ return Err(dom_error("InvalidAccessError", b"Invalid key type"));
+ }
+
+ // 2. Perform the decapsulation input check described in Section 7.3 of [FIPS-203] with the parameter set
+ // indicated by the name member of algorithm, using the key represented by the [[handle]] internal slot of key as
+ // the dk input parameter, and ciphertext as the c input parameter.
+ // 3. If the decapsulation key check failed, return an OperationError.
+ // NOTE: Presumably done by OpenSSL for us
+
+ // 4. Let sharedKey be the output that results from performing the ML-KEM.Decaps function described in Section
+ // 7.3 of [FIPS-203] with the parameter set indicated by the name member of algorithm, using the key
+ // represented by the [[handle]] internal slot of key as the dk input parameter, and ciphertext as the c input
+ // parameter.
+ let size = if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-512")) {
+ MlKemSize::MlKem512
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-768")) {
+ MlKemSize::MlKem768
+ } else if matches!(params.name.as_units(), Utf16StringUnits::Ascii(b"ML-KEM-1024")) {
+ MlKemSize::MlKem1024
+ } else {
+ unreachable!("the name identifies an ML-KEM parameter set")
+ };
+ let mut shared_key: Option<Bytes> = None;
+ // SAFETY: The handle, ciphertext and output slot are lent for the call.
+ let maybe_shared_key = unsafe {
+ web_crypto_mlkem_decapsulate(
+ size,
+ key.handle().as_ptr(),
+ Span::new(ciphertext.as_slice()),
+ core::ptr::from_mut(&mut shared_key).cast(),
+ receive_bytes,
+ )
+ };
+
+ if maybe_shared_key != 0 {
+ // SAFETY: LibCrypto transfers ownership of the error message.
+ let error = unsafe { Utf16String::from_raw_owned(maybe_shared_key) };
+ return Err(Exception::Dom(
+ "OperationError",
+ libjs_rust::api::utf16_formatted("Key decapsulation failed: {}", &[&error]),
+ ));
+ }
+
+ let shared_key = shared_key.expect("LibCrypto returns the shared key");
+
+ // 5. Return sharedKey.
+ Ok(shared_key)
+ }
+
+ // https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-get-shared-key-length
+ fn get_shared_key_length(&self, _: Gc<Realm>) -> WebIdlResult<u32> {
+ // 1. Return 256.
+ Ok(256)
+ }
+}
+
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 c7f4f6e1515..793f16dd9c4 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs
@@ -34,7 +34,7 @@ use crate::crypto::crypto_algorithms::{
AesCbc, AesCtr, AesGcm, AesKw, AesOcb, AesParameterType, AlgorithmId, AlgorithmMethods, AlgorithmParams, Argon2,
Argon2Params, Bytes, CShakeParams, ChaCha20Poly1305, CppAlgorithm, EcParameterType, Ecdh, Ecdsa, Ed448, Ed25519,
EncapsulatedKeyData, ExportKeyResult, Hkdf, HkdfParams, Hmac, HmacImportParams, HmacKeyGenParams, ImportKeyData,
- Kmac, KmacImportParams, KmacKeyGenParams, KmacParams, MlDsa, ParameterId, Pbkdf2, Pbkdf2Params, RsaOaep,
+ Kmac, KmacImportParams, KmacKeyGenParams, KmacParams, MlDsa, MlKem, ParameterId, Pbkdf2, Pbkdf2Params, RsaOaep,
RsaParameterType, RsaPss, RsassaPkcs1, Sha, X448, X25519, normalized_key_usages, public_key_for_private_key,
};
#[allow(
@@ -88,6 +88,7 @@ pub(crate) enum KeyFormat {
#[derive(Clone, Copy)]
enum RegisteredAlgorithm {
+ #[allow(dead_code, reason = "the temporary native algorithm bridge is removed separately")]
Cpp(AlgorithmId, ParameterId),
Sha,
Hmac,
@@ -118,6 +119,7 @@ enum RegisteredAlgorithm {
Ed25519,
Ed448(bool),
MlDsa(bool),
+ MlKem,
X25519(bool),
X448(bool),
CShake,
@@ -158,6 +160,7 @@ enum AlgorithmImplementation {
Ed25519(Ed25519),
Ed448(Ed448),
MlDsa(MlDsa),
+ MlKem(MlKem),
X25519(X25519),
X448(X448),
CShake(CShakeParams),
@@ -197,6 +200,7 @@ impl Deref for AlgorithmImplementation {
Self::Ed25519(algorithm) => algorithm,
Self::Ed448(algorithm) => algorithm,
Self::MlDsa(algorithm) => algorithm,
+ Self::MlKem(algorithm) => algorithm,
Self::X25519(algorithm) => algorithm,
Self::X448(algorithm) => algorithm,
Self::CShake(algorithm) => algorithm,
@@ -453,6 +457,7 @@ pub(crate) fn normalize_an_algorithm(
RegisteredAlgorithm::MlDsa(has_parameters) => {
AlgorithmImplementation::MlDsa(MlDsa::from_value(vm, *algorithm, has_parameters)?)
}
+ RegisteredAlgorithm::MlKem => AlgorithmImplementation::MlKem(MlKem),
RegisteredAlgorithm::X25519(has_parameters) => {
AlgorithmImplementation::X25519(X25519::from_value(vm, *algorithm, has_parameters)?)
}
@@ -2019,9 +2024,11 @@ impl SubtleCrypto {
// 12. Let encapsulatedBits be the result of performing the encapsulate operation specified by the [[algorithm]]
// internal slot of encapsulationKey using encapsulationKey.
- let maybe_encapsulated_bits = normalized_encapsulation_algorithm
- .methods
- .encapsulate(realm, encapsulation_key);
+ let maybe_encapsulated_bits = normalized_encapsulation_algorithm.methods.encapsulate(
+ realm,
+ &normalized_encapsulation_algorithm.parameter,
+ encapsulation_key,
+ );
if let Err(error) = maybe_encapsulated_bits {
throw_in_this_context(error);
return;
@@ -2157,9 +2164,11 @@ impl SubtleCrypto {
// 10. Let encapsulatedBits be the result of performing the encapsulate operation specified by the [[algorithm]]
// internal slot of encapsulationKey using encapsulationKey.
- let maybe_encapsulated_bits = normalized_encapsulation_algorithm
- .methods
- .encapsulate(realm, encapsulation_key);
+ let maybe_encapsulated_bits = normalized_encapsulation_algorithm.methods.encapsulate(
+ realm,
+ &normalized_encapsulation_algorithm.parameter,
+ encapsulation_key,
+ );
if let Err(error) = maybe_encapsulated_bits {
throw_in_this_context(error);
return;
@@ -2300,10 +2309,12 @@ impl SubtleCrypto {
}
// 13. Let decapsulatedBits be the result of performing the decapsulate operation specified by the [[algorithm]]
// internal slot of decapsulationKey using decapsulationKey and ciphertext.
- let maybe_decapsulated_bits =
- normalized_decapsulation_algorithm
- .methods
- .decapsulate(realm, decapsulation_key, &cipher_text);
+ let maybe_decapsulated_bits = normalized_decapsulation_algorithm.methods.decapsulate(
+ realm,
+ &normalized_decapsulation_algorithm.parameter,
+ decapsulation_key,
+ &cipher_text,
+ );
if let Err(error) = maybe_decapsulated_bits {
throw_in_this_context(error);
return;
@@ -2435,10 +2446,12 @@ impl SubtleCrypto {
// 11. Let decapsulatedBits be the result of performing the decapsulate operation specified by the [[algorithm]]
// internal slot of decapsulationKey using decapsulationKey and ciphertext.
- let maybe_decapsulated_bits =
- normalized_decapsulation_algorithm
- .methods
- .decapsulate(realm, decapsulation_key, &cipher_text);
+ let maybe_decapsulated_bits = normalized_decapsulation_algorithm.methods.decapsulate(
+ realm,
+ &normalized_decapsulation_algorithm.parameter,
+ decapsulation_key,
+ &cipher_text,
+ );
if let Err(error) = maybe_decapsulated_bits {
throw_in_this_context(error);
return;
@@ -3433,41 +3446,16 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {
// https://wicg.github.io/webcrypto-modern-algos/#ml-kem-registration
for name in ["ML-KEM-512", "ML-KEM-768", "ML-KEM-1024"] {
- define_an_algorithm(
- &mut internal_object,
- "generateKey",
- name,
- RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
- );
- define_an_algorithm(
- &mut internal_object,
- "importKey",
- name,
- RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
- );
- define_an_algorithm(
- &mut internal_object,
- "exportKey",
- name,
- RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
- );
- define_an_algorithm(
- &mut internal_object,
- "encapsulate",
- name,
- RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
- );
- define_an_algorithm(
- &mut internal_object,
- "decapsulate",
- name,
- RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
- );
+ define_an_algorithm(&mut internal_object, "generateKey", name, RegisteredAlgorithm::MlKem);
+ define_an_algorithm(&mut internal_object, "importKey", name, RegisteredAlgorithm::MlKem);
+ define_an_algorithm(&mut internal_object, "exportKey", name, RegisteredAlgorithm::MlKem);
+ define_an_algorithm(&mut internal_object, "encapsulate", name, RegisteredAlgorithm::MlKem);
+ define_an_algorithm(&mut internal_object, "decapsulate", name, RegisteredAlgorithm::MlKem);
define_an_algorithm(
&mut internal_object,
"get shared key length",
name,
- RegisteredAlgorithm::Cpp(AlgorithmId::MlKem, ParameterId::AlgorithmParams),
+ RegisteredAlgorithm::MlKem,
);
}
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
index abe2c4ad549..71ee6a5b25a 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
@@ -76,13 +76,6 @@ static void receive_key_usages(void* state, ReadonlySpan<KeyUsage> usages)
*static_cast<Vector<KeyUsage>*>(state) = Vector<KeyUsage>(usages);
}
-static Vector<KeyUsage> usage_intersection(ReadonlySpan<KeyUsage> a, ReadonlySpan<KeyUsage> b)
-{
- Vector<KeyUsage> result;
- web_rust_crypto_usage_intersection(a, b, &result, receive_key_usages);
- return result;
-}
-
Vector<KeyUsage> normalized_key_usages(ReadonlySpan<KeyUsage> usages)
{
Vector<KeyUsage> result;
@@ -90,37 +83,6 @@ Vector<KeyUsage> normalized_key_usages(ReadonlySpan<KeyUsage> usages)
return result;
}
-static StringView key_usage_to_string(KeyUsage usage)
-{
- switch (usage) {
- case KeyUsage::Encrypt:
- return "encrypt"sv;
- case KeyUsage::Decrypt:
- return "decrypt"sv;
- case KeyUsage::Sign:
- return "sign"sv;
- case KeyUsage::Verify:
- return "verify"sv;
- case KeyUsage::DeriveKey:
- return "deriveKey"sv;
- case KeyUsage::DeriveBits:
- return "deriveBits"sv;
- case KeyUsage::WrapKey:
- return "wrapKey"sv;
- case KeyUsage::UnwrapKey:
- return "unwrapKey"sv;
- case KeyUsage::EncapsulateKey:
- return "encapsulateKey"sv;
- case KeyUsage::EncapsulateBits:
- return "encapsulateBits"sv;
- case KeyUsage::DecapsulateKey:
- return "decapsulateKey"sv;
- case KeyUsage::DecapsulateBits:
- return "decapsulateBits"sv;
- }
- VERIFY_NOT_REACHED();
-}
-
// Out of line to ensure this class has a key function
AlgorithmMethods::~AlgorithmMethods() = default;
@@ -226,36 +188,6 @@ FlatPtr web_crypto_decode_asn1_structure(ReadonlyBytes data, Asn1Structure struc
return 0;
}
-template<typename Structure>
-static WebIDL::ExceptionOr<Structure> parse_an_ASN1_structure(JS::Realm&, ReadonlyBytes data, bool exact_data = true)
-{
- constexpr auto structure_kind = [] {
- if constexpr (IsSame<Structure, ::Crypto::Certificate::SubjectPublicKey>)
- return Asn1Structure::SubjectPublicKeyInfo;
- else if constexpr (IsSame<Structure, ::Crypto::Certificate::PrivateKey>)
- return Asn1Structure::PrivateKeyInfo;
- else if constexpr (IsSame<Structure, StringView>)
- return Asn1Structure::OctetString;
- else
- static_assert(DependentFalse<Structure>, "Don't know how to parse ASN.1 structure type");
- }();
- Structure structure;
- auto error = web_rust_crypto_parse_an_asn1_structure(data, structure_kind, exact_data, &structure);
- if (error != 0)
- return WebIDL::DataError::create(Utf16String::adopt_raw(error));
- return structure;
-}
-
-static WebIDL::ExceptionOr<::Crypto::Certificate::SubjectPublicKey> parse_a_subject_public_key_info(JS::Realm& realm, ReadonlyBytes bytes)
-{
- return parse_an_ASN1_structure<::Crypto::Certificate::SubjectPublicKey>(realm, bytes);
-}
-
-static WebIDL::ExceptionOr<::Crypto::Certificate::PrivateKey> parse_a_private_key_info(JS::Realm& realm, ReadonlyBytes bytes)
-{
- return parse_an_ASN1_structure<::Crypto::Certificate::PrivateKey>(realm, bytes);
-}
-
static WebIDL::ExceptionOr<::Crypto::PK::RSAPrivateKey> parse_jwk_rsa_private_key(JS::Realm& realm, JsonWebKey const& jwk)
{
auto n = TRY(base64_url_uint_decode(realm, *jwk.n));
@@ -1154,525 +1086,80 @@ bool web_crypto_mldsa_export_der(CryptoKey::InternalKeyData const* key, bool is_
return true;
}
-// https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-generate-key
-WebIDL::ExceptionOr<Variant<GC::Ref<CryptoKey>, CryptoKeyPair>> MLKEM::generate_key(JS::Realm&, AlgorithmParams const& params, bool extractable, Vector<KeyUsage> const& usages)
-{
- // 1. If usages contains an entry which is not one of "encapsulateKey", "encapsulateBits", "decapsulateKey" or
- // "decapsulateBits", then throw a SyntaxError.
- for (auto const usage : usages) {
- if (usage != KeyUsage::EncapsulateKey
- && usage != KeyUsage::EncapsulateBits
- && usage != KeyUsage::DecapsulateKey
- && usage != KeyUsage::DecapsulateBits) {
- return WebIDL::SyntaxError::create("Invalid key usage"_utf16);
- }
- }
-
- // 2. Generate an ML-KEM key pair, as described in Section 7.1 of [FIPS-203], with the parameter set indicated
- // by the name member of normalizedAlgorithm.
- auto maybe_key_pair = [&] {
- if (params.name == "ML-KEM-512"sv)
- return ::Crypto::PK::MLKEM::generate_key_pair(::Crypto::PK::MLKEMSize::MLKEM512);
- if (params.name == "ML-KEM-768"sv)
- return ::Crypto::PK::MLKEM::generate_key_pair(::Crypto::PK::MLKEMSize::MLKEM768);
- if (params.name == "ML-KEM-1024"sv)
- return ::Crypto::PK::MLKEM::generate_key_pair(::Crypto::PK::MLKEMSize::MLKEM1024);
- VERIFY_NOT_REACHED();
- }();
-
- // 3. If the key generation step fails, then throw an OperationError.
- if (maybe_key_pair.is_error())
- return WebIDL::OperationError::create(Utf16String::formatted("Key generation failed: {}", maybe_key_pair.release_error()));
- auto const key_pair = maybe_key_pair.release_value();
-
- // 6. Let publicKey be a new CryptoKey representing the encapsulation key of the generated key pair.
- auto public_key = CryptoKey::create(key_pair.public_key);
-
- // 7. Set the [[type]] internal slot of publicKey to "public".
- public_key->set_type(KeyType::Public);
-
- // 4. Let algorithm be a new KeyAlgorithm object.
- // 5. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
- // 8. Set the [[algorithm]] internal slot of publicKey to algorithm.
- public_key->set_algorithm(CryptoKey::KeyAlgorithmData { params.name });
-
- // 9. Set the [[extractable]] internal slot of publicKey to true.
- public_key->set_extractable(true);
-
- // 10. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encapsulateKey",
- // "encapsulateBits" ].
- public_key->set_usages(usage_intersection(usages, { { KeyUsage::EncapsulateKey, KeyUsage::EncapsulateBits } }));
-
- // 11. Let privateKey be a new CryptoKey representing the decapsulation key of the generated key pair.
- auto private_key = CryptoKey::create(key_pair.private_key);
-
- // 12. Set the [[type]] internal slot of privateKey to "private".
- private_key->set_type(KeyType::Private);
-
- // 13. Set the [[algorithm]] internal slot of privateKey to algorithm.
- private_key->set_algorithm(CryptoKey::KeyAlgorithmData { params.name });
-
- // 14. Set the [[extractable]] internal slot of privateKey to extractable.
- private_key->set_extractable(extractable);
-
- // 15. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decapsulateKey",
- // "decapsulateBits" ].
- private_key->set_usages(usage_intersection(usages, { { KeyUsage::DecapsulateKey, KeyUsage::DecapsulateBits } }));
+extern "C" {
+FlatPtr web_crypto_mlkem_generate_key_pair(::Crypto::PK::MLKEMSize, ReadonlyBytes, CryptoKey::InternalKeyData**, CryptoKey::InternalKeyData**);
+CryptoKey::InternalKeyData* web_crypto_mlkem_key_info_read_private_key(void const*);
+CryptoKey::InternalKeyData* web_crypto_mlkem_read_public_key(ReadonlyBytes);
+void web_crypto_mlkem_public_bytes(CryptoKey::InternalKeyData const*, void*, ReceiveEncodedBytes);
+void web_crypto_mlkem_seed_bytes(CryptoKey::InternalKeyData const*, ReadonlyBytes*);
+bool web_crypto_mlkem_export_der(CryptoKey::InternalKeyData const*, bool, ReadonlySpan<u32>, void*, ReceiveEncodedBytes);
+FlatPtr web_crypto_mlkem_encapsulate(::Crypto::PK::MLKEMSize, CryptoKey::InternalKeyData const*, void*, void*, ReceiveEncodedBytes);
+FlatPtr web_crypto_mlkem_decapsulate(::Crypto::PK::MLKEMSize, CryptoKey::InternalKeyData const*, ReadonlyBytes, void*, ReceiveEncodedBytes);
+}
- // 16. Let result be a new CryptoKeyPair dictionary.
- // 17. Set the publicKey attribute of result to be publicKey.
- // 18. Set the privateKey attribute of result to be privateKey.
- auto result = CryptoKeyPair { public_key, private_key };
+static_assert(to_underlying(::Crypto::PK::MLKEMSize::MLKEM512) == 0);
+static_assert(to_underlying(::Crypto::PK::MLKEMSize::MLKEM768) == 1);
+static_assert(to_underlying(::Crypto::PK::MLKEMSize::MLKEM1024) == 2);
- // 19. Return result.
- return Variant<GC::Ref<CryptoKey>, CryptoKeyPair> { result };
+FlatPtr web_crypto_mlkem_generate_key_pair(::Crypto::PK::MLKEMSize size, ReadonlyBytes seed, CryptoKey::InternalKeyData** out_public_key, CryptoKey::InternalKeyData** out_private_key)
+{
+ auto key_pair = ::Crypto::PK::MLKEM::generate_key_pair(size, MUST(ByteBuffer::copy(seed)));
+ if (key_pair.is_error())
+ return Utf16String::formatted("{}", key_pair.error()).into_raw();
+ *out_public_key = new CryptoKey::InternalKeyData(move(key_pair.value().public_key));
+ *out_private_key = new CryptoKey::InternalKeyData(move(key_pair.value().private_key));
+ return 0;
}
-// https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-import-key
-WebIDL::ExceptionOr<GC::Ref<CryptoKey>> MLKEM::import_key(JS::Realm& realm, AlgorithmParams const& params, KeyFormat format, CryptoKey::ImportKeyData key_data, bool, Vector<KeyUsage> const& usages)
+CryptoKey::InternalKeyData* web_crypto_mlkem_key_info_read_private_key(void const* key_info)
{
- GC::Ptr<CryptoKey> key = nullptr;
-
- // 1. Let keyData be the key data to be imported.
- // 2. -> If format is "spki":
- if (format == KeyFormat::Spki) {
- // 1. If usages contains an entry which is not "encapsulateKey" or "encapsulateBits" then throw
- // a SyntaxError.
- for (auto const usage : usages) {
- if (usage != KeyUsage::EncapsulateKey && usage != KeyUsage::EncapsulateBits)
- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));
- }
-
- // 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
- // 3. If an error occurred while parsing, then throw a DataError.
- auto const spki = TRY(parse_a_subject_public_key_info(realm, key_data.get<ByteBuffer>()));
-
- Array<u32, 9> expected_oid;
- // 4. If the name member of normalizedAlgorithm is "ML-KEM-512":
- if (params.name == "ML-KEM-512"sv) {
- // Let expectedOid be id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1).
- expected_oid = ::Crypto::ASN1::ml_kem_512_oid;
- }
- // If the name member of normalizedAlgorithm is "ML-KEM-768":
- else if (params.name == "ML-KEM-768"sv) {
- // Let expectedOid be id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2).
- expected_oid = ::Crypto::ASN1::ml_kem_768_oid;
- }
- // If the name member of normalizedAlgorithm is "ML-KEM-1024":
- else if (params.name == "ML-KEM-1024"sv) {
- // Let expectedOid be id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3).
- expected_oid = ::Crypto::ASN1::ml_kem_1024_oid;
- }
- // Otherwise:
- else {
- // throw a NotSupportedError.
- return WebIDL::NotSupportedError::create("Invalid key format"_utf16);
- }
-
- // 5. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equal
- // to expectedOid, then throw a DataError.
- if (spki.algorithm.identifier != expected_oid)
- return WebIDL::DataError::create("Invalid algorithm"_utf16);
-
- // 6. If the parameters field of the algorithm AlgorithmIdentifier field of spki is present, then throw a DataError.
- if (spki.algorithm.ec_parameters.has_value())
- return WebIDL::DataError::create("Invalid algorithm parameters"_utf16);
-
- // 7. Let publicKey be the ML-KEM public key identified by the subjectPublicKey field of spki.
- auto const public_key = spki.raw_key;
-
- // 8. Let key be a new CryptoKey that represents publicKey.
- key = CryptoKey::create(::Crypto::PK::MLKEMPublicKey(public_key));
-
- // 9. Set the [[type]] internal slot of key to "public"
- key->set_type(KeyType::Public);
-
- // 10. Let algorithm be a new KeyAlgorithm.
- // 11. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
- // 12. Set the [[algorithm]] internal slot of key to algorithm.
- key->set_algorithm(CryptoKey::KeyAlgorithmData { params.name });
- }
- // -> If format is "pkcs8":
- else if (format == KeyFormat::Pkcs8) {
- // 1. If usages contains an entry which is not "decapsulateKey" or "decapsulateBits" then throw a SyntaxError.
- for (auto const& usage : usages) {
- if (usage != KeyUsage::DecapsulateKey && usage != KeyUsage::DecapsulateBits) {
- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));
- }
- }
-
- // 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
- // 3. If an error occurred while parsing, then throw a DataError.
- VERIFY(key_data.has<ByteBuffer>());
- auto private_key_info = TRY(parse_a_private_key_info(realm, key_data.get<ByteBuffer>()));
-
- // 4. => If the name member of normalizedAlgorithm is "ML-KEM-512":
- // Let expectedOid be id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1).
- // Let asn1Structure be the ASN.1 ML-KEM-512-PrivateKey structure.
- // => If the name member of normalizedAlgorithm is "ML-KEM-768":
- // Let expectedOid be id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2).
- // Let asn1Structure be the ASN.1 ML-KEM-768-PrivateKey structure.
- // => If the name member of normalizedAlgorithm is "ML-KEM-1024":
- // Let expectedOid be id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3).
- // Let asn1Structure be the ASN.1 ML-KEM-1024-PrivateKey structure.
- // => Otherwise:
- // throw a NotSupportedError.
- Array<u32, 9> expected_oid {};
- if (params.name == "ML-KEM-512"sv) {
- expected_oid = ::Crypto::ASN1::ml_kem_512_oid;
- } else if (params.name == "ML-KEM-768"sv) {
- expected_oid = ::Crypto::ASN1::ml_kem_768_oid;
- } else if (params.name == "ML-KEM-1024"sv) {
- expected_oid = ::Crypto::ASN1::ml_kem_1024_oid;
- } else {
- return WebIDL::NotSupportedError::create("Invalid algorithm"_utf16);
- }
-
- // 5. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of
- // privateKeyInfo is not equal to expectedOid, then throw a DataError.
- if (private_key_info.algorithm.identifier != expected_oid)
- return WebIDL::DataError::create("Invalid algorithm"_utf16);
-
- // 6. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of
- // privateKeyInfo is present, then throw a DataError.
- if (private_key_info.algorithm.ec_parameters.has_value())
- return WebIDL::DataError::create("Invalid algorithm parameters"_utf16);
-
- // 7. Let mlKemPrivateKey be the result of performing the parse an ASN.1 structure algorithm, with
- // data as the privateKey field of privateKeyInfo, structure as asn1Structure, and exactData set to
- // true.
- // NOTE: We already did this in parse_a_private_key_info
- // 8. If an error occurred while parsing, then throw a DataError.
- auto& ml_kem_private_key = private_key_info.mlkem;
-
- // 9. Let key be a new CryptoKey that represents the ML-KEM private key identified by
- // mlKemPrivateKey.
- key = CryptoKey::create(ml_kem_private_key);
-
- // 10. Set the [[type]] internal slot of key to "private"
- key->set_type(KeyType::Private);
-
- // 11. Let algorithm be a new KeyAlgorithm.
- // 12. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
- // 13. Set the [[algorithm]] internal slot of key to algorithm.
- key->set_algorithm(CryptoKey::KeyAlgorithmData { params.name });
- }
- // -> If format is "raw-public":
- else if (format == KeyFormat::RawPublic) {
- // 1. If usages contains an entry which is not "encapsulateKey" or "encapsulateBits" then throw a SyntaxError.
- for (auto const usage : usages) {
- if (usage != KeyUsage::EncapsulateKey && usage != KeyUsage::EncapsulateBits)
- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));
- }
-
- // 2. Let data be keyData.
- auto const& data = key_data;
-
- // 3. Let key be a new CryptoKey that represents the ML-KEM public key data in data.
- ASSERT(data.has<ByteBuffer>());
- key = CryptoKey::create(::Crypto::PK::MLKEMPublicKey { data.get<ByteBuffer>() });
-
- // 4. Set the [[type]] internal slot of key to "public"
- key->set_type(KeyType::Public);
-
- // 5. Let algorithm be a new KeyAlgorithm object.
- // 6. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
- // 6. Set the [[algorithm]] internal slot of key to algorithm.
- key->set_algorithm(CryptoKey::KeyAlgorithmData { params.name });
- }
- // -> If format is "raw-seed":
- else if (format == KeyFormat::RawSeed) {
- // 1. If usages contains an entry which is not "decapsulateKey" or "decapsulateBits" then throw a SyntaxError.
- for (auto const& usage : usages) {
- if (usage != KeyUsage::DecapsulateKey && usage != KeyUsage::DecapsulateBits) {
- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid key usage '{}'", key_usage_to_string(usage)));
- }
- }
-
- // 2. Let data be keyData.
- VERIFY(key_data.has<ByteBuffer>());
- auto const data = move(key_data.get<ByteBuffer>());
-
- // 3. If the length in bits of data is not 512 then throw a DataError.
- if (data.size() * 8 != 512)
- return WebIDL::DataError::create("Invalid key format"_utf16);
-
- // 4. Let privateKey be the result of performing the ML-KEM.KeyGen_internal function described in
- // Section 6.1 of [FIPS-203] with the parameter set indicated by the name member of
- // normalizedAlgorithm, using the first 256 bits of data as d and the last 256 bits of data as z.
- auto maybe_key_pair = [&] {
- if (params.name == "ML-KEM-512"sv)
- return ::Crypto::PK::MLKEM::generate_key_pair(::Crypto::PK::MLKEMSize::MLKEM512, data);
- if (params.name == "ML-KEM-768"sv)
- return ::Crypto::PK::MLKEM::generate_key_pair(::Crypto::PK::MLKEMSize::MLKEM768, data);
- if (params.name == "ML-KEM-1024"sv)
- return ::Crypto::PK::MLKEM::generate_key_pair(::Crypto::PK::MLKEMSize::MLKEM1024, data);
- VERIFY_NOT_REACHED();
- }();
- if (maybe_key_pair.is_error())
- return WebIDL::OperationError::create(Utf16String::formatted("Key generation failed: {}", maybe_key_pair.release_error()));
- auto const key_pair = maybe_key_pair.release_value();
-
- // 5. Let key be a new CryptoKey that represents the ML-KEM private key identified by privateKey.
- key = CryptoKey::create(key_pair.private_key);
-
- // 6. Set the [[type]] internal slot of key to "private"
- key->set_type(KeyType::Private);
-
- // 7. Let algorithm be a new KeyAlgorithm.
- // 8. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
- // 9. Set the [[algorithm]] internal slot of key to algorithm.
- key->set_algorithm(CryptoKey::KeyAlgorithmData { params.name });
- }
- // FIXME: -> If format is "jwk":
- // -> Otherwise:
- else {
- // throw a NotSupportedError.
- return WebIDL::NotSupportedError::create("Invalid key format"_utf16);
- }
-
- // 3. Return key.
- return GC::Ref { *key };
+ return new CryptoKey::InternalKeyData(static_cast<::Crypto::Certificate::PrivateKey const*>(key_info)->mlkem);
}
-// https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-export-key
-WebIDL::ExceptionOr<ExportKeyResult> MLKEM::export_key(JS::Realm& realm, KeyFormat format, GC::Ref<CryptoKey> key)
+CryptoKey::InternalKeyData* web_crypto_mlkem_read_public_key(ReadonlyBytes bytes)
{
- Optional<ExportKeyResult> result;
- auto& vm = realm.vm();
-
- // 1. Let key be the CryptoKey to be exported.
-
- // 2. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be
- // accessed, then throw an OperationError.
- // Note: In our impl this is always accessible
- auto const& handle = key->handle();
-
- // 3. -> If format is "spki":
- if (format == KeyFormat::Spki) {
- // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
- if (key->type() != KeyType::Public)
- return WebIDL::InvalidAccessError::create("Key is not a public key"_utf16);
-
- // 2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
-
- // 3. Let data be an instance of the SubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:
- // * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
- // * -> If the name member of keyAlgorithm is "ML-KEM-512":
- // Set the algorithm object identifier to the id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1) OID.
- // -> If the name member of keyAlgorithm is "ML-KEM-768":
- // Set the algorithm object identifier to the id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2) OID.
- // -> If the name member of keyAlgorithm is "ML-KEM-1024":
- // Set the algorithm object identifier to the id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3) OID.
- // -> Otherwise:
- // throw a NotSupportedError.
- // * Set the subjectPublicKey field to keyData.
- Array<u32, 9> algorithm_oid {};
- if (key->algorithm_name() == "ML-KEM-512"sv) {
- algorithm_oid = ::Crypto::ASN1::ml_kem_512_oid;
- } else if (key->algorithm_name() == "ML-KEM-768"sv) {
- algorithm_oid = ::Crypto::ASN1::ml_kem_768_oid;
- } else if (key->algorithm_name() == "ML-KEM-1024"sv) {
- algorithm_oid = ::Crypto::ASN1::ml_kem_1024_oid;
- } else {
- return WebIDL::NotSupportedError::create("Invalid algorithm"_utf16);
- }
-
- ::Crypto::ASN1::Encoder encoder;
- VERIFY(handle.has<::Crypto::PK::MLKEMPublicKey>());
- auto data = TRY_OR_THROW_OOM(vm, ::Crypto::PK::wrap_in_subject_public_key_info(handle.get<::Crypto::PK::MLKEMPublicKey>().public_key(), algorithm_oid));
-
- // 4. Let result be the result of DER-encoding data.
- result = ExportKeyResult { data };
- }
- // -> If format is "pkcs8":
- else if (format == KeyFormat::Pkcs8) {
- // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
- if (key->type() != KeyType::Private)
- return WebIDL::InvalidAccessError::create("Key is not a private key"_utf16);
-
- // 2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
-
- // 3. Let data be an instance of the PrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:
- // * Set the version field to 0.
- // * Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:
- // * => If the name member of keyAlgorithm is "ML-KEM-512":
- // Set the algorithm object identifier to the id-alg-ml-kem-512 (2.16.840.1.101.3.4.4.1) OID.
- // * => If the name member of keyAlgorithm is "ML-KEM-768":
- // Set the algorithm object identifier to the id-alg-ml-kem-768 (2.16.840.1.101.3.4.4.2) OID.
- // * => If the name member of keyAlgorithm is "ML-KEM-1024":
- // Set the algorithm object identifier to the id-alg-ml-kem-1024 (2.16.840.1.101.3.4.4.3) OID.
- // * => Otherwise:
- // throw a NotSupportedError.
- // * Set the privateKey field as follows:
- // * => If the name member of keyAlgorithm is "ML-KEM-512":
- // Set the privateKey field to the result of DER-encoding a ML-KEM-512-PrivateKey
- // ASN.1 type that represents the ML-KEM private key seed represented by the
- // [[handle]] internal slot of key using the seed-only format (using a context-
- // specific [0] primitive tag with an implicit encoding of OCTET STRING).
- // * => If the name member of keyAlgorithm is "ML-KEM-768":
- // Set the privateKey field to the result of DER-encoding a ML-KEM-65-PrivateKey
- // ASN.1 type that represents the ML-KEM private key seed represented by the
- // [[handle]] internal slot of key using the seed-only format (using a context-
- // specific [0] primitive tag with an implicit encoding of OCTET STRING).
- // * => If the name member of keyAlgorithm is "ML-KEM-1024":
- // Set the privateKey field to the result of DER-encoding a ML-KEM-1024-PrivateKey
- // ASN.1 type that represents the ML-KEM private key seed represented by the
- // [[handle]] internal slot of key using the seed-only format (using a context-
- // specific [0] primitive tag with an implicit encoding of OCTET STRING).
- // * => Otherwise:
- // throw a NotSupportedError.
- Array<u32, 9> algorithm_oid {};
- if (key->algorithm_name() == "ML-KEM-512"sv) {
- algorithm_oid = ::Crypto::ASN1::ml_kem_512_oid;
- } else if (key->algorithm_name() == "ML-KEM-768"sv) {
- algorithm_oid = ::Crypto::ASN1::ml_kem_768_oid;
- } else if (key->algorithm_name() == "ML-KEM-1024"sv) {
- algorithm_oid = ::Crypto::ASN1::ml_kem_1024_oid;
- } else {
- return WebIDL::NotSupportedError::create("Invalid algorithm"_utf16);
- }
-
- ::Crypto::ASN1::Encoder encoder;
- VERIFY(handle.has<::Crypto::PK::MLKEMPrivateKey>());
- auto const data = TRY_OR_THROW_OOM(realm.vm(), ::Crypto::PK::wrap_in_private_key_info(handle.get<::Crypto::PK::MLKEMPrivateKey>(), algorithm_oid));
-
- // 4. Let result be the result of DER-encoding data.
- result = ExportKeyResult { data };
- }
- // -> If format is "raw-public":
- else if (format == KeyFormat::RawPublic) {
- // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
- if (key->type() != KeyType::Public)
- return WebIDL::InvalidAccessError::create("Key is not a public key"_utf16);
-
- // 2. Let data be a byte sequence containing the raw octets of the key represented by the [[handle]] internal slot of key.
- VERIFY(handle.has<::Crypto::PK::MLKEMPublicKey>());
- auto const data = handle.get<::Crypto::PK::MLKEMPublicKey>().public_key();
-
- // 3. Let result be data.
- result = ExportKeyResult { data };
- }
- // -> If format is "raw-seed":
- else if (format == KeyFormat::RawSeed) {
- // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
- if (key->type() != KeyType::Private)
- return WebIDL::InvalidAccessError::create("Key is not a private key"_utf16);
-
- // 2. Let data be a byte sequence containing the concatenation of the d and z seed variables of the
- // key represented by the [[handle]] internal slot of key.
- VERIFY(key->handle().has<::Crypto::PK::MLKEMPrivateKey>());
- auto const data = key->handle().get<::Crypto::PK::MLKEMPrivateKey>().seed();
-
- // 3. Let result be data.
- result = ExportKeyResult { data };
- }
- // FIXME: -> If format is "jwk":
- // -> Otherwise:
- else {
- // throw a NotSupportedError.
- return WebIDL::NotSupportedError::create("Invalid key format"_utf16);
- }
-
- // 4. Return result.
- return result.release_value();
+ return new CryptoKey::InternalKeyData(::Crypto::PK::MLKEMPublicKey { MUST(ByteBuffer::copy(bytes)) });
}
-Optional<ReadonlySpan<KeyUsage>> MLKEM::public_key_usages() const
+void web_crypto_mlkem_public_bytes(CryptoKey::InternalKeyData const* key, void* state, ReceiveEncodedBytes receive)
{
- static constexpr Array usages { KeyUsage::EncapsulateKey, KeyUsage::EncapsulateBits };
- return usages.span();
+ auto public_key = key->get<::Crypto::PK::MLKEMPublicKey>().public_key();
+ receive(state, public_key);
}
-// https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-encapsulate
-WebIDL::ExceptionOr<EncapsulatedBits> MLKEM::encapsulate(JS::Realm&, AlgorithmParams const& params, GC::Ref<CryptoKey> key)
+void web_crypto_mlkem_seed_bytes(CryptoKey::InternalKeyData const* key, ReadonlyBytes* bytes)
{
- // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
- if (key->type() != KeyType::Public)
- return WebIDL::InvalidAccessError::create("Invalid key type"_utf16);
-
- // 2. Perform the encapsulation key check described in Section 7.2 of [FIPS-203] with the parameter set indicated
- // by the name member of algorithm, using the key represented by the [[handle]] internal slot of key as the ek
- // input parameter.
- // 3. If the encapsulation key check failed, return an OperationError.
- // NOTE: Presumably done by OpenSSL for us
-
- // 4. Let sharedKey and ciphertext be the outputs that result from performing the ML-KEM.Encaps function
- // described in Section 7.2 of [FIPS-203] with the parameter set indicated by the name member of algorithm,
- // using the key represented by the [[handle]] internal slot of key as the ek input parameter.
- VERIFY(key->handle().has<::Crypto::PK::MLKEMPublicKey>());
- auto maybe_encapsulation = [&]() {
- if (params.name == "ML-KEM-512"sv) {
- return ::Crypto::PK::MLKEM::encapsulate(::Crypto::PK::MLKEMSize::MLKEM512, key->handle().get<::Crypto::PK::MLKEMPublicKey>());
- }
- if (params.name == "ML-KEM-768"sv) {
- return ::Crypto::PK::MLKEM::encapsulate(::Crypto::PK::MLKEMSize::MLKEM768, key->handle().get<::Crypto::PK::MLKEMPublicKey>());
- }
- if (params.name == "ML-KEM-1024"sv) {
- return ::Crypto::PK::MLKEM::encapsulate(::Crypto::PK::MLKEMSize::MLKEM1024, key->handle().get<::Crypto::PK::MLKEMPublicKey>());
- }
- VERIFY_NOT_REACHED();
- }();
-
- // 5. If the ML-KEM.Encaps function returned an error, return an OperationError.
- if (maybe_encapsulation.is_error())
- return WebIDL::OperationError::create(Utf16String::formatted("Key encapsulation failed: {}", maybe_encapsulation.release_error()));
- auto const [shared_key, ciphertext] = maybe_encapsulation.release_value();
-
- // 6. Let result be a new EncapsulatedBits dictionary.
- // 7. Set the sharedKey attribute of result to the result of creating an ArrayBuffer containing sharedKey.
- // 8. Set the ciphertext attribute of result to the result of creating an ArrayBuffer containing ciphertext.
- auto result = EncapsulatedBits { shared_key, ciphertext };
-
- // 9. Return result.
- return result;
+ *bytes = key->get<::Crypto::PK::MLKEMPrivateKey>().seed();
}
-// https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-decapsulate
-WebIDL::ExceptionOr<ByteBuffer> MLKEM::decapsulate(JS::Realm&, AlgorithmParams const& params, GC::Ref<CryptoKey> key, ByteBuffer const& ciphertext)
+bool web_crypto_mlkem_export_der(CryptoKey::InternalKeyData const* key, bool is_public, ReadonlySpan<u32> oid, void* state, ReceiveEncodedBytes receive)
{
- // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
- if (key->type() != KeyType::Private)
- return WebIDL::InvalidAccessError::create("Invalid key type"_utf16);
-
- // 2. Perform the decapsulation input check described in Section 7.3 of [FIPS-203] with the parameter set
- // indicated by the name member of algorithm, using the key represented by the [[handle]] internal slot of key as
- // the dk input parameter, and ciphertext as the c input parameter.
- // 3. If the decapsulation key check failed, return an OperationError.
- // NOTE: Presumably done by OpenSSL for us
-
- // 4. Let sharedKey be the output that results from performing the ML-KEM.Decaps function described in Section
- // 7.3 of [FIPS-203] with the parameter set indicated by the name member of algorithm, using the key
- // represented by the [[handle]] internal slot of key as the dk input parameter, and ciphertext as the c input
- // parameter.
- VERIFY(key->handle().has<::Crypto::PK::MLKEMPrivateKey>());
- auto maybe_shared_key = [&]() {
- if (params.name == "ML-KEM-512"sv) {
- return ::Crypto::PK::MLKEM::decapsulate(::Crypto::PK::MLKEMSize::MLKEM512, key->handle().get<::Crypto::PK::MLKEMPrivateKey>(), ciphertext);
- }
- if (params.name == "ML-KEM-768"sv) {
- return ::Crypto::PK::MLKEM::decapsulate(::Crypto::PK::MLKEMSize::MLKEM768, key->handle().get<::Crypto::PK::MLKEMPrivateKey>(), ciphertext);
- }
- if (params.name == "ML-KEM-1024"sv) {
- return ::Crypto::PK::MLKEM::decapsulate(::Crypto::PK::MLKEMSize::MLKEM1024, key->handle().get<::Crypto::PK::MLKEMPrivateKey>(), ciphertext);
- }
- VERIFY_NOT_REACHED();
- }();
-
- if (maybe_shared_key.is_error())
- return WebIDL::OperationError::create(Utf16String::formatted("Key decapsulation failed: {}", maybe_shared_key.release_error()));
-
- auto const shared_key = maybe_shared_key.release_value();
+ auto result = is_public
+ ? ::Crypto::PK::wrap_in_subject_public_key_info(key->get<::Crypto::PK::MLKEMPublicKey>().public_key(), oid)
+ : ::Crypto::PK::wrap_in_private_key_info(key->get<::Crypto::PK::MLKEMPrivateKey>(), oid);
+ if (result.is_error())
+ return false;
+ receive(state, result.value());
+ return true;
+}
- // 5. Return sharedKey.
- return shared_key;
+FlatPtr web_crypto_mlkem_encapsulate(::Crypto::PK::MLKEMSize size, CryptoKey::InternalKeyData const* key, void* shared_key, void* ciphertext, ReceiveEncodedBytes receive)
+{
+ auto result = ::Crypto::PK::MLKEM::encapsulate(size, key->get<::Crypto::PK::MLKEMPublicKey>());
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ receive(shared_key, result.value().shared_key);
+ receive(ciphertext, result.value().ciphertext);
+ return 0;
}
-// https://wicg.github.io/webcrypto-modern-algos/#ml-kem-operations-get-shared-key-length
-WebIDL::ExceptionOr<u32> MLKEM::get_shared_key_length(AlgorithmParams const&) const
+FlatPtr web_crypto_mlkem_decapsulate(::Crypto::PK::MLKEMSize size, CryptoKey::InternalKeyData const* key, ReadonlyBytes ciphertext, void* state, ReceiveEncodedBytes receive)
{
- // 1. Return 256.
- return 256;
+ auto result = ::Crypto::PK::MLKEM::decapsulate(size, key->get<::Crypto::PK::MLKEMPrivateKey>(), MUST(ByteBuffer::copy(ciphertext)));
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ receive(state, result.value());
+ return 0;
}
struct Argon2Inputs {
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
index 4cce3be0a41..87094fc9017 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h
@@ -138,23 +138,6 @@ protected:
AlgorithmMethods() = default;
};
-class MLKEM : public AlgorithmMethods {
-public:
- virtual WebIDL::ExceptionOr<Variant<GC::Ref<CryptoKey>, CryptoKeyPair>> generate_key(JS::Realm& realm, AlgorithmParams const&, bool, Vector<KeyUsage> const&) override;
- virtual WebIDL::ExceptionOr<GC::Ref<CryptoKey>> import_key(JS::Realm& realm, AlgorithmParams const&, KeyFormat, CryptoKey::ImportKeyData, bool, Vector<KeyUsage> const&) override;
- virtual WebIDL::ExceptionOr<ExportKeyResult> export_key(JS::Realm& realm, KeyFormat, GC::Ref<CryptoKey>) override;
- virtual WebIDL::ExceptionOr<EncapsulatedBits> encapsulate(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>) override;
- virtual WebIDL::ExceptionOr<ByteBuffer> decapsulate(JS::Realm& realm, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&) override;
- virtual WebIDL::ExceptionOr<u32> get_shared_key_length(AlgorithmParams const&) const override;
-
- virtual Optional<ReadonlySpan<KeyUsage>> public_key_usages() const override;
-
- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new MLKEM); }
-
-private:
- MLKEM() = default;
-};
-
// 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 e4cf18a1b49..abfaa9b6693 100644
--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp
@@ -189,7 +189,7 @@ JSCompletion web_crypto_algorithm_from_value(JS::Realm*, AlgorithmId method_id,
auto methods = [&]() -> NonnullOwnPtr<AlgorithmMethods> {
switch (method_id) {
case AlgorithmId::MLKEM:
- return MLKEM::create();
+ VERIFY_NOT_REACHED();
}
VERIFY_NOT_REACHED();
}();
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 584cf0b261f..36dc93bdae0 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,
- 83,
+ 70,
"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",