Skip to content

Truly independent web browser

LibCrypto: Expose native cryptography to Rust

Shannon Boothbf4843b47e17
diff --git a/Cargo.lock b/Cargo.lock
index 377fb975879..2d5d71b002c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1760,6 +1760,13 @@ dependencies = [
"flate2",
]
+[[package]]
+name = "libcrypto_rust"
+version = "0.1.0"
+dependencies = [
+ "ak",
+]
+
[[package]]
name = "libgfx_rust"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index f353c408bd9..295b418b382 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,6 +3,7 @@ members = [
"AK/Rust",
"Libraries/LibCompositing/Rust",
"Libraries/LibCompress/Rust",
+ "Libraries/LibCrypto/Rust",
"Libraries/LibGfx/Rust",
"Libraries/LibHTTP/Rust",
"Libraries/LibImageDecoders/Rust",
diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txt
index f011757acfb..534d119c89f 100644
--- a/Libraries/LibCrypto/CMakeLists.txt
+++ b/Libraries/LibCrypto/CMakeLists.txt
@@ -1,7 +1,9 @@
add_cxx_compile_options(-Wvla)
set(SOURCES
+ KeyHandle.cpp
OpenSSL.cpp
+ RustBindings.cpp
ASN1/ASN1.cpp
ASN1/DER.cpp
ASN1/PEM.cpp
diff --git a/Libraries/LibCrypto/KeyHandle.cpp b/Libraries/LibCrypto/KeyHandle.cpp
new file mode 100644
index 00000000000..8f78ea67154
--- /dev/null
+++ b/Libraries/LibCrypto/KeyHandle.cpp
@@ -0,0 +1,225 @@
+/*
+ * Copyright (c) 2023, stelar7 <[email protected]>
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Array.h>
+#include <AK/Memory.h>
+#include <LibCrypto/KeyHandle.h>
+
+namespace Crypto {
+
+struct CryptoKeyHandleFields {
+ u8 handle_tag { 0 };
+ Array<ReadonlyBytes, 8> handle_buffers;
+ size_t handle_buffer_count { 0 };
+ bool has_ec_parameters { false };
+ ReadonlySpan<u32> ec_parameters;
+ bool has_ec_public_key { false };
+};
+
+extern "C" {
+void crypto_key_destroy_handle(KeyHandle*);
+KeyHandle* crypto_key_create_byte_handle(ReadonlyBytes);
+KeyHandle* crypto_key_create_okp_handle(bool, ReadonlyBytes);
+void crypto_key_okp_handle_bytes(KeyHandle const*, ReadonlyBytes*);
+void crypto_key_byte_handle_bytes(KeyHandle const*, ReadonlyBytes*);
+void crypto_key_encode_handle(KeyHandle const*, void*, void (*)(void*, CryptoKeyHandleFields const*));
+bool crypto_key_decode_handle(CryptoKeyHandleFields const*, KeyHandle**);
+}
+
+void crypto_key_destroy_handle(KeyHandle* handle)
+{
+ handle->visit(
+ [](ByteBuffer& data) { secure_zero(data.data(), data.size()); },
+ [](OKPPublicKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },
+ [](OKPPrivateKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },
+ [](::Crypto::PK::RSAPrivateKey& data) { data.clear_sensitive_data(); },
+ [](::Crypto::PK::ECPrivateKey& data) { data.clear_sensitive_data(); },
+ [](::Crypto::PK::MLDSAPrivateKey& data) { data.clear_sensitive_data(); },
+ [](::Crypto::PK::MLKEMPrivateKey& data) { data.clear_sensitive_data(); },
+ [](auto&) { });
+ delete handle;
+}
+
+KeyHandle* crypto_key_create_byte_handle(ReadonlyBytes bytes)
+{
+ return new KeyHandle(MUST(ByteBuffer::copy(bytes)));
+}
+
+void crypto_key_byte_handle_bytes(KeyHandle const* handle, ReadonlyBytes* bytes)
+{
+ *bytes = handle->get<ByteBuffer>().bytes();
+}
+
+KeyHandle* crypto_key_create_okp_handle(bool is_private, ReadonlyBytes bytes)
+{
+ auto key_bytes = MUST(ByteBuffer::copy(bytes));
+ if (is_private)
+ return new KeyHandle(OKPPrivateKey { move(key_bytes) });
+ return new KeyHandle(OKPPublicKey { move(key_bytes) });
+}
+
+void crypto_key_okp_handle_bytes(KeyHandle const* handle, ReadonlyBytes* bytes)
+{
+ if (handle->has<OKPPrivateKey>())
+ *bytes = handle->get<OKPPrivateKey>().bytes;
+ else
+ *bytes = handle->get<OKPPublicKey>().bytes;
+}
+
+static_assert(to_underlying(HandleTag::ECPrivateKey) == 4);
+static_assert(to_underlying(HandleTag::OKPPrivateKey) == 10);
+
+static ByteBuffer export_big_integer(::Crypto::UnsignedBigInteger const& value)
+{
+ auto buffer = MUST(ByteBuffer::create_zeroed(value.byte_length()));
+ auto written = value.export_data(buffer.bytes());
+ VERIFY(written.size() == buffer.size());
+ return buffer;
+}
+
+void crypto_key_encode_handle(KeyHandle const* handle, void* state, void (*steps)(void*, CryptoKeyHandleFields const*))
+{
+ CryptoKeyHandleFields fields;
+ // NB: The inline capacity holds every buffer that a handle exports, so that none moves while the fields borrow it.
+ Vector<ByteBuffer, 8> exported;
+ auto add = [&](ReadonlyBytes bytes) { fields.handle_buffers[fields.handle_buffer_count++] = bytes; };
+ auto add_exported = [&](ByteBuffer buffer) {
+ exported.unchecked_append(move(buffer));
+ add(exported.last().bytes());
+ };
+ handle->visit(
+ [&](ByteBuffer const& buffer) {
+ fields.handle_tag = to_underlying(HandleTag::ByteBuffer);
+ add(buffer.bytes());
+ },
+ [&](::Crypto::PK::RSAPublicKey const& rsa_key) {
+ fields.handle_tag = to_underlying(HandleTag::RSAPublicKey);
+ add_exported(export_big_integer(rsa_key.modulus()));
+ add_exported(export_big_integer(rsa_key.public_exponent()));
+ },
+ [&](::Crypto::PK::RSAPrivateKey const& rsa_key) {
+ fields.handle_tag = to_underlying(HandleTag::RSAPrivateKey);
+ add_exported(export_big_integer(rsa_key.modulus()));
+ add_exported(export_big_integer(rsa_key.private_exponent()));
+ add_exported(export_big_integer(rsa_key.public_exponent()));
+ add_exported(export_big_integer(rsa_key.prime1()));
+ add_exported(export_big_integer(rsa_key.prime2()));
+ add_exported(export_big_integer(rsa_key.exponent1()));
+ add_exported(export_big_integer(rsa_key.exponent2()));
+ add_exported(export_big_integer(rsa_key.coefficient()));
+ },
+ [&](::Crypto::PK::ECPublicKey const& ec_key) {
+ fields.handle_tag = to_underlying(HandleTag::ECPublicKey);
+ add_exported(MUST(ec_key.x_bytes()));
+ add_exported(MUST(ec_key.y_bytes()));
+ },
+ [&](::Crypto::PK::ECPrivateKey const& ec_key) {
+ fields.handle_tag = to_underlying(HandleTag::ECPrivateKey);
+ add_exported(MUST(ec_key.d_bytes()));
+ fields.has_ec_parameters = ec_key.parameters().has_value();
+ if (fields.has_ec_parameters)
+ fields.ec_parameters = ec_key.parameters()->span();
+ fields.has_ec_public_key = ec_key.public_key().has_value();
+ if (fields.has_ec_public_key) {
+ add_exported(MUST(ec_key.public_key()->x_bytes()));
+ add_exported(MUST(ec_key.public_key()->y_bytes()));
+ }
+ },
+ [&](::Crypto::PK::MLDSAPublicKey const& mldsa_key) {
+ fields.handle_tag = to_underlying(HandleTag::MLDSAPublicKey);
+ add(mldsa_key.public_key().bytes());
+ },
+ [&](::Crypto::PK::MLDSAPrivateKey const& mldsa_key) {
+ fields.handle_tag = to_underlying(HandleTag::MLDSAPrivateKey);
+ add(mldsa_key.seed().bytes());
+ add(mldsa_key.public_key().bytes());
+ add(mldsa_key.private_key().bytes());
+ },
+ [&](::Crypto::PK::MLKEMPublicKey const& mlkem_key) {
+ fields.handle_tag = to_underlying(HandleTag::MLKEMPublicKey);
+ add_exported(mlkem_key.public_key());
+ },
+ [&](::Crypto::PK::MLKEMPrivateKey const& mlkem_key) {
+ fields.handle_tag = to_underlying(HandleTag::MLKEMPrivateKey);
+ add(mlkem_key.seed().bytes());
+ add(mlkem_key.public_key().bytes());
+ add(mlkem_key.private_key().bytes());
+ },
+ [&](OKPPublicKey const& okp_key) {
+ fields.handle_tag = to_underlying(HandleTag::OKPPublicKey);
+ add(okp_key.bytes.bytes());
+ },
+ [&](OKPPrivateKey const& okp_key) {
+ fields.handle_tag = to_underlying(HandleTag::OKPPrivateKey);
+ add(okp_key.bytes.bytes());
+ });
+
+ steps(state, &fields);
+
+ for (auto& buffer : exported)
+ secure_zero(buffer.data(), buffer.size());
+}
+
+static ErrorOr<KeyHandle> handle_from_fields(CryptoKeyHandleFields const& fields)
+{
+ auto buffer = [&](size_t index) {
+ VERIFY(index < fields.handle_buffer_count);
+ return fields.handle_buffers[index];
+ };
+ auto copy = [&](size_t index) -> ErrorOr<ByteBuffer> {
+ return TRY(ByteBuffer::copy(buffer(index)));
+ };
+ auto big_integer = [&](size_t index) { return ::Crypto::UnsignedBigInteger::import_data(buffer(index)); };
+
+ switch (static_cast<HandleTag>(fields.handle_tag)) {
+ case HandleTag::ByteBuffer:
+ return TRY(copy(0));
+ case HandleTag::RSAPublicKey:
+ return ::Crypto::PK::RSAPublicKey { big_integer(0), big_integer(1) };
+ case HandleTag::RSAPrivateKey:
+ return ::Crypto::PK::RSAPrivateKey { big_integer(0), big_integer(1), big_integer(2), big_integer(3), big_integer(4), big_integer(5), big_integer(6), big_integer(7) };
+ case HandleTag::ECPublicKey:
+ return ::Crypto::PK::ECPublicKey { big_integer(0), big_integer(1), buffer(0).size() };
+ case HandleTag::ECPrivateKey: {
+ Optional<::Crypto::ASN1::ObjectIdentifier> parameters;
+ if (fields.has_ec_parameters) {
+ ::Crypto::ASN1::ObjectIdentifier identifier;
+ TRY(identifier.try_append(fields.ec_parameters.data(), fields.ec_parameters.size()));
+ parameters = move(identifier);
+ }
+ Optional<::Crypto::PK::ECPublicKey> public_key;
+ if (fields.has_ec_public_key)
+ public_key = ::Crypto::PK::ECPublicKey { big_integer(1), big_integer(2), buffer(1).size() };
+ return ::Crypto::PK::ECPrivateKey { big_integer(0), buffer(0).size(), move(parameters), move(public_key) };
+ }
+ case HandleTag::MLDSAPublicKey:
+ return ::Crypto::PK::MLDSAPublicKey { TRY(copy(0)) };
+ case HandleTag::MLDSAPrivateKey:
+ return ::Crypto::PK::MLDSAPrivateKey { TRY(copy(0)), TRY(copy(1)), TRY(copy(2)) };
+ case HandleTag::MLKEMPublicKey:
+ return ::Crypto::PK::MLKEMPublicKey { TRY(copy(0)) };
+ case HandleTag::MLKEMPrivateKey:
+ return ::Crypto::PK::MLKEMPrivateKey { TRY(copy(0)), TRY(copy(1)), TRY(copy(2)) };
+ case HandleTag::OKPPublicKey:
+ return OKPPublicKey { TRY(copy(0)) };
+ case HandleTag::OKPPrivateKey:
+ return OKPPrivateKey { TRY(copy(0)) };
+ }
+ VERIFY_NOT_REACHED();
+}
+
+bool crypto_key_decode_handle(CryptoKeyHandleFields const* fields, KeyHandle** out_handle)
+{
+ auto handle = handle_from_fields(*fields);
+ if (handle.is_error())
+ return false;
+ *out_handle = new KeyHandle(handle.release_value());
+ return true;
+}
+
+}
diff --git a/Libraries/LibCrypto/KeyHandle.h b/Libraries/LibCrypto/KeyHandle.h
new file mode 100644
index 00000000000..e48a9964e02
--- /dev/null
+++ b/Libraries/LibCrypto/KeyHandle.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2023, stelar7 <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Variant.h>
+#include <AK/kmalloc.h>
+#include <LibCrypto/PK/EC.h>
+#include <LibCrypto/PK/MLDSA.h>
+#include <LibCrypto/PK/MLKEM.h>
+#include <LibCrypto/PK/RSA.h>
+
+namespace Crypto {
+
+// The raw key octets of an Ed25519, Ed448, X25519, or X448 ("OKP") key.
+struct OKPPublicKey {
+ ByteBuffer bytes;
+};
+
+struct OKPPrivateKey {
+ ByteBuffer bytes;
+};
+
+struct KeyHandle final : Variant<ByteBuffer, PK::RSAPublicKey, PK::RSAPrivateKey, PK::ECPublicKey, PK::ECPrivateKey, PK::MLDSAPublicKey, PK::MLDSAPrivateKey, PK::MLKEMPublicKey, PK::MLKEMPrivateKey, OKPPublicKey, OKPPrivateKey> {
+ AK_ALLOC_WITH_KMALLOC;
+
+ using Variant::Variant;
+};
+
+// These tags identify the key components in stored CryptoKey records.
+enum class HandleTag : u8 {
+ ByteBuffer = 0,
+ RSAPublicKey = 1,
+ RSAPrivateKey = 2,
+ ECPublicKey = 3,
+ ECPrivateKey = 4,
+ MLDSAPublicKey = 5,
+ MLDSAPrivateKey = 6,
+ MLKEMPublicKey = 7,
+ MLKEMPrivateKey = 8,
+ OKPPublicKey = 9,
+ OKPPrivateKey = 10,
+};
+
+}
diff --git a/Libraries/LibCrypto/Rust/Cargo.toml b/Libraries/LibCrypto/Rust/Cargo.toml
new file mode 100644
index 00000000000..24cc856c11f
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "libcrypto_rust"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+ak = { path = "../../../AK/Rust" }
+
+[lints]
+workspace = true
diff --git a/Libraries/LibCrypto/Rust/src/ffi.rs b/Libraries/LibCrypto/Rust/src/ffi.rs
new file mode 100644
index 00000000000..38a37cf6650
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/ffi.rs
@@ -0,0 +1,484 @@
+/*
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2024, stelar7 <[email protected]>
+ * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2024, Andreas Kling <[email protected]>
+ * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+
+use ak::{Span, SpanMut};
+
+use super::{
+ Argon2Inputs, Argon2Type, Asn1Structure, CShakeKind, EcCurve, KmacKind, MlDsaSize, MlKemSize, OkpCurve,
+ RsaJwkInteger, ShaHashKind,
+};
+
+pub(super) type ReceiveBytes = unsafe extern "C" fn(*mut c_void, Span<'_, u8>);
+
+#[repr(u8)]
+#[derive(PartialEq, Eq)]
+#[allow(dead_code, reason = "constructed by the native decoder")]
+pub(super) enum Base64Status {
+ Success,
+ OutOfMemory,
+ InvalidBase64,
+ NonAscii,
+}
+
+#[repr(C)]
+pub(super) struct OptionalBytes<'a> {
+ has_value: bool,
+ bytes: Span<'a, u8>,
+}
+
+impl<'a> From<Option<&'a [u8]>> for OptionalBytes<'a> {
+ fn from(bytes: Option<&'a [u8]>) -> Self {
+ Self {
+ has_value: bytes.is_some(),
+ bytes: Span::new(bytes.unwrap_or_default()),
+ }
+ }
+}
+
+unsafe extern "C" {
+ pub(super) fn crypto_encode_base64url(bytes: Span<'_, u8>, receive: ReceiveBytes, state: *mut c_void) -> i32;
+ pub(super) fn crypto_decode_base64url(
+ raw: usize,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ error_message: &mut usize,
+ ) -> Base64Status;
+ pub(super) fn crypto_decode_asn1_structure(
+ data: Span<'_, u8>,
+ structure: Asn1Structure,
+ out: *mut c_void,
+ all_consumed: &mut bool,
+ ) -> usize;
+ pub(super) fn crypto_public_key_for_private_key(key: *const c_void, name: usize, named_curve: usize)
+ -> *mut c_void;
+ pub(super) fn crypto_sha_digest(
+ kind: ShaHashKind,
+ data: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_cshake_validate_parameters(
+ output_length: u32,
+ customization: OptionalBytes<'_>,
+ function_name: OptionalBytes<'_>,
+ ) -> usize;
+ pub(super) fn crypto_cshake_digest(
+ kind: CShakeKind,
+ data: Span<'_, u8>,
+ output_length: u32,
+ customization: OptionalBytes<'_>,
+ function_name: OptionalBytes<'_>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+ pub(super) fn crypto_hmac_sign(
+ kind: ShaHashKind,
+ key: Span<'_, u8>,
+ message: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> ();
+ pub(super) fn crypto_timing_safe_compare(left: Span<'_, u8>, right: Span<'_, u8>) -> bool;
+ pub(super) fn crypto_kmac_default_key_length(kind: KmacKind) -> u32;
+ pub(super) fn crypto_kmac_validate_parameters(output_length: u32, customization: OptionalBytes<'_>) -> bool;
+ pub(super) fn crypto_kmac_sign(
+ kind: KmacKind,
+ key: Span<'_, u8>,
+ message: Span<'_, u8>,
+ output_length: u32,
+ customization: OptionalBytes<'_>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_hash_digest_size(kind: ShaHashKind) -> usize;
+ pub(super) fn crypto_hkdf_derive_key(
+ kind: ShaHashKind,
+ salt: Span<'_, u8>,
+ key: Span<'_, u8>,
+ info: Span<'_, u8>,
+ length: u32,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_pbkdf2_derive_key(
+ kind: ShaHashKind,
+ password: Span<'_, u8>,
+ salt: Span<'_, u8>,
+ iterations: u32,
+ length: u32,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_argon2_validate_parameters(nonce: Span<'_, u8>) -> usize;
+ pub(super) fn crypto_argon2_derive_key(
+ kind: Argon2Type,
+ inputs: &RawArgon2Inputs<'_>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+ pub(super) fn crypto_aes_cbc_cipher(
+ encrypt: bool,
+ key: Span<'_, u8>,
+ input: Span<'_, u8>,
+ iv: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_aes_ctr_cipher(
+ encrypt: bool,
+ key: Span<'_, u8>,
+ input: Span<'_, u8>,
+ counter: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_aes_kw_cipher(
+ wrap: bool,
+ key: Span<'_, u8>,
+ input: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_aes_gcm_encrypt(
+ key: Span<'_, u8>,
+ plaintext: Span<'_, u8>,
+ iv: Span<'_, u8>,
+ additional_data: Span<'_, u8>,
+ tag_length: usize,
+ ciphertext: *mut c_void,
+ tag: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_aes_gcm_decrypt(
+ key: Span<'_, u8>,
+ ciphertext: Span<'_, u8>,
+ iv: Span<'_, u8>,
+ additional_data: Span<'_, u8>,
+ tag: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_aes_ocb_cipher(
+ encrypt: bool,
+ key: Span<'_, u8>,
+ input: Span<'_, u8>,
+ iv: Span<'_, u8>,
+ additional_data: Span<'_, u8>,
+ tag_length: usize,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+ pub(super) fn crypto_chacha20_poly1305_cipher(
+ encrypt: bool,
+ key: Span<'_, u8>,
+ iv: Span<'_, u8>,
+ input: Span<'_, u8>,
+ additional_data: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+ pub(super) fn crypto_asn1_allocate_key_info(structure: Asn1Structure) -> *mut c_void;
+ pub(super) fn crypto_asn1_delete_key_info(structure: Asn1Structure, key_info: *mut c_void) -> ();
+ pub(super) fn crypto_rsa_key_info_has_encryption_oid(structure: Asn1Structure, key_info: *const c_void) -> bool;
+ pub(super) fn crypto_rsa_key_info_read_key(structure: Asn1Structure, key_info: *const c_void) -> *mut c_void;
+ pub(super) fn crypto_rsa_key_is_valid(key: *const c_void, valid: &mut bool) -> bool;
+ pub(super) fn crypto_rsa_validate_public_exponent(exponent: Span<'_, u8>, modulus_length: u32) -> bool;
+ pub(super) fn crypto_rsa_validate_modulus_length(modulus_length: u32) -> bool;
+ pub(super) fn crypto_rsa_generate_key_pair(
+ modulus_length: u32,
+ exponent: Span<'_, u8>,
+ public_key: &mut *mut c_void,
+ private_key: &mut *mut c_void,
+ ) -> bool;
+ pub(super) fn crypto_rsa_export_public_exponent(
+ exponent: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_rsa_read_key_metadata(
+ key: *const c_void,
+ modulus_length: &mut u32,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_rsa_key_from_jwk_components(
+ is_private: bool,
+ components: Span<'_, Span<'_, u8>>,
+ ) -> *mut c_void;
+ pub(super) fn crypto_rsa_export_der(
+ key: *const c_void,
+ is_public: bool,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_rsa_export_jwk_integer(
+ key: *const c_void,
+ component: RsaJwkInteger,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_rsa_oaep_cipher(
+ encrypt: bool,
+ hash_kind: ShaHashKind,
+ key: *const c_void,
+ label: Span<'_, u8>,
+ input: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_rsa_pss_sign(
+ hash_kind: ShaHashKind,
+ key: *const c_void,
+ salt_length: u32,
+ message: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_rsa_pss_verify(
+ hash_kind: ShaHashKind,
+ key: *const c_void,
+ salt_length: u32,
+ message: Span<'_, u8>,
+ signature: Span<'_, u8>,
+ verified: &mut bool,
+ ) -> bool;
+ pub(super) fn crypto_rsa_pkcs1_sign(
+ hash_kind: ShaHashKind,
+ key: *const c_void,
+ message: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_rsa_pkcs1_verify(
+ hash_kind: ShaHashKind,
+ key: *const c_void,
+ message: Span<'_, u8>,
+ signature: Span<'_, u8>,
+ verified: &mut bool,
+ ) -> bool;
+ pub(super) fn crypto_ec_generate_key_pair(
+ curve: EcCurve,
+ public_key: &mut *mut c_void,
+ private_key: &mut *mut c_void,
+ ) -> bool;
+ pub(super) fn crypto_ec_sign(
+ curve: EcCurve,
+ key: *const c_void,
+ digest: Span<'_, u8>,
+ error: &mut usize,
+ r: *mut c_void,
+ s: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> u8;
+ pub(super) fn crypto_ec_verify(
+ curve: EcCurve,
+ key: *const c_void,
+ digest: Span<'_, u8>,
+ r: Span<'_, u8>,
+ s: Span<'_, u8>,
+ verified: &mut bool,
+ ) -> usize;
+ pub(super) fn crypto_ec_public_key_scalar_size(key: *const c_void) -> usize;
+ pub(super) fn crypto_ec_compute_coordinate(
+ curve: EcCurve,
+ key: *const c_void,
+ public_key: *const c_void,
+ error: &mut usize,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> u8;
+ pub(super) fn crypto_ec_key_info_has_public_key_oid(structure: Asn1Structure, key_info: *const c_void) -> bool;
+ pub(super) fn crypto_ec_key_info_parameters(
+ structure: Asn1Structure,
+ key_info: *const c_void,
+ parameters: &mut Span<'_, u32>,
+ ) -> bool;
+ pub(super) fn crypto_ec_private_key_info_parameters_match(key_info: *const c_void) -> bool;
+ pub(super) fn crypto_ec_key_info_read_key(structure: Asn1Structure, key_info: *const c_void) -> *mut c_void;
+ pub(super) fn crypto_ec_key_from_coordinates(
+ x: Span<'_, u8>,
+ y: Span<'_, u8>,
+ coord_size: usize,
+ d: OptionalBytes<'_>,
+ ) -> *mut c_void;
+ pub(super) fn crypto_ec_parse_raw_public_key(bytes: Span<'_, u8>) -> *mut c_void;
+ pub(super) fn crypto_ec_key_is_valid(curve: EcCurve, key: *const c_void, valid: &mut bool) -> bool;
+ pub(super) fn crypto_ec_export_der(
+ curve: EcCurve,
+ key: *const c_void,
+ is_public: bool,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_ec_export_uncompressed(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> bool;
+ pub(super) fn crypto_ec_export_public_coordinates(
+ curve: EcCurve,
+ key: *const c_void,
+ x: *mut c_void,
+ y: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_ec_export_private_scalar(
+ key: *const c_void,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_okp_generate_private_key(curve: OkpCurve, state: *mut c_void, receive: ReceiveBytes) -> bool;
+ pub(super) fn crypto_okp_generate_public_key(
+ curve: OkpCurve,
+ private_key: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_okp_compute_coordinate(
+ curve: OkpCurve,
+ private_key: Span<'_, u8>,
+ public_key: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_okp_sign(
+ curve: OkpCurve,
+ private_key: Span<'_, u8>,
+ message: Span<'_, u8>,
+ context: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_okp_verify(
+ curve: OkpCurve,
+ public_key: Span<'_, u8>,
+ signature: Span<'_, u8>,
+ message: Span<'_, u8>,
+ context: Span<'_, u8>,
+ verified: &mut bool,
+ ) -> usize;
+ pub(super) fn crypto_okp_key_info_has_oid(
+ curve: OkpCurve,
+ structure: Asn1Structure,
+ key_info: *const c_void,
+ ) -> bool;
+ pub(super) fn crypto_asn1_key_info_raw_key(
+ structure: Asn1Structure,
+ key_info: *const c_void,
+ bytes: &mut Span<'_, u8>,
+ ) -> ();
+ pub(super) fn crypto_asn1_octet_string_bytes(string: *const c_void, bytes: &mut Span<'_, u8>) -> ();
+ pub(super) fn crypto_okp_export_der(
+ curve: OkpCurve,
+ is_public: bool,
+ key: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_mldsa_sign(
+ size: MlDsaSize,
+ key: *const c_void,
+ message: Span<'_, u8>,
+ context: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_mldsa_verify(
+ size: MlDsaSize,
+ key: *const c_void,
+ message: Span<'_, u8>,
+ signature: Span<'_, u8>,
+ context: Span<'_, u8>,
+ verified: &mut bool,
+ ) -> bool;
+ pub(super) fn crypto_mldsa_generate_key_pair(
+ size: MlDsaSize,
+ seed: Span<'_, u8>,
+ public_key: &mut *mut c_void,
+ private_key: &mut *mut c_void,
+ ) -> usize;
+ pub(super) fn crypto_asn1_key_info_identifier(
+ structure: Asn1Structure,
+ key_info: *const c_void,
+ oid: &mut Span<'_, u32>,
+ ) -> ();
+ pub(super) fn crypto_mldsa_key_info_read_private_key(key_info: *const c_void) -> *mut c_void;
+ pub(super) fn crypto_mldsa_read_public_key(bytes: Span<'_, u8>) -> *mut c_void;
+ pub(super) fn crypto_mldsa_public_bytes(key: *const c_void, bytes: &mut Span<'_, u8>) -> ();
+ pub(super) fn crypto_mldsa_seed_bytes(key: *const c_void, bytes: &mut Span<'_, u8>) -> ();
+ pub(super) fn crypto_mldsa_export_der(
+ key: *const c_void,
+ is_public: bool,
+ oid: Span<'_, u32>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_mlkem_generate_key_pair(
+ size: MlKemSize,
+ seed: Span<'_, u8>,
+ public_key: &mut *mut c_void,
+ private_key: &mut *mut c_void,
+ ) -> usize;
+ pub(super) fn crypto_mlkem_key_info_read_private_key(key_info: *const c_void) -> *mut c_void;
+ pub(super) fn crypto_mlkem_read_public_key(bytes: Span<'_, u8>) -> *mut c_void;
+ pub(super) fn crypto_mlkem_public_bytes(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> ();
+ pub(super) fn crypto_mlkem_seed_bytes(key: *const c_void, bytes: &mut Span<'_, u8>) -> ();
+ pub(super) fn crypto_mlkem_export_der(
+ key: *const c_void,
+ is_public: bool,
+ oid: Span<'_, u32>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> bool;
+ pub(super) fn crypto_mlkem_encapsulate(
+ size: MlKemSize,
+ key: *const c_void,
+ shared_key: *mut c_void,
+ ciphertext: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+ pub(super) fn crypto_mlkem_decapsulate(
+ size: MlKemSize,
+ key: *const c_void,
+ ciphertext: Span<'_, u8>,
+ state: *mut c_void,
+ receive: ReceiveBytes,
+ ) -> usize;
+ pub(super) fn crypto_fill_with_random(bytes: SpanMut<'_, u8>);
+ pub(super) fn crypto_generate_random_uuid(state: *mut c_void, receive: ReceiveBytes);
+}
+
+#[repr(C)]
+pub(super) struct RawArgon2Inputs<'a> {
+ password: Span<'a, u8>,
+ nonce: Span<'a, u8>,
+ parallelism: u32,
+ memory: u32,
+ passes: u32,
+ version: u32,
+ secret_value: OptionalBytes<'a>,
+ associated_data: OptionalBytes<'a>,
+ tag_length: u32,
+}
+
+impl<'a> From<&Argon2Inputs<'a>> for RawArgon2Inputs<'a> {
+ fn from(inputs: &Argon2Inputs<'a>) -> Self {
+ Self {
+ password: Span::new(inputs.password),
+ nonce: Span::new(inputs.nonce),
+ memory: inputs.memory,
+ passes: inputs.passes,
+ parallelism: inputs.parallelism,
+ version: inputs.version,
+ secret_value: inputs.secret_value.into(),
+ associated_data: inputs.associated_data.into(),
+ tag_length: inputs.tag_length,
+ }
+ }
+}
diff --git a/Libraries/LibCrypto/Rust/src/key.rs b/Libraries/LibCrypto/Rust/src/key.rs
new file mode 100644
index 00000000000..8afa2d4e331
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/key.rs
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2023, stelar7 <[email protected]>
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Span;
+
+#[repr(transparent)]
+pub struct KeyHandle(NonNull<c_void>);
+
+pub struct KeyPair {
+ pub public_key: KeyHandle,
+ pub private_key: KeyHandle,
+}
+
+impl KeyPair {
+ pub(super) unsafe fn from_raw(public_key: *mut c_void, private_key: *mut c_void) -> Self {
+ // SAFETY: The caller transfers ownership of both native keys.
+ let (public_key, private_key) = unsafe { (KeyHandle::from_raw(public_key), KeyHandle::from_raw(private_key)) };
+ Self {
+ public_key: public_key.expect("LibCrypto returns a public key"),
+ private_key: private_key.expect("LibCrypto returns a private key"),
+ }
+ }
+}
+
+#[derive(Debug)]
+pub enum KeyDecodeError {
+ InvalidComponents,
+ OutOfMemory,
+}
+
+pub struct KeyComponents<'a> {
+ pub tag: u8,
+ buffers: [&'a [u8]; 8],
+ buffer_count: usize,
+ pub ec_parameters: Option<&'a [u32]>,
+ pub has_ec_public_key: bool,
+}
+
+impl<'a> KeyComponents<'a> {
+ pub fn buffers(&self) -> &[&'a [u8]] {
+ &self.buffers[..self.buffer_count]
+ }
+}
+
+#[repr(C)]
+struct RawKeyComponents<'a> {
+ tag: u8,
+ buffers: [Span<'a, u8>; 8],
+ buffer_count: usize,
+ has_ec_parameters: bool,
+ ec_parameters: Span<'a, u32>,
+ has_ec_public_key: bool,
+}
+
+unsafe extern "C" {
+ fn crypto_key_destroy_handle(key: *mut c_void);
+ fn crypto_key_create_byte_handle(bytes: Span<'_, u8>) -> *mut c_void;
+ fn crypto_key_create_okp_handle(is_private: bool, bytes: Span<'_, u8>) -> *mut c_void;
+ fn crypto_key_byte_handle_bytes(key: *const c_void, bytes: &mut Span<'_, u8>);
+ fn crypto_key_okp_handle_bytes(key: *const c_void, bytes: &mut Span<'_, u8>);
+ fn crypto_key_encode_handle(
+ key: *const c_void,
+ state: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void, *const RawKeyComponents<'_>),
+ );
+ fn crypto_key_decode_handle(fields: &RawKeyComponents<'_>, key: &mut *mut c_void) -> bool;
+}
+
+impl KeyHandle {
+ /// # Safety
+ ///
+ /// A non-null pointer must transfer ownership of a LibCrypto key handle.
+ pub unsafe fn from_raw(key: *mut c_void) -> Option<Self> {
+ NonNull::new(key).map(Self)
+ }
+
+ pub fn as_raw(&self) -> *mut c_void {
+ self.0.as_ptr()
+ }
+
+ pub fn from_secret_bytes(bytes: &[u8]) -> Self {
+ // SAFETY: The input is borrowed for the copy.
+ let key = unsafe { crypto_key_create_byte_handle(Span::new(bytes)) };
+ // SAFETY: The native call transfers ownership of the key.
+ unsafe { Self::from_raw(key) }.expect("LibCrypto returns a secret key")
+ }
+
+ pub fn from_okp_bytes(is_private: bool, bytes: &[u8]) -> Self {
+ // SAFETY: The input is borrowed for the copy.
+ let key = unsafe { crypto_key_create_okp_handle(is_private, Span::new(bytes)) };
+ // SAFETY: The native call transfers ownership of the key.
+ unsafe { Self::from_raw(key) }.expect("LibCrypto returns an OKP key")
+ }
+
+ pub fn secret_bytes(&self) -> &[u8] {
+ let mut bytes = Span::default();
+ // SAFETY: The key owns the returned bytes.
+ unsafe { crypto_key_byte_handle_bytes(self.as_raw(), &mut bytes) };
+ bytes.as_slice()
+ }
+
+ pub fn okp_bytes(&self) -> &[u8] {
+ let mut bytes = Span::default();
+ // SAFETY: The key owns the returned bytes.
+ unsafe { crypto_key_okp_handle_bytes(self.as_raw(), &mut bytes) };
+ bytes.as_slice()
+ }
+
+ pub fn with_components<R>(&self, callback: impl FnOnce(KeyComponents<'_>) -> R) -> R {
+ fn run<F: FnOnce(KeyComponents<'_>) -> R, R>(key: &KeyHandle, callback: F) -> R {
+ unsafe extern "C" fn receive<F: FnOnce(KeyComponents<'_>) -> R, R>(
+ state: *mut c_void,
+ fields: *const RawKeyComponents<'_>,
+ ) {
+ // SAFETY: LibCrypto invokes the callback synchronously with the live slots.
+ let (state, fields) = unsafe { (&mut *state.cast::<(Option<F>, Option<R>)>(), &*fields) };
+ let callback = state.0.take().expect("LibCrypto supplies the components once");
+ state.1 = Some(callback(KeyComponents {
+ tag: fields.tag,
+ buffers: fields.buffers.map(Span::as_slice),
+ buffer_count: fields.buffer_count,
+ ec_parameters: fields.has_ec_parameters.then(|| fields.ec_parameters.as_slice()),
+ has_ec_public_key: fields.has_ec_public_key,
+ }));
+ }
+ let mut state: (Option<F>, Option<R>) = (Some(callback), None);
+ // SAFETY: The key and callback state are live for the synchronous native call.
+ unsafe { crypto_key_encode_handle(key.as_raw(), core::ptr::from_mut(&mut state).cast(), receive::<F, R>) };
+ state.1.expect("LibCrypto supplies the key components")
+ }
+ run(self, callback)
+ }
+
+ pub fn from_components(
+ tag: u8,
+ buffers: &[&[u8]],
+ ec_parameters: Option<&[u32]>,
+ has_ec_public_key: bool,
+ ) -> Result<Self, KeyDecodeError> {
+ let expected = match tag {
+ 0 | 5 | 7 | 9 | 10 => 1,
+ 1 | 3 => 2,
+ 2 => 8,
+ 4 if has_ec_public_key => 3,
+ 4 => 1,
+ 6 | 8 => 3,
+ _ => return Err(KeyDecodeError::InvalidComponents),
+ };
+ if buffers.len() != expected || (tag != 4 && (ec_parameters.is_some() || has_ec_public_key)) {
+ return Err(KeyDecodeError::InvalidComponents);
+ }
+ let mut spans = [Span::default(); 8];
+ for (span, bytes) in spans.iter_mut().zip(buffers) {
+ *span = Span::new(bytes);
+ }
+ let fields = RawKeyComponents {
+ tag,
+ buffers: spans,
+ buffer_count: buffers.len(),
+ has_ec_parameters: ec_parameters.is_some(),
+ ec_parameters: Span::new(ec_parameters.unwrap_or_default()),
+ has_ec_public_key,
+ };
+ let mut key = core::ptr::null_mut();
+ // SAFETY: The validated fields and output slot are live for the call.
+ if !unsafe { crypto_key_decode_handle(&fields, &mut key) } {
+ return Err(KeyDecodeError::OutOfMemory);
+ }
+ // SAFETY: Success transfers ownership of the native key.
+ Ok(unsafe { Self::from_raw(key) }.expect("LibCrypto returns the decoded key"))
+ }
+}
+
+impl Drop for KeyHandle {
+ fn drop(&mut self) {
+ // SAFETY: This value owns the native handle.
+ unsafe { crypto_key_destroy_handle(self.as_raw()) };
+ }
+}
diff --git a/Libraries/LibCrypto/Rust/src/key_info.rs b/Libraries/LibCrypto/Rust/src/key_info.rs
new file mode 100644
index 00000000000..3947349661e
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/key_info.rs
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2024, stelar7 <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::{Span, Utf16String};
+
+use super::{Asn1Structure, KeyHandle, OkpCurve, ffi, result_from_error};
+
+pub enum Asn1Value<'a> {
+ KeyInfo(KeyInfo),
+ OctetString(&'a [u8]),
+}
+
+pub struct KeyInfo {
+ structure: Asn1Structure,
+ ptr: NonNull<c_void>,
+}
+
+pub fn decode_asn1_structure(data: &[u8], structure: Asn1Structure) -> Result<(Asn1Value<'_>, bool), Utf16String> {
+ // SAFETY: LibCrypto allocates storage of the selected structure.
+ let raw = unsafe { ffi::crypto_asn1_allocate_key_info(structure) };
+ let native = KeyInfo {
+ structure,
+ ptr: NonNull::new(raw).expect("LibCrypto returns the ASN.1 structure"),
+ };
+ let mut all_consumed = false;
+ // SAFETY: The input and native storage of the selected structure live for the call.
+ let status = unsafe {
+ ffi::crypto_decode_asn1_structure(Span::new(data), structure, native.ptr.as_ptr(), &mut all_consumed)
+ };
+ result_from_error(status)?;
+ let value = if matches!(structure, Asn1Structure::OctetString) {
+ let mut bytes = Span::default();
+ // SAFETY: This native value is an octet string that borrows its bytes from data.
+ unsafe { ffi::crypto_asn1_octet_string_bytes(native.ptr.as_ptr(), &mut bytes) };
+ Asn1Value::OctetString(bytes.as_slice())
+ } else {
+ Asn1Value::KeyInfo(native)
+ };
+ Ok((value, all_consumed))
+}
+
+impl KeyInfo {
+ pub fn has_rsa_encryption_oid(&self) -> bool {
+ // SAFETY: The native value matches its structure tag.
+ unsafe { ffi::crypto_rsa_key_info_has_encryption_oid(self.structure, self.ptr.as_ptr()) }
+ }
+
+ pub fn rsa_key(&self) -> KeyHandle {
+ // SAFETY: The native value matches its structure tag.
+ let raw = unsafe { ffi::crypto_rsa_key_info_read_key(self.structure, self.ptr.as_ptr()) };
+ // SAFETY: The native call transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns an RSA key")
+ }
+
+ pub fn has_ec_public_key_oid(&self) -> bool {
+ // SAFETY: The native value matches its structure tag.
+ unsafe { ffi::crypto_ec_key_info_has_public_key_oid(self.structure, self.ptr.as_ptr()) }
+ }
+
+ pub fn ec_parameters(&self) -> Option<&[u32]> {
+ let mut parameters = Span::default();
+ // SAFETY: The native value matches its structure tag and owns the parameters.
+ let has_parameters =
+ unsafe { ffi::crypto_ec_key_info_parameters(self.structure, self.ptr.as_ptr(), &mut parameters) };
+ has_parameters.then(|| parameters.as_slice())
+ }
+
+ pub fn ec_private_parameters_match(&self) -> bool {
+ assert!(matches!(self.structure, Asn1Structure::PrivateKeyInfo));
+ // SAFETY: This is a native private key info value.
+ unsafe { ffi::crypto_ec_private_key_info_parameters_match(self.ptr.as_ptr()) }
+ }
+
+ pub fn ec_key(&self) -> KeyHandle {
+ // SAFETY: The native value matches its structure tag.
+ let raw = unsafe { ffi::crypto_ec_key_info_read_key(self.structure, self.ptr.as_ptr()) };
+ // SAFETY: The native call transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns an EC key")
+ }
+
+ pub fn has_okp_oid(&self, curve: OkpCurve) -> bool {
+ // SAFETY: The native value matches its structure tag.
+ unsafe { ffi::crypto_okp_key_info_has_oid(curve, self.structure, self.ptr.as_ptr()) }
+ }
+
+ pub fn raw_key(&self) -> &[u8] {
+ let mut bytes = Span::default();
+ // SAFETY: The native value matches its structure tag and owns the bytes.
+ unsafe { ffi::crypto_asn1_key_info_raw_key(self.structure, self.ptr.as_ptr(), &mut bytes) };
+ bytes.as_slice()
+ }
+
+ pub fn oid(&self) -> &[u32] {
+ let mut oid = Span::default();
+ // SAFETY: The native value matches its structure tag and owns the identifier.
+ unsafe { ffi::crypto_asn1_key_info_identifier(self.structure, self.ptr.as_ptr(), &mut oid) };
+ oid.as_slice()
+ }
+
+ pub fn mldsa_private_key(&self) -> KeyHandle {
+ assert!(matches!(self.structure, Asn1Structure::PrivateKeyInfo));
+ // SAFETY: This is a native private key info value.
+ let raw = unsafe { ffi::crypto_mldsa_key_info_read_private_key(self.ptr.as_ptr()) };
+ // SAFETY: The native call transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns an ML-DSA key")
+ }
+
+ pub fn mlkem_private_key(&self) -> KeyHandle {
+ assert!(matches!(self.structure, Asn1Structure::PrivateKeyInfo));
+ // SAFETY: This is a native private key info value.
+ let raw = unsafe { ffi::crypto_mlkem_key_info_read_private_key(self.ptr.as_ptr()) };
+ // SAFETY: The native call transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns an ML-KEM key")
+ }
+}
+
+impl Drop for KeyInfo {
+ fn drop(&mut self) {
+ // SAFETY: This value owns the native structure.
+ unsafe { ffi::crypto_asn1_delete_key_info(self.structure, self.ptr.as_ptr()) };
+ }
+}
diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rs
new file mode 100644
index 00000000000..e73d58e7d1c
--- /dev/null
+++ b/Libraries/LibCrypto/Rust/src/lib.rs
@@ -0,0 +1,1029 @@
+/*
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2024, stelar7 <[email protected]>
+ * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2024, Andreas Kling <[email protected]>
+ * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+
+use ak::{Span, SpanMut, Utf16String};
+
+mod ffi;
+mod key;
+mod key_info;
+
+pub use key::{KeyComponents, KeyDecodeError, KeyHandle, KeyPair};
+pub use key_info::{Asn1Value, KeyInfo, decode_asn1_structure};
+
+use ffi::ReceiveBytes;
+
+#[derive(Debug)]
+pub struct BackendError;
+
+#[repr(i32)]
+pub enum ShaHashKind {
+ Sha1 = 4,
+ Sha256,
+ Sha384,
+ Sha512,
+ Sha3_256,
+ Sha3_384,
+ Sha3_512,
+}
+
+#[repr(i32)]
+pub enum CShakeKind {
+ CShake128,
+ CShake256,
+}
+
+#[repr(i32)]
+#[derive(Clone, Copy)]
+pub enum KmacKind {
+ Kmac128,
+ Kmac256,
+}
+
+#[repr(i32)]
+pub enum Argon2Type {
+ Argon2d,
+ Argon2i,
+ Argon2id,
+}
+
+#[derive(Clone, Copy)]
+#[repr(u8)]
+pub enum EcCurve {
+ P256,
+ P384,
+ P521,
+}
+
+#[derive(Clone, Copy)]
+#[repr(u8)]
+pub enum OkpCurve {
+ Ed25519,
+ Ed448,
+ X25519,
+ X448,
+}
+
+#[repr(u8)]
+pub enum RsaJwkInteger {
+ Modulus,
+ PublicExponent,
+ PrivateExponent,
+ Prime1,
+ Prime2,
+ Exponent1,
+ Exponent2,
+ Coefficient,
+}
+
+#[derive(Clone, Copy)]
+#[repr(i32)]
+pub enum MlDsaSize {
+ MlDsa44,
+ MlDsa65,
+ MlDsa87,
+}
+
+#[derive(Clone, Copy)]
+#[repr(i32)]
+pub enum MlKemSize {
+ MlKem512,
+ MlKem768,
+ MlKem1024,
+}
+
+#[derive(Clone, Copy)]
+#[repr(u8)]
+pub enum Asn1Structure {
+ SubjectPublicKeyInfo,
+ PrivateKeyInfo,
+ OctetString,
+}
+
+pub struct Argon2Inputs<'a> {
+ pub password: &'a [u8],
+ pub nonce: &'a [u8],
+ pub memory: u32,
+ pub passes: u32,
+ pub parallelism: u32,
+ pub version: u32,
+ pub secret_value: Option<&'a [u8]>,
+ pub associated_data: Option<&'a [u8]>,
+ pub tag_length: u32,
+}
+
+unsafe extern "C" fn receive_bytes(state: *mut c_void, bytes: Span<'_, u8>) {
+ // SAFETY: The native call supplies the output slot and lends the bytes during the callback.
+ unsafe { *state.cast::<Vec<u8>>() = bytes.as_slice().to_vec() };
+}
+
+fn receive_native_bytes<T>(call: impl FnOnce(*mut c_void, ReceiveBytes) -> T) -> (T, Vec<u8>) {
+ let mut bytes = Vec::new();
+ let status = call(core::ptr::from_mut(&mut bytes).cast(), receive_bytes);
+ (status, bytes)
+}
+
+fn result_from_error(raw: usize) -> Result<(), Utf16String> {
+ if raw == 0 {
+ Ok(())
+ } else {
+ // SAFETY: A nonzero error returned by LibCrypto transfers an owned string.
+ Err(unsafe { Utf16String::from_raw_owned(raw) })
+ }
+}
+
+pub fn fill_with_random(bytes: &mut [u8]) {
+ // SAFETY: The native function writes into the span during the call.
+ unsafe { ffi::crypto_fill_with_random(SpanMut::new(bytes)) };
+}
+
+pub fn generate_random_uuid() -> Utf16String {
+ // SAFETY: The native function invokes the receiver synchronously.
+ let ((), bytes) =
+ receive_native_bytes(|state, receive| unsafe { ffi::crypto_generate_random_uuid(state, receive) });
+ Utf16String::from_ascii(&bytes)
+}
+
+#[derive(Debug)]
+pub enum Base64DecodeError {
+ OutOfMemory,
+ InvalidBase64(Utf16String),
+ NonAscii,
+}
+
+pub fn encode_base64url(bytes: &[u8]) -> Result<Utf16String, i32> {
+ // SAFETY: The input is borrowed and the receiver is invoked synchronously.
+ let (status, encoded) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_encode_base64url(Span::new(bytes), receive, state)
+ });
+ if status != 0 {
+ return Err(status);
+ }
+ Ok(Utf16String::from_ascii(&encoded))
+}
+
+pub fn decode_base64url(input: &Utf16String) -> Result<Vec<u8>, Base64DecodeError> {
+ use ak::Utf16StringUnits;
+ let is_ascii = match input.as_units() {
+ Utf16StringUnits::Ascii(_) => true,
+ Utf16StringUnits::Latin1(units) => units.is_ascii(),
+ Utf16StringUnits::Utf16(units) => units.iter().all(|&unit| unit <= 0x7f),
+ };
+ if !is_ascii {
+ return Err(Base64DecodeError::NonAscii);
+ }
+ let mut message = 0;
+ // SAFETY: The string and output slots are live during the call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_decode_base64url(input.raw_identity(), state, receive, &mut message)
+ });
+ match status {
+ ffi::Base64Status::Success => Ok(bytes),
+ ffi::Base64Status::OutOfMemory => Err(Base64DecodeError::OutOfMemory),
+ ffi::Base64Status::InvalidBase64 => {
+ // SAFETY: The decoder transfers an owned diagnostic string for this status.
+ Err(Base64DecodeError::InvalidBase64(unsafe {
+ Utf16String::from_raw_owned(message)
+ }))
+ }
+ ffi::Base64Status::NonAscii => Err(Base64DecodeError::NonAscii),
+ }
+}
+
+pub fn sha_digest(kind: ShaHashKind, data: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) =
+ receive_native_bytes(|state, receive| unsafe { ffi::crypto_sha_digest(kind, Span::new(data), state, receive) });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn cshake_validate_parameters(
+ output_length: u32,
+ customization: Option<&[u8]>,
+ function_name: Option<&[u8]>,
+) -> Result<(), Utf16String> {
+ // SAFETY: The input is borrowed for the call.
+ result_from_error(unsafe {
+ ffi::crypto_cshake_validate_parameters(output_length, customization.into(), function_name.into())
+ })
+}
+
+pub fn cshake_digest(
+ kind: CShakeKind,
+ data: &[u8],
+ output_length: u32,
+ customization: Option<&[u8]>,
+ function_name: Option<&[u8]>,
+) -> Result<Vec<u8>, Utf16String> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_cshake_digest(
+ kind,
+ Span::new(data),
+ output_length,
+ customization.into(),
+ function_name.into(),
+ state,
+ receive,
+ )
+ });
+ result_from_error(status)?;
+ Ok(bytes)
+}
+
+pub fn hmac_sign(kind: ShaHashKind, key: &[u8], message: &[u8]) -> Vec<u8> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let ((), bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_hmac_sign(kind, Span::new(key), Span::new(message), state, receive);
+ });
+ bytes
+}
+
+pub fn timing_safe_compare(left: &[u8], right: &[u8]) -> bool {
+ // SAFETY: The input is borrowed for the call.
+ unsafe { ffi::crypto_timing_safe_compare(Span::new(left), Span::new(right)) }
+}
+
+pub fn kmac_default_key_length(kind: KmacKind) -> u32 {
+ // SAFETY: The input is borrowed for the call.
+ unsafe { ffi::crypto_kmac_default_key_length(kind) }
+}
+
+pub fn kmac_validate_parameters(output_length: u32, customization: Option<&[u8]>) -> bool {
+ // SAFETY: The input is borrowed for the call.
+ unsafe { ffi::crypto_kmac_validate_parameters(output_length, customization.into()) }
+}
+
+pub fn kmac_sign(
+ kind: KmacKind,
+ key: &[u8],
+ message: &[u8],
+ output_length: u32,
+ customization: Option<&[u8]>,
+) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_kmac_sign(
+ kind,
+ Span::new(key),
+ Span::new(message),
+ output_length,
+ customization.into(),
+ state,
+ receive,
+ )
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn hash_digest_size(kind: ShaHashKind) -> usize {
+ // SAFETY: The input is borrowed for the call.
+ unsafe { ffi::crypto_hash_digest_size(kind) }
+}
+
+pub fn hkdf_derive_key(
+ kind: ShaHashKind,
+ salt: &[u8],
+ key: &[u8],
+ info: &[u8],
+ length: u32,
+) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_hkdf_derive_key(
+ kind,
+ Span::new(salt),
+ Span::new(key),
+ Span::new(info),
+ length,
+ state,
+ receive,
+ )
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn pbkdf2_derive_key(
+ kind: ShaHashKind,
+ password: &[u8],
+ salt: &[u8],
+ iterations: u32,
+ length: u32,
+) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_pbkdf2_derive_key(
+ kind,
+ Span::new(password),
+ Span::new(salt),
+ iterations,
+ length,
+ state,
+ receive,
+ )
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn argon2_validate_parameters(nonce: &[u8]) -> Result<(), Utf16String> {
+ // SAFETY: The input is borrowed for the call.
+ result_from_error(unsafe { ffi::crypto_argon2_validate_parameters(Span::new(nonce)) })
+}
+
+pub fn argon2_derive_key(kind: Argon2Type, inputs: &Argon2Inputs<'_>) -> Result<Vec<u8>, Utf16String> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_argon2_derive_key(kind, &inputs.into(), state, receive)
+ });
+ result_from_error(status)?;
+ Ok(bytes)
+}
+
+pub fn aes_cbc_cipher(encrypt: bool, key: &[u8], input: &[u8], iv: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_aes_cbc_cipher(encrypt, Span::new(key), Span::new(input), Span::new(iv), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn aes_ctr_cipher(encrypt: bool, key: &[u8], input: &[u8], counter: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_aes_ctr_cipher(
+ encrypt,
+ Span::new(key),
+ Span::new(input),
+ Span::new(counter),
+ state,
+ receive,
+ )
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn aes_kw_cipher(wrap: bool, key: &[u8], input: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_aes_kw_cipher(wrap, Span::new(key), Span::new(input), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn aes_gcm_encrypt(
+ key: &[u8],
+ plaintext: &[u8],
+ iv: &[u8],
+ additional_data: &[u8],
+ tag_length: usize,
+) -> Result<(Vec<u8>, Vec<u8>), BackendError> {
+ let mut first = Vec::new();
+ let mut second = Vec::new();
+ // SAFETY: Inputs and both output slots are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_aes_gcm_encrypt(
+ Span::new(key),
+ Span::new(plaintext),
+ Span::new(iv),
+ Span::new(additional_data),
+ tag_length,
+ core::ptr::from_mut(&mut first).cast(),
+ core::ptr::from_mut(&mut second).cast(),
+ receive_bytes,
+ )
+ };
+ status.then_some(()).ok_or(BackendError)?;
+ Ok((first, second))
+}
+
+pub fn aes_gcm_decrypt(
+ key: &[u8],
+ ciphertext: &[u8],
+ iv: &[u8],
+ additional_data: &[u8],
+ tag: &[u8],
+) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_aes_gcm_decrypt(
+ Span::new(key),
+ Span::new(ciphertext),
+ Span::new(iv),
+ Span::new(additional_data),
+ Span::new(tag),
+ state,
+ receive,
+ )
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn aes_ocb_cipher(
+ encrypt: bool,
+ key: &[u8],
+ input: &[u8],
+ iv: &[u8],
+ additional_data: &[u8],
+ tag_length: usize,
+) -> Result<Vec<u8>, Utf16String> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_aes_ocb_cipher(
+ encrypt,
+ Span::new(key),
+ Span::new(input),
+ Span::new(iv),
+ Span::new(additional_data),
+ tag_length,
+ state,
+ receive,
+ )
+ });
+ result_from_error(status)?;
+ Ok(bytes)
+}
+
+pub fn chacha20_poly1305_cipher(
+ encrypt: bool,
+ key: &[u8],
+ iv: &[u8],
+ input: &[u8],
+ additional_data: &[u8],
+) -> Result<Vec<u8>, Utf16String> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_chacha20_poly1305_cipher(
+ encrypt,
+ Span::new(key),
+ Span::new(iv),
+ Span::new(input),
+ Span::new(additional_data),
+ state,
+ receive,
+ )
+ });
+ result_from_error(status)?;
+ Ok(bytes)
+}
+
+pub fn rsa_key_is_valid(key: &KeyHandle) -> Result<bool, BackendError> {
+ let mut value = false;
+ // SAFETY: Inputs and output are borrowed for the call.
+ let status = unsafe { ffi::crypto_rsa_key_is_valid(key.as_raw(), &mut value) };
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(value)
+}
+
+pub fn rsa_validate_public_exponent(exponent: &[u8], modulus_length: u32) -> bool {
+ // SAFETY: The input is borrowed for the call.
+ unsafe { ffi::crypto_rsa_validate_public_exponent(Span::new(exponent), modulus_length) }
+}
+
+pub fn rsa_validate_modulus_length(modulus_length: u32) -> bool {
+ // SAFETY: The input is borrowed for the call.
+ unsafe { ffi::crypto_rsa_validate_modulus_length(modulus_length) }
+}
+
+pub fn rsa_generate_key_pair(modulus_length: u32, exponent: &[u8]) -> Result<KeyPair, BackendError> {
+ let mut public_key = core::ptr::null_mut();
+ let mut private_key = core::ptr::null_mut();
+ // SAFETY: Inputs and output slots are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_rsa_generate_key_pair(modulus_length, Span::new(exponent), &mut public_key, &mut private_key)
+ };
+ status.then_some(()).ok_or(BackendError)?;
+ // SAFETY: Success transfers ownership of both keys.
+ Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
+}
+
+pub fn rsa_export_public_exponent(exponent: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_rsa_export_public_exponent(Span::new(exponent), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn rsa_export_der(key: &KeyHandle, is_public: bool) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_rsa_export_der(key.as_raw(), is_public, state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn rsa_export_jwk_integer(key: &KeyHandle, component: RsaJwkInteger) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_rsa_export_jwk_integer(key.as_raw(), component, state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn rsa_oaep_cipher(
+ encrypt: bool,
+ hash_kind: ShaHashKind,
+ key: &KeyHandle,
+ label: &[u8],
+ input: &[u8],
+) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_rsa_oaep_cipher(
+ encrypt,
+ hash_kind,
+ key.as_raw(),
+ Span::new(label),
+ Span::new(input),
+ state,
+ receive,
+ )
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn rsa_pss_sign(
+ hash_kind: ShaHashKind,
+ key: &KeyHandle,
+ salt_length: u32,
+ message: &[u8],
+) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_rsa_pss_sign(hash_kind, key.as_raw(), salt_length, Span::new(message), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn rsa_pss_verify(
+ hash_kind: ShaHashKind,
+ key: &KeyHandle,
+ salt_length: u32,
+ message: &[u8],
+ signature: &[u8],
+) -> Result<bool, BackendError> {
+ let mut value = false;
+ // SAFETY: Inputs and output are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_rsa_pss_verify(
+ hash_kind,
+ key.as_raw(),
+ salt_length,
+ Span::new(message),
+ Span::new(signature),
+ &mut value,
+ )
+ };
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(value)
+}
+
+pub fn rsa_pkcs1_sign(hash_kind: ShaHashKind, key: &KeyHandle, message: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_rsa_pkcs1_sign(hash_kind, key.as_raw(), Span::new(message), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn rsa_pkcs1_verify(
+ hash_kind: ShaHashKind,
+ key: &KeyHandle,
+ message: &[u8],
+ signature: &[u8],
+) -> Result<bool, BackendError> {
+ let mut value = false;
+ // SAFETY: Inputs and output are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_rsa_pkcs1_verify(
+ hash_kind,
+ key.as_raw(),
+ Span::new(message),
+ Span::new(signature),
+ &mut value,
+ )
+ };
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(value)
+}
+
+pub fn ec_generate_key_pair(curve: EcCurve) -> Result<KeyPair, BackendError> {
+ let mut public_key = core::ptr::null_mut();
+ let mut private_key = core::ptr::null_mut();
+ // SAFETY: Inputs and output slots are borrowed for the call.
+ let status = unsafe { ffi::crypto_ec_generate_key_pair(curve, &mut public_key, &mut private_key) };
+ status.then_some(()).ok_or(BackendError)?;
+ // SAFETY: Success transfers ownership of both keys.
+ Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
+}
+
+pub fn ec_verify(curve: EcCurve, key: &KeyHandle, digest: &[u8], r: &[u8], s: &[u8]) -> Result<bool, Utf16String> {
+ let mut value = false;
+ // SAFETY: Inputs and output are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_ec_verify(
+ curve,
+ key.as_raw(),
+ Span::new(digest),
+ Span::new(r),
+ Span::new(s),
+ &mut value,
+ )
+ };
+ result_from_error(status)?;
+ Ok(value)
+}
+
+pub fn ec_public_key_scalar_size(key: &KeyHandle) -> usize {
+ // SAFETY: The input is borrowed for the call.
+ unsafe { ffi::crypto_ec_public_key_scalar_size(key.as_raw()) }
+}
+
+pub fn ec_key_from_coordinates(x: &[u8], y: &[u8], coord_size: usize, d: Option<&[u8]>) -> KeyHandle {
+ // SAFETY: The input is borrowed for the call.
+ let raw = unsafe { ffi::crypto_ec_key_from_coordinates(Span::new(x), Span::new(y), coord_size, d.into()) };
+ // SAFETY: The native operation transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns a key")
+}
+
+pub fn ec_parse_raw_public_key(bytes: &[u8]) -> Option<KeyHandle> {
+ // SAFETY: The input is borrowed for the call.
+ let raw = unsafe { ffi::crypto_ec_parse_raw_public_key(Span::new(bytes)) };
+ // SAFETY: The native operation transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }
+}
+
+pub fn ec_key_is_valid(curve: EcCurve, key: &KeyHandle) -> Result<bool, BackendError> {
+ let mut value = false;
+ // SAFETY: Inputs and output are borrowed for the call.
+ let status = unsafe { ffi::crypto_ec_key_is_valid(curve, key.as_raw(), &mut value) };
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(value)
+}
+
+pub fn ec_export_der(curve: EcCurve, key: &KeyHandle, is_public: bool) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_ec_export_der(curve, key.as_raw(), is_public, state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn ec_export_uncompressed(key: &KeyHandle) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_ec_export_uncompressed(key.as_raw(), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn ec_export_public_coordinates(curve: EcCurve, key: &KeyHandle) -> Result<(Vec<u8>, Vec<u8>), BackendError> {
+ let mut first = Vec::new();
+ let mut second = Vec::new();
+ // SAFETY: Inputs and both output slots are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_ec_export_public_coordinates(
+ curve,
+ key.as_raw(),
+ core::ptr::from_mut(&mut first).cast(),
+ core::ptr::from_mut(&mut second).cast(),
+ receive_bytes,
+ )
+ };
+ status.then_some(()).ok_or(BackendError)?;
+ Ok((first, second))
+}
+
+pub fn ec_export_private_scalar(key: &KeyHandle) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_ec_export_private_scalar(key.as_raw(), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn okp_generate_private_key(curve: OkpCurve) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) =
+ receive_native_bytes(|state, receive| unsafe { ffi::crypto_okp_generate_private_key(curve, state, receive) });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn okp_generate_public_key(curve: OkpCurve, private_key: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_okp_generate_public_key(curve, Span::new(private_key), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn okp_compute_coordinate(curve: OkpCurve, private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_okp_compute_coordinate(curve, Span::new(private_key), Span::new(public_key), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn okp_sign(curve: OkpCurve, private_key: &[u8], message: &[u8], context: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_okp_sign(
+ curve,
+ Span::new(private_key),
+ Span::new(message),
+ Span::new(context),
+ state,
+ receive,
+ )
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn okp_verify(
+ curve: OkpCurve,
+ public_key: &[u8],
+ signature: &[u8],
+ message: &[u8],
+ context: &[u8],
+) -> Result<bool, Utf16String> {
+ let mut value = false;
+ // SAFETY: Inputs and output are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_okp_verify(
+ curve,
+ Span::new(public_key),
+ Span::new(signature),
+ Span::new(message),
+ Span::new(context),
+ &mut value,
+ )
+ };
+ result_from_error(status)?;
+ Ok(value)
+}
+
+pub fn okp_export_der(curve: OkpCurve, is_public: bool, key: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_okp_export_der(curve, is_public, Span::new(key), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn mldsa_sign(size: MlDsaSize, key: &KeyHandle, message: &[u8], context: &[u8]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_mldsa_sign(
+ size,
+ key.as_raw(),
+ Span::new(message),
+ Span::new(context),
+ state,
+ receive,
+ )
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn mldsa_verify(
+ size: MlDsaSize,
+ key: &KeyHandle,
+ message: &[u8],
+ signature: &[u8],
+ context: &[u8],
+) -> Result<bool, BackendError> {
+ let mut value = false;
+ // SAFETY: Inputs and output are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_mldsa_verify(
+ size,
+ key.as_raw(),
+ Span::new(message),
+ Span::new(signature),
+ Span::new(context),
+ &mut value,
+ )
+ };
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(value)
+}
+
+pub fn mldsa_generate_key_pair(size: MlDsaSize, seed: &[u8]) -> Result<KeyPair, Utf16String> {
+ let mut public_key = core::ptr::null_mut();
+ let mut private_key = core::ptr::null_mut();
+ // SAFETY: Inputs and output slots are borrowed for the call.
+ let status =
+ unsafe { ffi::crypto_mldsa_generate_key_pair(size, Span::new(seed), &mut public_key, &mut private_key) };
+ result_from_error(status)?;
+ // SAFETY: Success transfers ownership of both keys.
+ Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
+}
+
+pub fn mldsa_read_public_key(bytes: &[u8]) -> KeyHandle {
+ // SAFETY: The input is borrowed for the call.
+ let raw = unsafe { ffi::crypto_mldsa_read_public_key(Span::new(bytes)) };
+ // SAFETY: The native operation transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns a key")
+}
+
+pub fn mldsa_public_bytes(key: &KeyHandle) -> &[u8] {
+ let mut bytes = Span::default();
+ // SAFETY: The key owns the bytes returned by the native call.
+ unsafe { ffi::crypto_mldsa_public_bytes(key.as_raw(), &mut bytes) };
+ bytes.as_slice()
+}
+
+pub fn mldsa_seed_bytes(key: &KeyHandle) -> &[u8] {
+ let mut bytes = Span::default();
+ // SAFETY: The key owns the bytes returned by the native call.
+ unsafe { ffi::crypto_mldsa_seed_bytes(key.as_raw(), &mut bytes) };
+ bytes.as_slice()
+}
+
+pub fn mldsa_export_der(key: &KeyHandle, is_public: bool, oid: &[u32]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_mldsa_export_der(key.as_raw(), is_public, Span::new(oid), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn mlkem_generate_key_pair(size: MlKemSize, seed: &[u8]) -> Result<KeyPair, Utf16String> {
+ let mut public_key = core::ptr::null_mut();
+ let mut private_key = core::ptr::null_mut();
+ // SAFETY: Inputs and output slots are borrowed for the call.
+ let status =
+ unsafe { ffi::crypto_mlkem_generate_key_pair(size, Span::new(seed), &mut public_key, &mut private_key) };
+ result_from_error(status)?;
+ // SAFETY: Success transfers ownership of both keys.
+ Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
+}
+
+pub fn mlkem_read_public_key(bytes: &[u8]) -> KeyHandle {
+ // SAFETY: The input is borrowed for the call.
+ let raw = unsafe { ffi::crypto_mlkem_read_public_key(Span::new(bytes)) };
+ // SAFETY: The native operation transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }.expect("LibCrypto returns a key")
+}
+
+pub fn mlkem_public_bytes(key: &KeyHandle) -> Vec<u8> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let ((), bytes) =
+ receive_native_bytes(|state, receive| unsafe { ffi::crypto_mlkem_public_bytes(key.as_raw(), state, receive) });
+ bytes
+}
+
+pub fn mlkem_seed_bytes(key: &KeyHandle) -> &[u8] {
+ let mut bytes = Span::default();
+ // SAFETY: The key owns the bytes returned by the native call.
+ unsafe { ffi::crypto_mlkem_seed_bytes(key.as_raw(), &mut bytes) };
+ bytes.as_slice()
+}
+
+pub fn mlkem_export_der(key: &KeyHandle, is_public: bool, oid: &[u32]) -> Result<Vec<u8>, BackendError> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_mlkem_export_der(key.as_raw(), is_public, Span::new(oid), state, receive)
+ });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+pub fn mlkem_encapsulate(size: MlKemSize, key: &KeyHandle) -> Result<(Vec<u8>, Vec<u8>), Utf16String> {
+ let mut first = Vec::new();
+ let mut second = Vec::new();
+ // SAFETY: Inputs and both output slots are borrowed for the call.
+ let status = unsafe {
+ ffi::crypto_mlkem_encapsulate(
+ size,
+ key.as_raw(),
+ core::ptr::from_mut(&mut first).cast(),
+ core::ptr::from_mut(&mut second).cast(),
+ receive_bytes,
+ )
+ };
+ result_from_error(status)?;
+ Ok((first, second))
+}
+
+pub fn mlkem_decapsulate(size: MlKemSize, key: &KeyHandle, ciphertext: &[u8]) -> Result<Vec<u8>, Utf16String> {
+ // SAFETY: Inputs and output are borrowed for the synchronous native call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_mlkem_decapsulate(size, key.as_raw(), Span::new(ciphertext), state, receive)
+ });
+ result_from_error(status)?;
+ Ok(bytes)
+}
+
+pub fn public_key_for_private_key(
+ key: &KeyHandle,
+ name: &Utf16String,
+ named_curve: Option<&Utf16String>,
+) -> Option<KeyHandle> {
+ let named_curve = named_curve.map_or(0, Utf16String::raw_identity);
+ // SAFETY: The inputs are borrowed for the call.
+ let raw = unsafe { ffi::crypto_public_key_for_private_key(key.as_raw(), name.raw_identity(), named_curve) };
+ // SAFETY: A non-null result transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }
+}
+
+pub fn rsa_read_key_metadata(key: &KeyHandle) -> Result<(u32, Vec<u8>), BackendError> {
+ let mut modulus_length = 0;
+ // SAFETY: The key and output slots live until the native call returns.
+ let (success, exponent) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_rsa_read_key_metadata(key.as_raw(), &mut modulus_length, state, receive)
+ });
+ success.then_some((modulus_length, exponent)).ok_or(BackendError)
+}
+
+pub fn rsa_key_from_components(is_private: bool, components: &[&[u8]]) -> Option<KeyHandle> {
+ if (is_private && !matches!(components.len(), 3 | 8)) || (!is_private && components.len() != 2) {
+ return None;
+ }
+ let mut spans = [Span::default(); 8];
+ for (span, component) in spans.iter_mut().zip(components) {
+ *span = Span::new(component);
+ }
+ // SAFETY: The spans are live for the call and contain the required components.
+ let raw = unsafe { ffi::crypto_rsa_key_from_jwk_components(is_private, Span::new(&spans[..components.len()])) };
+ // SAFETY: A non-null result transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }
+}
+
+#[derive(Debug)]
+pub enum EcError {
+ Operation(Utf16String),
+ CoordinateEncoding,
+}
+
+fn ec_result(status: u8, error: usize) -> Result<(), EcError> {
+ match status {
+ 0 => Ok(()),
+ 1 => result_from_error(error).map_err(EcError::Operation),
+ _ => Err(EcError::CoordinateEncoding),
+ }
+}
+
+pub fn ec_sign(curve: EcCurve, key: &KeyHandle, digest: &[u8]) -> Result<(Vec<u8>, Vec<u8>), EcError> {
+ let mut error = 0;
+ let mut r = Vec::new();
+ let mut s = Vec::new();
+ // SAFETY: Inputs and both output slots are live for the synchronous call.
+ let status = unsafe {
+ ffi::crypto_ec_sign(
+ curve,
+ key.as_raw(),
+ Span::new(digest),
+ &mut error,
+ core::ptr::from_mut(&mut r).cast(),
+ core::ptr::from_mut(&mut s).cast(),
+ receive_bytes,
+ )
+ };
+ ec_result(status, error)?;
+ Ok((r, s))
+}
+
+pub fn ec_compute_coordinate(curve: EcCurve, key: &KeyHandle, public_key: &KeyHandle) -> Result<Vec<u8>, EcError> {
+ let mut error = 0;
+ // SAFETY: The key handles and output slots are live for the synchronous call.
+ let (status, bytes) = receive_native_bytes(|state, receive| unsafe {
+ ffi::crypto_ec_compute_coordinate(curve, key.as_raw(), public_key.as_raw(), &mut error, state, receive)
+ });
+ ec_result(status, error)?;
+ Ok(bytes)
+}
diff --git a/Libraries/LibCrypto/RustBindings.cpp b/Libraries/LibCrypto/RustBindings.cpp
new file mode 100644
index 00000000000..89ab07e9279
--- /dev/null
+++ b/Libraries/LibCrypto/RustBindings.cpp
@@ -0,0 +1,1190 @@
+/*
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2024, stelar7 <[email protected]>
+ * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2024, Andreas Kling <[email protected]>
+ * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Base64.h>
+#include <AK/Memory.h>
+#include <AK/Random.h>
+#include <LibCrypto/ASN1/ASN1.h>
+#include <LibCrypto/ASN1/Constants.h>
+#include <LibCrypto/ASN1/DER.h>
+#include <LibCrypto/Authentication/HMAC.h>
+#include <LibCrypto/Authentication/KMAC.h>
+#include <LibCrypto/Certificate/Certificate.h>
+#include <LibCrypto/Cipher/AES.h>
+#include <LibCrypto/Cipher/ChaCha.h>
+#include <LibCrypto/Curves/EdwardsCurve.h>
+#include <LibCrypto/Curves/SECPxxxr1.h>
+#include <LibCrypto/Hash/Argon2.h>
+#include <LibCrypto/Hash/HKDF.h>
+#include <LibCrypto/Hash/HashManager.h>
+#include <LibCrypto/Hash/PBKDF2.h>
+#include <LibCrypto/Hash/SHA1.h>
+#include <LibCrypto/Hash/SHA2.h>
+#include <LibCrypto/Hash/SHAKE.h>
+#include <LibCrypto/KeyHandle.h>
+#include <LibCrypto/PK/MLDSA.h>
+#include <LibCrypto/PK/MLKEM.h>
+#include <LibCrypto/PK/RSA.h>
+
+namespace Crypto {
+
+template<typename T>
+struct Asn1Storage final {
+ AK_ALLOC_WITH_KMALLOC;
+
+ T value;
+};
+
+using SubjectPublicKeyStorage = Asn1Storage<Certificate::SubjectPublicKey>;
+using PrivateKeyStorage = Asn1Storage<Certificate::PrivateKey>;
+using OctetStringStorage = Asn1Storage<StringView>;
+
+extern "C" {
+using ReceiveEncodedBytes = void (*)(void*, ReadonlyBytes);
+int crypto_encode_base64url(ReadonlyBytes, ReceiveEncodedBytes, void*);
+
+enum class Base64DecodeResult : u8 {
+ Success,
+ OutOfMemory,
+ InvalidBase64,
+ NonAscii,
+};
+Base64DecodeResult crypto_decode_base64url(FlatPtr, void*, ReceiveEncodedBytes, FlatPtr*);
+
+enum class Asn1Structure : u8 {
+ SubjectPublicKeyInfo,
+ PrivateKeyInfo,
+ OctetString,
+};
+FlatPtr crypto_decode_asn1_structure(ReadonlyBytes, Asn1Structure, void*, bool*);
+}
+
+static bool receive_byte_result(ErrorOr<ByteBuffer> const& result, void* state, ReceiveEncodedBytes receive)
+{
+ if (result.is_error())
+ return false;
+ receive(state, result.value());
+ return true;
+}
+
+int crypto_encode_base64url(ReadonlyBytes bytes, ReceiveEncodedBytes receive, void* state)
+{
+ auto encoded = encode_base64url(bytes, AK::OmitPadding::Yes);
+ if (encoded.is_error())
+ return encoded.error().code();
+ receive(state, encoded.value().bytes_as_string_view().bytes());
+ return 0;
+}
+
+Base64DecodeResult crypto_decode_base64url(FlatPtr raw, void* state, ReceiveEncodedBytes receive, FlatPtr* error_message)
+{
+ auto base64_url_string = Utf16String::from_raw(raw);
+ auto base64_bytes_or_error = decode_base64url(base64_url_string.to_byte_string(), AK::LastChunkHandling::Loose);
+ if (base64_bytes_or_error.is_error()) {
+ if (base64_bytes_or_error.error().code() == ENOMEM)
+ return Base64DecodeResult::OutOfMemory;
+ *error_message = Utf16String::formatted("{}", base64_bytes_or_error.release_error()).into_raw();
+ return Base64DecodeResult::InvalidBase64;
+ }
+ receive(state, base64_bytes_or_error.value());
+ return Base64DecodeResult::Success;
+}
+
+FlatPtr crypto_decode_asn1_structure(ReadonlyBytes data, Asn1Structure structure, void* out, bool* all_consumed)
+{
+ ::Crypto::ASN1::Decoder decoder(data);
+ switch (structure) {
+ case Asn1Structure::SubjectPublicKeyInfo: {
+ auto subject_public_key = ::Crypto::Certificate::parse_subject_public_key_info(decoder);
+ if (subject_public_key.is_error())
+ return Utf16String::formatted("{}", subject_public_key.release_error()).into_raw();
+ static_cast<SubjectPublicKeyStorage*>(out)->value = subject_public_key.release_value();
+ break;
+ }
+ case Asn1Structure::PrivateKeyInfo: {
+ auto private_key = ::Crypto::Certificate::parse_private_key_info(decoder);
+ if (private_key.is_error())
+ return Utf16String::formatted("{}", private_key.release_error()).into_raw();
+ static_cast<PrivateKeyStorage*>(out)->value = private_key.release_value();
+ break;
+ }
+ case Asn1Structure::OctetString: {
+ auto octet_string = decoder.read<StringView>(::Crypto::ASN1::Class::Universal, ::Crypto::ASN1::Kind::OctetString);
+ if (octet_string.is_error())
+ return Utf16String::formatted("{}", octet_string.error()).into_raw();
+ static_cast<OctetStringStorage*>(out)->value = octet_string.release_value();
+ break;
+ }
+ }
+ *all_consumed = decoder.eof();
+ return 0;
+}
+
+extern "C" {
+void* crypto_asn1_allocate_key_info(Asn1Structure);
+void crypto_asn1_delete_key_info(Asn1Structure, void*);
+bool crypto_rsa_key_info_has_encryption_oid(Asn1Structure, void const*);
+KeyHandle* crypto_rsa_key_info_read_key(Asn1Structure, void const*);
+bool crypto_rsa_key_is_valid(KeyHandle const*, bool*);
+bool crypto_rsa_validate_public_exponent(ReadonlyBytes, u32);
+bool crypto_rsa_validate_modulus_length(u32);
+bool crypto_rsa_generate_key_pair(u32, ReadonlyBytes, KeyHandle**, KeyHandle**);
+bool crypto_rsa_export_public_exponent(ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_rsa_read_key_metadata(KeyHandle const*, u32*, void*, ReceiveEncodedBytes);
+KeyHandle* crypto_rsa_key_from_jwk_components(bool, ReadonlySpan<ReadonlyBytes>);
+bool crypto_rsa_export_der(KeyHandle const*, bool, void*, ReceiveEncodedBytes);
+bool crypto_rsa_export_jwk_integer(KeyHandle const*, u8, void*, ReceiveEncodedBytes);
+bool crypto_rsa_oaep_cipher(bool, ::Crypto::Hash::HashKind, KeyHandle const*, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_rsa_pss_sign(::Crypto::Hash::HashKind, KeyHandle const*, u32, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_rsa_pss_verify(::Crypto::Hash::HashKind, KeyHandle const*, u32, ReadonlyBytes, ReadonlyBytes, bool*);
+bool crypto_rsa_pkcs1_sign(::Crypto::Hash::HashKind, KeyHandle const*, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_rsa_pkcs1_verify(::Crypto::Hash::HashKind, KeyHandle const*, ReadonlyBytes, ReadonlyBytes, bool*);
+}
+
+void* crypto_asn1_allocate_key_info(Asn1Structure structure)
+{
+ if (structure == Asn1Structure::SubjectPublicKeyInfo)
+ return new SubjectPublicKeyStorage;
+ if (structure == Asn1Structure::OctetString)
+ return new OctetStringStorage;
+ VERIFY(structure == Asn1Structure::PrivateKeyInfo);
+ return new PrivateKeyStorage;
+}
+
+void crypto_asn1_delete_key_info(Asn1Structure structure, void* key_info)
+{
+ if (structure == Asn1Structure::SubjectPublicKeyInfo) {
+ delete static_cast<SubjectPublicKeyStorage*>(key_info);
+ return;
+ }
+ if (structure == Asn1Structure::OctetString) {
+ delete static_cast<OctetStringStorage*>(key_info);
+ return;
+ }
+ VERIFY(structure == Asn1Structure::PrivateKeyInfo);
+ delete static_cast<PrivateKeyStorage*>(key_info);
+}
+
+bool crypto_rsa_key_info_has_encryption_oid(Asn1Structure structure, void const* key_info)
+{
+ if (structure == Asn1Structure::SubjectPublicKeyInfo)
+ return static_cast<SubjectPublicKeyStorage const*>(key_info)->value.algorithm.identifier == ::Crypto::ASN1::rsa_encryption_oid;
+ VERIFY(structure == Asn1Structure::PrivateKeyInfo);
+ return static_cast<PrivateKeyStorage const*>(key_info)->value.algorithm.identifier == ::Crypto::ASN1::rsa_encryption_oid;
+}
+
+KeyHandle* crypto_rsa_key_info_read_key(Asn1Structure structure, void const* key_info)
+{
+ if (structure == Asn1Structure::SubjectPublicKeyInfo)
+ return new KeyHandle(static_cast<SubjectPublicKeyStorage const*>(key_info)->value.rsa);
+ VERIFY(structure == Asn1Structure::PrivateKeyInfo);
+ return new KeyHandle(static_cast<PrivateKeyStorage const*>(key_info)->value.rsa);
+}
+
+bool crypto_rsa_key_is_valid(KeyHandle const* key, bool* valid)
+{
+ auto result = key->visit(
+ [](::Crypto::PK::RSAPublicKey const& public_key) { return public_key.is_valid(); },
+ [](::Crypto::PK::RSAPrivateKey const& private_key) { return private_key.is_valid(); },
+ [](auto const&) -> ErrorOr<bool> { VERIFY_NOT_REACHED(); });
+ if (result.is_error())
+ return false;
+ *valid = result.value();
+ return true;
+}
+
+bool crypto_rsa_validate_public_exponent(ReadonlyBytes bytes, u32 modulus_length)
+{
+ auto public_exponent = ::Crypto::UnsignedBigInteger::import_data(bytes);
+ return public_exponent >= ::Crypto::UnsignedBigInteger { 3 }
+ && public_exponent.is_odd()
+ && public_exponent.plus(1).one_based_index_of_highest_set_bit() <= modulus_length;
+}
+
+bool crypto_rsa_validate_modulus_length(u32 modulus_length)
+{
+ return !::Crypto::PK::RSA::validate_key_generation_parameters(modulus_length).is_error();
+}
+
+bool crypto_rsa_generate_key_pair(u32 modulus_length, ReadonlyBytes public_exponent, KeyHandle** out_public_key, KeyHandle** out_private_key)
+{
+ auto key_pair = ::Crypto::PK::RSA::generate_key_pair(modulus_length, ::Crypto::UnsignedBigInteger::import_data(public_exponent));
+ if (key_pair.is_error())
+ return false;
+ *out_public_key = new KeyHandle(move(key_pair.value().public_key));
+ *out_private_key = new KeyHandle(move(key_pair.value().private_key));
+ return true;
+}
+
+static ErrorOr<ByteBuffer> export_rsa_exponent(::Crypto::UnsignedBigInteger const& exponent)
+{
+ auto bytes = TRY(ByteBuffer::create_uninitialized(exponent.byte_length()));
+ return ByteBuffer::copy(exponent.export_data(bytes.span()));
+}
+
+bool crypto_rsa_export_public_exponent(ReadonlyBytes public_exponent, void* state, ReceiveEncodedBytes receive)
+{
+ auto bytes = export_rsa_exponent(::Crypto::UnsignedBigInteger::import_data(public_exponent));
+ return receive_byte_result(bytes, state, receive);
+}
+
+bool crypto_rsa_read_key_metadata(KeyHandle const* key, u32* modulus_length, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = key->visit(
+ [&](::Crypto::PK::RSAPublicKey const& public_key) {
+ *modulus_length = public_key.modulus().byte_length() * 8;
+ return export_rsa_exponent(public_key.public_exponent());
+ },
+ [&](::Crypto::PK::RSAPrivateKey const& private_key) {
+ *modulus_length = private_key.modulus().byte_length() * 8;
+ return export_rsa_exponent(private_key.public_exponent());
+ },
+ [](auto const&) -> ErrorOr<ByteBuffer> { VERIFY_NOT_REACHED(); });
+ return receive_byte_result(result, state, receive);
+}
+
+KeyHandle* crypto_rsa_key_from_jwk_components(bool is_private, ReadonlySpan<ReadonlyBytes> components)
+{
+ auto n = ::Crypto::UnsignedBigInteger::import_data(components[0]);
+ auto e = ::Crypto::UnsignedBigInteger::import_data(components[1]);
+ if (!is_private)
+ return new KeyHandle(::Crypto::PK::RSAPublicKey(move(n), move(e)));
+
+ auto d = ::Crypto::UnsignedBigInteger::import_data(components[2]);
+ if (components.size() == 3)
+ return new KeyHandle(::Crypto::PK::RSAPrivateKey(move(n), move(d), move(e)));
+
+ auto p = ::Crypto::UnsignedBigInteger::import_data(components[3]);
+ auto q = ::Crypto::UnsignedBigInteger::import_data(components[4]);
+ auto dp = ::Crypto::UnsignedBigInteger::import_data(components[5]);
+ auto dq = ::Crypto::UnsignedBigInteger::import_data(components[6]);
+ auto qi = ::Crypto::UnsignedBigInteger::import_data(components[7]);
+ return new KeyHandle(::Crypto::PK::RSAPrivateKey(move(n), move(d), move(e), move(p), move(q), move(dp), move(dq), move(qi)));
+}
+
+bool crypto_rsa_export_der(KeyHandle const* key, bool is_public, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = is_public
+ ? ::Crypto::PK::wrap_in_subject_public_key_info(key->get<::Crypto::PK::RSAPublicKey>(), ::Crypto::ASN1::rsa_encryption_oid, nullptr)
+ : ::Crypto::PK::wrap_in_private_key_info(key->get<::Crypto::PK::RSAPrivateKey>(), ::Crypto::ASN1::rsa_encryption_oid, nullptr);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_rsa_export_jwk_integer(KeyHandle const* key, u8 component, void* state, ReceiveEncodedBytes receive)
+{
+ auto const& integer = key->visit(
+ [&](::Crypto::PK::RSAPublicKey const& public_key) -> ::Crypto::UnsignedBigInteger const& {
+ VERIFY(component < 2);
+ return component == 0 ? public_key.modulus() : public_key.public_exponent();
+ },
+ [&](::Crypto::PK::RSAPrivateKey const& private_key) -> ::Crypto::UnsignedBigInteger const& {
+ switch (component) {
+ case 0:
+ return private_key.modulus();
+ case 1:
+ return private_key.public_exponent();
+ case 2:
+ return private_key.private_exponent();
+ case 3:
+ return private_key.prime1();
+ case 4:
+ return private_key.prime2();
+ case 5:
+ return private_key.exponent1();
+ case 6:
+ return private_key.exponent2();
+ case 7:
+ return private_key.coefficient();
+ }
+ VERIFY_NOT_REACHED();
+ },
+ [](auto const&) -> ::Crypto::UnsignedBigInteger const& { VERIFY_NOT_REACHED(); });
+ auto bytes = ByteBuffer::create_uninitialized(integer.byte_length());
+ if (bytes.is_error())
+ return false;
+ receive(state, integer.export_data(bytes.value().span()));
+ return true;
+}
+
+bool crypto_rsa_oaep_cipher(bool encrypt, ::Crypto::Hash::HashKind hash_kind, KeyHandle const* key, ReadonlyBytes label, ReadonlyBytes input, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = [&]() {
+ if (encrypt) {
+ ::Crypto::PK::RSA_OAEP_EME rsa { hash_kind, key->get<::Crypto::PK::RSAPublicKey>() };
+ rsa.set_label(label);
+ return rsa.encrypt(input);
+ }
+ ::Crypto::PK::RSA_OAEP_EME rsa { hash_kind, key->get<::Crypto::PK::RSAPrivateKey>() };
+ rsa.set_label(label);
+ return rsa.decrypt(input);
+ }();
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_rsa_pss_sign(::Crypto::Hash::HashKind hash_kind, KeyHandle const* key, u32 salt_length, ReadonlyBytes message, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::PK::RSA_PSS_EMSA rsa { hash_kind, key->get<::Crypto::PK::RSAPrivateKey>() };
+ rsa.set_salt_length(salt_length);
+ auto result = rsa.sign(message);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_rsa_pss_verify(::Crypto::Hash::HashKind hash_kind, KeyHandle const* key, u32 salt_length, ReadonlyBytes message, ReadonlyBytes signature, bool* verified)
+{
+ ::Crypto::PK::RSA_PSS_EMSA rsa { hash_kind, key->get<::Crypto::PK::RSAPublicKey>() };
+ rsa.set_salt_length(salt_length);
+ auto result = rsa.verify(message, signature);
+ if (result.is_error())
+ return false;
+ *verified = result.value();
+ return true;
+}
+
+bool crypto_rsa_pkcs1_sign(::Crypto::Hash::HashKind hash_kind, KeyHandle const* key, ReadonlyBytes message, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::PK::RSA_PKCS1_EMSA rsa { hash_kind, key->get<::Crypto::PK::RSAPrivateKey>() };
+ auto result = rsa.sign(message);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_rsa_pkcs1_verify(::Crypto::Hash::HashKind hash_kind, KeyHandle const* key, ReadonlyBytes message, ReadonlyBytes signature, bool* verified)
+{
+ ::Crypto::PK::RSA_PKCS1_EMSA rsa { hash_kind, key->get<::Crypto::PK::RSAPublicKey>() };
+ auto result = rsa.verify(message, signature);
+ if (result.is_error())
+ return false;
+ *verified = result.value();
+ return true;
+}
+
+extern "C" {
+bool crypto_aes_cbc_cipher(bool, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_aes_ctr_cipher(bool, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_aes_kw_cipher(bool, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_aes_gcm_encrypt(ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, size_t, void*, void*, ReceiveEncodedBytes);
+bool crypto_aes_gcm_decrypt(ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+FlatPtr crypto_aes_ocb_cipher(bool, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, size_t, void*, ReceiveEncodedBytes);
+}
+
+bool crypto_aes_cbc_cipher(bool encrypt, ReadonlyBytes key, ReadonlyBytes input, ReadonlyBytes iv, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Cipher::AESCBCCipher cipher(key);
+ auto result = encrypt ? cipher.encrypt(input, iv) : cipher.decrypt(input, iv);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_aes_ctr_cipher(bool encrypt, ReadonlyBytes key, ReadonlyBytes input, ReadonlyBytes counter, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Cipher::AESCTRCipher cipher(key);
+ auto result = encrypt ? cipher.encrypt(input, counter) : cipher.decrypt(input, counter);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_aes_kw_cipher(bool wrap, ReadonlyBytes key, ReadonlyBytes input, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Cipher::AESKWCipher cipher(key);
+ auto result = wrap ? cipher.wrap(input) : cipher.unwrap(input);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_aes_gcm_encrypt(ReadonlyBytes key, ReadonlyBytes plaintext, ReadonlyBytes iv, ReadonlyBytes additional_data, size_t tag_length, void* ciphertext, void* tag, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Cipher::AESGCMCipher cipher(key);
+ auto result = cipher.encrypt(plaintext, iv, additional_data, tag_length);
+ if (result.is_error())
+ return false;
+ receive(ciphertext, result.value().ciphertext);
+ receive(tag, result.value().tag);
+ return true;
+}
+
+bool crypto_aes_gcm_decrypt(ReadonlyBytes key, ReadonlyBytes ciphertext, ReadonlyBytes iv, ReadonlyBytes additional_data, ReadonlyBytes tag, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Cipher::AESGCMCipher cipher(key);
+ auto result = cipher.decrypt(ciphertext, iv, additional_data, tag);
+ if (result.is_error()) {
+ dbgln("FAILED: {}", result.error());
+ return false;
+ }
+ receive(state, result.value());
+ return true;
+}
+
+FlatPtr crypto_aes_ocb_cipher(bool encrypt, ReadonlyBytes key, ReadonlyBytes input, ReadonlyBytes iv, ReadonlyBytes additional_data, size_t tag_length, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Cipher::AESOCBCipher cipher(key);
+ auto result = encrypt ? cipher.encrypt(input, iv, additional_data, tag_length) : cipher.decrypt(input, iv, additional_data, tag_length);
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ receive(state, result.value());
+ return 0;
+}
+
+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);
+
+extern "C" bool crypto_sha_digest(::Crypto::Hash::HashKind, ReadonlyBytes, void*, ReceiveEncodedBytes);
+
+bool 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());
+ return receive_byte_result(result_buffer, state, receive);
+}
+
+struct OptionalBytes {
+ bool has_value;
+ ReadonlyBytes bytes;
+
+ Optional<ReadonlyBytes> to_optional() const { return has_value ? Optional<ReadonlyBytes> { bytes } : Optional<ReadonlyBytes> {}; }
+};
+
+enum class EcCurve : u8 {
+ P256,
+ P384,
+ P521,
+};
+
+static ::Crypto::Curves::SECPxxxr1 ec_curve(EcCurve curve)
+{
+ switch (curve) {
+ case EcCurve::P256:
+ return ::Crypto::Curves::SECP256r1 {};
+ case EcCurve::P384:
+ return ::Crypto::Curves::SECP384r1 {};
+ case EcCurve::P521:
+ return ::Crypto::Curves::SECP521r1 {};
+ }
+ VERIFY_NOT_REACHED();
+}
+
+static ReadonlySpan<u32> ec_curve_oid(EcCurve curve)
+{
+ switch (curve) {
+ case EcCurve::P256:
+ return ::Crypto::ASN1::secp256r1_oid;
+ case EcCurve::P384:
+ return ::Crypto::ASN1::secp384r1_oid;
+ case EcCurve::P521:
+ return ::Crypto::ASN1::secp521r1_oid;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+extern "C" {
+bool crypto_ec_generate_key_pair(EcCurve, KeyHandle**, KeyHandle**);
+u8 crypto_ec_sign(EcCurve, KeyHandle const*, ReadonlyBytes, FlatPtr*, void*, void*, ReceiveEncodedBytes);
+FlatPtr crypto_ec_verify(EcCurve, KeyHandle const*, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, bool*);
+size_t crypto_ec_public_key_scalar_size(KeyHandle const*);
+u8 crypto_ec_compute_coordinate(EcCurve, KeyHandle const*, KeyHandle const*, FlatPtr*, void*, ReceiveEncodedBytes);
+bool crypto_ec_key_info_has_public_key_oid(Asn1Structure, void const*);
+bool crypto_ec_key_info_parameters(Asn1Structure, void const*, ReadonlySpan<u32>*);
+bool crypto_ec_private_key_info_parameters_match(void const*);
+KeyHandle* crypto_ec_key_info_read_key(Asn1Structure, void const*);
+KeyHandle* crypto_ec_key_from_coordinates(ReadonlyBytes, ReadonlyBytes, size_t, OptionalBytes);
+KeyHandle* crypto_ec_parse_raw_public_key(ReadonlyBytes);
+bool crypto_ec_key_is_valid(EcCurve, KeyHandle const*, bool*);
+bool crypto_ec_export_der(EcCurve, KeyHandle const*, bool, void*, ReceiveEncodedBytes);
+bool crypto_ec_export_uncompressed(KeyHandle const*, void*, ReceiveEncodedBytes);
+bool crypto_ec_export_public_coordinates(EcCurve, KeyHandle const*, void*, void*, ReceiveEncodedBytes);
+bool crypto_ec_export_private_scalar(KeyHandle const*, void*, ReceiveEncodedBytes);
+}
+
+bool crypto_ec_generate_key_pair(EcCurve curve_id, KeyHandle** out_public_key, KeyHandle** out_private_key)
+{
+ auto curve = ec_curve(curve_id);
+ auto maybe_private_key_data = curve.generate_private_key();
+ if (maybe_private_key_data.is_error())
+ return false;
+ auto private_key_data = maybe_private_key_data.release_value();
+ auto maybe_public_key_data = curve.generate_public_key(private_key_data);
+ if (maybe_public_key_data.is_error())
+ return false;
+ auto public_key_data = maybe_public_key_data.release_value();
+ auto public_key = ::Crypto::PK::ECPublicKey { public_key_data };
+ auto private_key = ::Crypto::PK::ECPrivateKey { move(private_key_data), public_key_data.size, {}, public_key };
+ *out_public_key = new KeyHandle(move(public_key));
+ *out_private_key = new KeyHandle(move(private_key));
+ return true;
+}
+
+u8 crypto_ec_sign(EcCurve curve_id, KeyHandle const* key, ReadonlyBytes digest, FlatPtr* error, void* r, void* s, ReceiveEncodedBytes receive)
+{
+ auto signature = ec_curve(curve_id).sign(digest, key->get<::Crypto::PK::ECPrivateKey>().d());
+ if (signature.is_error()) {
+ *error = Utf16String::from_utf8(signature.error().string_literal()).into_raw();
+ return 1;
+ }
+ auto r_bytes = signature.value().r_bytes();
+ if (r_bytes.is_error())
+ return 2;
+ receive(r, r_bytes.value());
+ auto s_bytes = signature.value().s_bytes();
+ if (s_bytes.is_error())
+ return 2;
+ receive(s, s_bytes.value());
+ return 0;
+}
+
+FlatPtr crypto_ec_verify(EcCurve curve_id, KeyHandle const* key, ReadonlyBytes digest, ReadonlyBytes r_bytes, ReadonlyBytes s_bytes, bool* verified)
+{
+ auto const& public_key = key->get<::Crypto::PK::ECPublicKey>();
+ auto r = ::Crypto::UnsignedBigInteger::import_data(r_bytes);
+ auto s = ::Crypto::UnsignedBigInteger::import_data(s_bytes);
+ auto result = ec_curve(curve_id).verify(digest, public_key.to_secpxxxr1_point(), { move(r), move(s), public_key.scalar_size() });
+ if (result.is_error())
+ return Utf16String::from_utf8(result.error().string_literal()).into_raw();
+ *verified = result.value();
+ return 0;
+}
+
+size_t crypto_ec_public_key_scalar_size(KeyHandle const* key)
+{
+ return key->get<::Crypto::PK::ECPublicKey>().scalar_size();
+}
+
+u8 crypto_ec_compute_coordinate(EcCurve curve_id, KeyHandle const* key, KeyHandle const* public_key, FlatPtr* error, void* state, ReceiveEncodedBytes receive)
+{
+ auto const& private_key_data = key->get<::Crypto::PK::ECPrivateKey>();
+ auto const& public_key_data = public_key->get<::Crypto::PK::ECPublicKey>();
+ auto secret = ec_curve(curve_id).compute_coordinate(private_key_data.d(), public_key_data.to_secpxxxr1_point());
+ if (secret.is_error()) {
+ *error = Utf16String::formatted("{}", secret.error()).into_raw();
+ return 1;
+ }
+ auto secret_data = secret.value().to_uncompressed();
+ if (secret_data.is_error())
+ return 2;
+ receive(state, secret_data.value());
+ return 0;
+}
+
+static ::Crypto::Certificate::AlgorithmIdentifier const& key_info_algorithm(Asn1Structure structure, void const* key_info)
+{
+ if (structure == Asn1Structure::SubjectPublicKeyInfo)
+ return static_cast<SubjectPublicKeyStorage const*>(key_info)->value.algorithm;
+ VERIFY(structure == Asn1Structure::PrivateKeyInfo);
+ return static_cast<PrivateKeyStorage const*>(key_info)->value.algorithm;
+}
+
+bool crypto_ec_key_info_has_public_key_oid(Asn1Structure structure, void const* key_info)
+{
+ return key_info_algorithm(structure, key_info).identifier == ::Crypto::ASN1::ec_public_key_encryption_oid;
+}
+
+bool crypto_ec_key_info_parameters(Asn1Structure structure, void const* key_info, ReadonlySpan<u32>* parameters)
+{
+ auto const& algorithm = key_info_algorithm(structure, key_info);
+ if (!algorithm.ec_parameters.has_value())
+ return false;
+ *parameters = algorithm.ec_parameters->span();
+ return true;
+}
+
+bool crypto_ec_private_key_info_parameters_match(void const* key_info)
+{
+ auto const& private_key_info = static_cast<PrivateKeyStorage const*>(key_info)->value;
+ auto const& parameters = private_key_info.ec.parameters();
+ return !parameters.has_value() || *parameters == private_key_info.algorithm.ec_parameters.value_or({});
+}
+
+KeyHandle* crypto_ec_key_info_read_key(Asn1Structure structure, void const* key_info)
+{
+ if (structure == Asn1Structure::SubjectPublicKeyInfo)
+ return new KeyHandle(static_cast<SubjectPublicKeyStorage const*>(key_info)->value.ec);
+ VERIFY(structure == Asn1Structure::PrivateKeyInfo);
+ return new KeyHandle(static_cast<PrivateKeyStorage const*>(key_info)->value.ec);
+}
+
+KeyHandle* crypto_ec_key_from_coordinates(ReadonlyBytes x, ReadonlyBytes y, size_t coord_size, OptionalBytes d)
+{
+ auto public_key = ::Crypto::PK::ECPublicKey { ::Crypto::UnsignedBigInteger::import_data(x), ::Crypto::UnsignedBigInteger::import_data(y), coord_size };
+ if (!d.has_value)
+ return new KeyHandle(move(public_key));
+ return new KeyHandle(::Crypto::PK::ECPrivateKey { ::Crypto::UnsignedBigInteger::import_data(d.bytes), coord_size, {}, move(public_key) });
+}
+
+KeyHandle* crypto_ec_parse_raw_public_key(ReadonlyBytes data)
+{
+ auto result = ::Crypto::PK::EC::parse_ec_key(data, false, {});
+ if (result.is_error())
+ return nullptr;
+ return new KeyHandle(move(result.value().public_key));
+}
+
+bool crypto_ec_key_is_valid(EcCurve curve_id, KeyHandle const* key, bool* valid)
+{
+ auto curve = ec_curve(curve_id);
+ auto result = key->visit(
+ [&](::Crypto::PK::ECPublicKey const& public_key) {
+ return curve.is_valid_point(public_key.to_secpxxxr1_point());
+ },
+ [&](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<bool> {
+ if (!private_key.public_key().has_value())
+ return true;
+ return curve.is_valid_point(private_key.public_key()->to_secpxxxr1_point(), private_key.d());
+ },
+ [](auto const&) -> ErrorOr<bool> { VERIFY_NOT_REACHED(); });
+ if (result.is_error())
+ return false;
+ *valid = result.value();
+ return true;
+}
+
+bool crypto_ec_export_der(EcCurve curve, KeyHandle const* key, bool is_public, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = [&]() -> ErrorOr<ByteBuffer> {
+ auto ec_params = ec_curve_oid(curve);
+ if (is_public) {
+ auto public_key_bytes = TRY(key->get<::Crypto::PK::ECPublicKey>().to_uncompressed());
+ return ::Crypto::PK::wrap_in_subject_public_key_info(public_key_bytes, ::Crypto::ASN1::ec_public_key_encryption_oid, ec_params);
+ }
+ return ::Crypto::PK::wrap_in_private_key_info(key->get<::Crypto::PK::ECPrivateKey>(), ::Crypto::ASN1::ec_public_key_encryption_oid, ec_params);
+ }();
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_ec_export_uncompressed(KeyHandle const* key, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = key->get<::Crypto::PK::ECPublicKey>().to_uncompressed();
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_ec_export_public_coordinates(EcCurve curve_id, KeyHandle const* key, void* x, void* y, ReceiveEncodedBytes receive)
+{
+ auto result = key->visit(
+ [&](::Crypto::PK::ECPublicKey const& public_key) -> ErrorOr<void> {
+ auto x_bytes = TRY(public_key.x_bytes());
+ receive(x, x_bytes);
+ auto y_bytes = TRY(public_key.y_bytes());
+ receive(y, y_bytes);
+ return {};
+ },
+ [&](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<void> {
+ auto public_key = TRY(ec_curve(curve_id).generate_public_key(private_key.d()));
+ auto x_bytes = TRY(public_key.x_bytes());
+ auto y_bytes = TRY(public_key.y_bytes());
+ receive(x, x_bytes);
+ receive(y, y_bytes);
+ return {};
+ },
+ [](auto const&) -> ErrorOr<void> { VERIFY_NOT_REACHED(); });
+ return !result.is_error();
+}
+
+bool crypto_ec_export_private_scalar(KeyHandle const* key, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = key->get<::Crypto::PK::ECPrivateKey>().d_bytes();
+ return receive_byte_result(result, state, receive);
+}
+
+enum class OkpCurve : u8 {
+ Ed25519,
+ Ed448,
+ X25519,
+ X448,
+};
+
+static ::Crypto::Curves::EdwardsCurve okp_curve(OkpCurve curve)
+{
+ switch (curve) {
+ case OkpCurve::Ed25519:
+ return ::Crypto::Curves::Ed25519 {};
+ case OkpCurve::Ed448:
+ return ::Crypto::Curves::Ed448 {};
+ case OkpCurve::X25519:
+ return ::Crypto::Curves::X25519 {};
+ case OkpCurve::X448:
+ return ::Crypto::Curves::X448 {};
+ }
+ VERIFY_NOT_REACHED();
+}
+
+static ReadonlySpan<u32> okp_curve_oid(OkpCurve curve)
+{
+ switch (curve) {
+ case OkpCurve::Ed25519:
+ return ::Crypto::ASN1::ed25519_oid;
+ case OkpCurve::Ed448:
+ return ::Crypto::ASN1::ed448_oid;
+ case OkpCurve::X25519:
+ return ::Crypto::ASN1::x25519_oid;
+ case OkpCurve::X448:
+ return ::Crypto::ASN1::x448_oid;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+extern "C" {
+bool crypto_okp_generate_private_key(OkpCurve, void*, ReceiveEncodedBytes);
+bool crypto_okp_generate_public_key(OkpCurve, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_okp_compute_coordinate(OkpCurve, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_okp_sign(OkpCurve, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+FlatPtr crypto_okp_verify(OkpCurve, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, bool*);
+bool crypto_okp_key_info_has_oid(OkpCurve, Asn1Structure, void const*);
+void crypto_asn1_key_info_raw_key(Asn1Structure, void const*, ReadonlyBytes*);
+void crypto_asn1_octet_string_bytes(OctetStringStorage const*, ReadonlyBytes*);
+bool crypto_okp_export_der(OkpCurve, bool, ReadonlyBytes, void*, ReceiveEncodedBytes);
+}
+
+bool crypto_okp_generate_private_key(OkpCurve curve, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = okp_curve(curve).generate_private_key();
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_okp_generate_public_key(OkpCurve curve, ReadonlyBytes private_key, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = okp_curve(curve).generate_public_key(private_key);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_okp_compute_coordinate(OkpCurve curve, ReadonlyBytes private_key, ReadonlyBytes public_key, void* state, ReceiveEncodedBytes receive)
+{
+ VERIFY(curve == OkpCurve::X25519 || curve == OkpCurve::X448);
+ auto result = curve == OkpCurve::X25519
+ ? ::Crypto::Curves::X25519 {}.compute_coordinate(private_key, public_key)
+ : ::Crypto::Curves::X448 {}.compute_coordinate(private_key, public_key);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_okp_sign(OkpCurve curve, ReadonlyBytes private_key, ReadonlyBytes message, ReadonlyBytes context, void* state, ReceiveEncodedBytes receive)
+{
+ VERIFY(curve == OkpCurve::Ed25519 || curve == OkpCurve::Ed448);
+ auto result = curve == OkpCurve::Ed25519
+ ? ::Crypto::Curves::Ed25519 {}.sign(private_key, message)
+ : ::Crypto::Curves::Ed448 {}.sign(private_key, message, context);
+ return receive_byte_result(result, state, receive);
+}
+
+FlatPtr crypto_okp_verify(OkpCurve curve, ReadonlyBytes public_key, ReadonlyBytes signature, ReadonlyBytes message, ReadonlyBytes context, bool* verified)
+{
+ VERIFY(curve == OkpCurve::Ed25519 || curve == OkpCurve::Ed448);
+ auto result = curve == OkpCurve::Ed25519
+ ? ::Crypto::Curves::Ed25519 {}.verify(public_key, signature, message)
+ : ::Crypto::Curves::Ed448 {}.verify(public_key, signature, message, context);
+ if (result.is_error())
+ return Utf16String::from_utf8(result.error().string_literal()).into_raw();
+ *verified = result.value();
+ return 0;
+}
+
+bool crypto_okp_key_info_has_oid(OkpCurve curve, Asn1Structure structure, void const* key_info)
+{
+ return key_info_algorithm(structure, key_info).identifier == okp_curve_oid(curve);
+}
+
+void crypto_asn1_key_info_raw_key(Asn1Structure structure, void const* key_info, ReadonlyBytes* bytes)
+{
+ if (structure == Asn1Structure::SubjectPublicKeyInfo) {
+ *bytes = static_cast<SubjectPublicKeyStorage const*>(key_info)->value.raw_key;
+ return;
+ }
+ VERIFY(structure == Asn1Structure::PrivateKeyInfo);
+ *bytes = static_cast<PrivateKeyStorage const*>(key_info)->value.raw_key;
+}
+
+void crypto_asn1_octet_string_bytes(OctetStringStorage const* string, ReadonlyBytes* bytes)
+{
+ *bytes = string->value.bytes();
+}
+
+bool crypto_okp_export_der(OkpCurve curve, bool is_public, ReadonlyBytes key, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = [&]() -> ErrorOr<ByteBuffer> {
+ auto oid = okp_curve_oid(curve);
+ if (is_public)
+ return ::Crypto::PK::wrap_in_subject_public_key_info(TRY(ByteBuffer::copy(key)), oid);
+ ::Crypto::ASN1::Encoder encoder;
+ TRY(encoder.write(key));
+ return ::Crypto::PK::wrap_in_private_key_info(encoder.finish(), oid);
+ }();
+ return receive_byte_result(result, state, receive);
+}
+
+extern "C" {
+void crypto_hmac_sign(::Crypto::Hash::HashKind, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_timing_safe_compare(ReadonlyBytes, ReadonlyBytes);
+}
+
+static_assert(::Crypto::Hash::SHA1::block_size() == 64);
+static_assert(::Crypto::Hash::SHA256::block_size() == 64);
+static_assert(::Crypto::Hash::SHA384::block_size() == 128);
+static_assert(::Crypto::Hash::SHA512::block_size() == 128);
+
+void crypto_hmac_sign(::Crypto::Hash::HashKind hash_kind, ReadonlyBytes key, ReadonlyBytes message, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Authentication::HMAC hmac(hash_kind, key);
+ auto mac = hmac.process(message);
+ receive(state, mac);
+}
+
+bool crypto_timing_safe_compare(ReadonlyBytes left, ReadonlyBytes right)
+{
+ VERIFY(left.size() == right.size());
+ return timing_safe_compare(left.data(), right.data(), left.size());
+}
+
+extern "C" {
+bool crypto_mldsa_sign(::Crypto::PK::MLDSASize, KeyHandle const*, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+bool crypto_mldsa_verify(::Crypto::PK::MLDSASize, KeyHandle const*, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, bool*);
+FlatPtr crypto_mldsa_generate_key_pair(::Crypto::PK::MLDSASize, ReadonlyBytes, KeyHandle**, KeyHandle**);
+void crypto_asn1_key_info_identifier(Asn1Structure, void const*, ReadonlySpan<u32>*);
+KeyHandle* crypto_mldsa_key_info_read_private_key(void const*);
+KeyHandle* crypto_mldsa_read_public_key(ReadonlyBytes);
+void crypto_mldsa_public_bytes(KeyHandle const*, ReadonlyBytes*);
+void crypto_mldsa_seed_bytes(KeyHandle const*, ReadonlyBytes*);
+bool crypto_mldsa_export_der(KeyHandle const*, bool, ReadonlySpan<u32>, void*, ReceiveEncodedBytes);
+}
+
+static_assert(to_underlying(::Crypto::PK::MLDSA44) == 0);
+static_assert(to_underlying(::Crypto::PK::MLDSA65) == 1);
+static_assert(to_underlying(::Crypto::PK::MLDSA87) == 2);
+
+bool crypto_mldsa_sign(::Crypto::PK::MLDSASize size, KeyHandle const* key, ReadonlyBytes message, ReadonlyBytes context, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::PK::MLDSA lattice(size, key->get<::Crypto::PK::MLDSAPrivateKey>(), MUST(ByteBuffer::copy(context)));
+ auto result = lattice.sign(message);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_mldsa_verify(::Crypto::PK::MLDSASize size, KeyHandle const* key, ReadonlyBytes message, ReadonlyBytes signature, ReadonlyBytes context, bool* verified)
+{
+ ::Crypto::PK::MLDSA lattice(size, key->get<::Crypto::PK::MLDSAPublicKey>(), MUST(ByteBuffer::copy(context)));
+ auto result = lattice.verify(message, signature);
+ if (result.is_error())
+ return false;
+ *verified = result.value();
+ return true;
+}
+
+FlatPtr crypto_mldsa_generate_key_pair(::Crypto::PK::MLDSASize size, ReadonlyBytes seed, KeyHandle** out_public_key, KeyHandle** out_private_key)
+{
+ auto key_pair = ::Crypto::PK::MLDSA::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 KeyHandle(move(key_pair.value().public_key));
+ *out_private_key = new KeyHandle(move(key_pair.value().private_key));
+ return 0;
+}
+
+void crypto_asn1_key_info_identifier(Asn1Structure structure, void const* key_info, ReadonlySpan<u32>* identifier)
+{
+ *identifier = key_info_algorithm(structure, key_info).identifier.span();
+}
+
+KeyHandle* crypto_mldsa_key_info_read_private_key(void const* key_info)
+{
+ return new KeyHandle(static_cast<PrivateKeyStorage const*>(key_info)->value.mldsa);
+}
+
+KeyHandle* crypto_mldsa_read_public_key(ReadonlyBytes bytes)
+{
+ return new KeyHandle(::Crypto::PK::MLDSAPublicKey { MUST(ByteBuffer::copy(bytes)) });
+}
+
+void crypto_mldsa_public_bytes(KeyHandle const* key, ReadonlyBytes* bytes)
+{
+ *bytes = key->visit(
+ [](::Crypto::PK::MLDSAPublicKey const& public_key) -> ReadonlyBytes { return public_key.public_key(); },
+ [](::Crypto::PK::MLDSAPrivateKey const& private_key) -> ReadonlyBytes { return private_key.public_key(); },
+ [](auto const&) -> ReadonlyBytes { VERIFY_NOT_REACHED(); });
+}
+
+void crypto_mldsa_seed_bytes(KeyHandle const* key, ReadonlyBytes* bytes)
+{
+ *bytes = key->get<::Crypto::PK::MLDSAPrivateKey>().seed();
+}
+
+bool crypto_mldsa_export_der(KeyHandle const* key, bool is_public, ReadonlySpan<u32> oid, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = is_public
+ ? ::Crypto::PK::wrap_in_subject_public_key_info(key->get<::Crypto::PK::MLDSAPublicKey>().public_key(), oid)
+ : ::Crypto::PK::wrap_in_private_key_info(key->get<::Crypto::PK::MLDSAPrivateKey>(), oid);
+ return receive_byte_result(result, state, receive);
+}
+
+extern "C" {
+FlatPtr crypto_mlkem_generate_key_pair(::Crypto::PK::MLKEMSize, ReadonlyBytes, KeyHandle**, KeyHandle**);
+KeyHandle* crypto_mlkem_key_info_read_private_key(void const*);
+KeyHandle* crypto_mlkem_read_public_key(ReadonlyBytes);
+void crypto_mlkem_public_bytes(KeyHandle const*, void*, ReceiveEncodedBytes);
+void crypto_mlkem_seed_bytes(KeyHandle const*, ReadonlyBytes*);
+bool crypto_mlkem_export_der(KeyHandle const*, bool, ReadonlySpan<u32>, void*, ReceiveEncodedBytes);
+FlatPtr crypto_mlkem_encapsulate(::Crypto::PK::MLKEMSize, KeyHandle const*, void*, void*, ReceiveEncodedBytes);
+FlatPtr crypto_mlkem_decapsulate(::Crypto::PK::MLKEMSize, KeyHandle const*, ReadonlyBytes, void*, ReceiveEncodedBytes);
+}
+
+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);
+
+FlatPtr crypto_mlkem_generate_key_pair(::Crypto::PK::MLKEMSize size, ReadonlyBytes seed, KeyHandle** out_public_key, KeyHandle** 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 KeyHandle(move(key_pair.value().public_key));
+ *out_private_key = new KeyHandle(move(key_pair.value().private_key));
+ return 0;
+}
+
+KeyHandle* crypto_mlkem_key_info_read_private_key(void const* key_info)
+{
+ return new KeyHandle(static_cast<PrivateKeyStorage const*>(key_info)->value.mlkem);
+}
+
+KeyHandle* crypto_mlkem_read_public_key(ReadonlyBytes bytes)
+{
+ return new KeyHandle(::Crypto::PK::MLKEMPublicKey { MUST(ByteBuffer::copy(bytes)) });
+}
+
+void crypto_mlkem_public_bytes(KeyHandle const* key, void* state, ReceiveEncodedBytes receive)
+{
+ auto public_key = key->get<::Crypto::PK::MLKEMPublicKey>().public_key();
+ receive(state, public_key);
+}
+
+void crypto_mlkem_seed_bytes(KeyHandle const* key, ReadonlyBytes* bytes)
+{
+ *bytes = key->get<::Crypto::PK::MLKEMPrivateKey>().seed();
+}
+
+bool crypto_mlkem_export_der(KeyHandle const* key, bool is_public, ReadonlySpan<u32> oid, void* state, ReceiveEncodedBytes receive)
+{
+ 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);
+ return receive_byte_result(result, state, receive);
+}
+
+FlatPtr crypto_mlkem_encapsulate(::Crypto::PK::MLKEMSize size, KeyHandle 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;
+}
+
+FlatPtr crypto_mlkem_decapsulate(::Crypto::PK::MLKEMSize size, KeyHandle const* key, ReadonlyBytes ciphertext, void* state, ReceiveEncodedBytes receive)
+{
+ 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 {
+ ReadonlyBytes message;
+ ReadonlyBytes nonce;
+ u32 parallelism;
+ u32 memory;
+ u32 passes;
+ u32 version;
+ OptionalBytes secret_value;
+ OptionalBytes associated_data;
+ u32 tag_length;
+};
+
+extern "C" {
+size_t crypto_hash_digest_size(::Crypto::Hash::HashKind);
+bool crypto_hkdf_derive_key(::Crypto::Hash::HashKind, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, u32, void*, ReceiveEncodedBytes);
+bool crypto_pbkdf2_derive_key(::Crypto::Hash::HashKind, ReadonlyBytes, ReadonlyBytes, u32, u32, void*, ReceiveEncodedBytes);
+FlatPtr crypto_argon2_validate_parameters(ReadonlyBytes);
+FlatPtr crypto_argon2_derive_key(::Crypto::Hash::Argon2Type, Argon2Inputs const*, void*, ReceiveEncodedBytes);
+}
+
+size_t crypto_hash_digest_size(::Crypto::Hash::HashKind hash_kind)
+{
+ return ::Crypto::Hash::Manager { hash_kind }.digest_size();
+}
+
+bool crypto_hkdf_derive_key(::Crypto::Hash::HashKind kind, ReadonlyBytes salt, ReadonlyBytes key_derivation_key, ReadonlyBytes info, u32 length, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Hash::HKDF hkdf(kind);
+ auto result = hkdf.derive_key(salt, key_derivation_key, info, length);
+ return receive_byte_result(result, state, receive);
+}
+
+bool crypto_pbkdf2_derive_key(::Crypto::Hash::HashKind kind, ReadonlyBytes password, ReadonlyBytes salt, u32 iterations, u32 length, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Hash::PBKDF2 pbkdf2(kind);
+ auto result = pbkdf2.derive_key(password, salt, iterations, length);
+ return receive_byte_result(result, state, receive);
+}
+
+static_assert(to_underlying(::Crypto::Hash::Argon2Type::Argon2d) == 0);
+static_assert(to_underlying(::Crypto::Hash::Argon2Type::Argon2i) == 1);
+static_assert(to_underlying(::Crypto::Hash::Argon2Type::Argon2id) == 2);
+
+FlatPtr crypto_argon2_validate_parameters(ReadonlyBytes nonce)
+{
+ auto result = ::Crypto::Hash::Argon2::validate_parameters(nonce);
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ return 0;
+}
+
+FlatPtr crypto_argon2_derive_key(::Crypto::Hash::Argon2Type kind, Argon2Inputs const* inputs, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Hash::Argon2 algorithm(kind);
+ auto result = algorithm.derive_key(inputs->message, inputs->nonce, inputs->parallelism, inputs->memory,
+ inputs->passes, inputs->version, inputs->secret_value.to_optional(), inputs->associated_data.to_optional(),
+ inputs->tag_length);
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ receive(state, result.value());
+ return 0;
+}
+
+static_assert(to_underlying(::Crypto::Hash::SHAKEKind::CSHAKE128) == 0);
+static_assert(to_underlying(::Crypto::Hash::SHAKEKind::CSHAKE256) == 1);
+
+extern "C" FlatPtr crypto_cshake_validate_parameters(u32, OptionalBytes, OptionalBytes);
+extern "C" FlatPtr crypto_cshake_digest(::Crypto::Hash::SHAKEKind, ReadonlyBytes, u32, OptionalBytes, OptionalBytes, void*, ReceiveEncodedBytes);
+
+FlatPtr 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;
+}
+
+FlatPtr 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 Utf16String::formatted("{}", maybe_result.error()).into_raw();
+ receive(state, maybe_result.value());
+ return 0;
+}
+
+extern "C" FlatPtr crypto_chacha20_poly1305_cipher(bool, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);
+
+FlatPtr crypto_chacha20_poly1305_cipher(bool encrypt, ReadonlyBytes key, ReadonlyBytes iv, ReadonlyBytes input, ReadonlyBytes additional_data, void* state, ReceiveEncodedBytes receive)
+{
+ auto result = encrypt
+ ? ::Crypto::Cipher::ChaCha20Poly1305::encrypt(key, iv, input, additional_data)
+ : ::Crypto::Cipher::ChaCha20Poly1305::decrypt(key, iv, input, additional_data);
+ if (result.is_error())
+ return Utf16String::formatted("{}", result.error()).into_raw();
+ receive(state, result.value());
+ return 0;
+}
+
+extern "C" {
+u32 crypto_kmac_default_key_length(::Crypto::Authentication::KMACKind);
+bool crypto_kmac_validate_parameters(u32, OptionalBytes);
+bool crypto_kmac_sign(::Crypto::Authentication::KMACKind, ReadonlyBytes, ReadonlyBytes, u32, OptionalBytes, void*, ReceiveEncodedBytes);
+}
+
+static_assert(to_underlying(::Crypto::Authentication::KMACKind::KMAC128) == 0);
+static_assert(to_underlying(::Crypto::Authentication::KMACKind::KMAC256) == 1);
+
+u32 crypto_kmac_default_key_length(::Crypto::Authentication::KMACKind kind)
+{
+ return ::Crypto::Authentication::KMAC::default_key_length(kind);
+}
+
+bool crypto_kmac_validate_parameters(u32 output_length, OptionalBytes customization)
+{
+ return !::Crypto::Authentication::KMAC::validate_parameters(output_length, customization.to_optional()).is_error();
+}
+
+bool crypto_kmac_sign(::Crypto::Authentication::KMACKind kind, ReadonlyBytes key, ReadonlyBytes message, u32 output_length, OptionalBytes customization, void* state, ReceiveEncodedBytes receive)
+{
+ ::Crypto::Authentication::KMAC kmac(kind);
+ auto result = kmac.sign(key, message, output_length, customization.to_optional());
+ return receive_byte_result(result, state, receive);
+}
+
+extern "C" KeyHandle* crypto_public_key_for_private_key(KeyHandle const*, FlatPtr name, FlatPtr named_curve);
+
+KeyHandle* crypto_public_key_for_private_key(KeyHandle const* key, FlatPtr raw_name, FlatPtr raw_named_curve)
+{
+ auto result = key->visit(
+ [](::Crypto::PK::RSAPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
+ return ::Crypto::PK::RSAPublicKey { private_key.modulus(), private_key.public_exponent() };
+ },
+ [&](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
+ if (private_key.public_key().has_value())
+ return *private_key.public_key();
+
+ VERIFY(raw_named_curve);
+ auto named_curve = Utf16String::from_raw(raw_named_curve);
+ auto point = TRY([&] -> ErrorOr<::Crypto::Curves::SECPxxxr1Point> {
+ if (named_curve == "P-256"_utf16)
+ return ::Crypto::Curves::SECP256r1 {}.generate_public_key(private_key.d());
+ if (named_curve == "P-384"_utf16)
+ return ::Crypto::Curves::SECP384r1 {}.generate_public_key(private_key.d());
+ if (named_curve == "P-521"_utf16)
+ return ::Crypto::Curves::SECP521r1 {}.generate_public_key(private_key.d());
+ return Error::from_string_literal("Unsupported named curve");
+ }());
+ return ::Crypto::PK::ECPublicKey { move(point) };
+ },
+ [](::Crypto::PK::MLDSAPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
+ return ::Crypto::PK::MLDSAPublicKey { private_key.public_key() };
+ },
+ [](::Crypto::PK::MLKEMPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
+ return ::Crypto::PK::MLKEMPublicKey { private_key.public_key() };
+ },
+ [&](OKPPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
+ auto name = Utf16String::from_raw(raw_name);
+ auto public_key = TRY([&] -> ErrorOr<ByteBuffer> {
+ if (name == "Ed25519"_utf16)
+ return ::Crypto::Curves::Ed25519 {}.generate_public_key(private_key.bytes);
+ if (name == "Ed448"_utf16)
+ return ::Crypto::Curves::Ed448 {}.generate_public_key(private_key.bytes);
+ if (name == "X25519"_utf16)
+ return ::Crypto::Curves::X25519 {}.generate_public_key(private_key.bytes);
+ if (name == "X448"_utf16)
+ return ::Crypto::Curves::X448 {}.generate_public_key(private_key.bytes);
+ return Error::from_string_literal("Unsupported algorithm");
+ }());
+ return OKPPublicKey { move(public_key) };
+ },
+ [](auto const&) -> ErrorOr<KeyHandle> {
+ return Error::from_string_literal("Key is not a private key");
+ });
+ if (result.is_error())
+ return nullptr;
+ return new KeyHandle(result.release_value());
+}
+
+extern "C" {
+void crypto_fill_with_random(Bytes);
+void crypto_generate_random_uuid(void*, ReceiveEncodedBytes);
+}
+
+void crypto_fill_with_random(Bytes bytes)
+{
+ fill_with_random(bytes);
+}
+
+void crypto_generate_random_uuid(void* state, ReceiveEncodedBytes receive)
+{
+ auto uuid = generate_random_uuid();
+ receive(state, uuid.bytes());
+}
+
+}