Skip to content

Truly independent web browser

LibCrypto: Hold ML-DSA and ML-KEM keys as OpenSSL keys

Shannon Booth90bb84f4756d
diff --git a/Libraries/LibCrypto/KeyHandle.cpp b/Libraries/LibCrypto/KeyHandle.cpp
index 9d4af9aec02..b26cfb82532 100644
--- a/Libraries/LibCrypto/KeyHandle.cpp
+++ b/Libraries/LibCrypto/KeyHandle.cpp
@@ -44,8 +44,6 @@ void crypto_key_destroy_handle(KeyHandle* handle)
[](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::MLDSAPrivateKey& data) { data.clear_sensitive_data(); },
- [](::Crypto::PK::MLKEMPrivateKey& data) { data.clear_sensitive_data(); },
[](auto&) { });
delete handle;
}
@@ -85,6 +83,8 @@ void crypto_key_encode_handle(KeyHandle const* handle, void* state, void (*steps
// 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; };
+ // NB: An ML-DSA or ML-KEM private key's seed is written here, since the key does not keep a copy of it.
+ Array<u8, max(::Crypto::PK::MLDSAPrivateKey::seed_size, ::Crypto::PK::MLKEMPrivateKey::seed_size)> seed_buffer;
auto add_exported = [&](ByteBuffer buffer) {
exported.unchecked_append(move(buffer));
add(exported.last().bytes());
@@ -129,9 +129,9 @@ void crypto_key_encode_handle(KeyHandle const* handle, void* state, void (*steps
},
[&](::Crypto::PK::MLDSAPrivateKey const& mldsa_key) {
fields.handle_tag = to_underlying(HandleTag::MLDSAPrivateKey);
- add(mldsa_key.seed().bytes());
+ add(MUST(mldsa_key.seed(seed_buffer)));
add(mldsa_key.public_key().bytes());
- add(mldsa_key.private_key().bytes());
+ add_exported(MUST(mldsa_key.expanded_key()));
},
[&](::Crypto::PK::MLKEMPublicKey const& mlkem_key) {
fields.handle_tag = to_underlying(HandleTag::MLKEMPublicKey);
@@ -139,9 +139,9 @@ void crypto_key_encode_handle(KeyHandle const* handle, void* state, void (*steps
},
[&](::Crypto::PK::MLKEMPrivateKey const& mlkem_key) {
fields.handle_tag = to_underlying(HandleTag::MLKEMPrivateKey);
- add(mlkem_key.seed().bytes());
+ add(MUST(mlkem_key.seed(seed_buffer)));
add(mlkem_key.public_key().bytes());
- add(mlkem_key.private_key().bytes());
+ add_exported(MUST(mlkem_key.expanded_key()));
},
[&](OKPPublicKey const& okp_key) {
fields.handle_tag = to_underlying(HandleTag::OKPPublicKey);
@@ -156,6 +156,7 @@ void crypto_key_encode_handle(KeyHandle const* handle, void* state, void (*steps
for (auto& buffer : exported)
secure_zero(buffer.data(), buffer.size());
+ secure_zero(seed_buffer.data(), seed_buffer.size());
}
static ErrorOr<KeyHandle> handle_from_fields(CryptoKeyHandleFields const& fields)
@@ -194,14 +195,29 @@ static ErrorOr<KeyHandle> handle_from_fields(CryptoKeyHandleFields const& fields
public_key = TRY(::Crypto::PK::ECPublicKey::from_coordinates(buffer(1), buffer(2)));
return TRY(::Crypto::PK::ECPrivateKey::from_scalar(buffer(0), move(parameters), move(public_key)));
}
+ // NB: A private key is rebuilt from its seed, with the parameter set that its public key's length names, and must
+ // give back that public key. No key in the expandedKey form, which has no seed, can have been stored, since Web
+ // Crypto rejects that form at import.
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)) };
+ return TRY(::Crypto::PK::MLDSAPublicKey::from_bytes(buffer(0)));
+ case HandleTag::MLDSAPrivateKey: {
+ auto public_key = TRY(::Crypto::PK::MLDSAPublicKey::from_bytes(buffer(1)));
+ auto private_key = TRY(::Crypto::PK::MLDSAPrivateKey::generate(public_key.size(), buffer(0)));
+ if (private_key.public_key().bytes() != buffer(1))
+ return Error::from_string_literal("The stored ML-DSA public key does not match its seed");
+ return private_key;
+ }
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)) };
+ return TRY(::Crypto::PK::MLKEMPublicKey::from_bytes(buffer(0)));
+ case HandleTag::MLKEMPrivateKey: {
+ auto public_key = TRY(::Crypto::PK::MLKEMPublicKey::from_bytes(buffer(1)));
+ if (!public_key.size().has_value())
+ return Error::from_string_literal("The stored ML-KEM public key is not valid");
+ auto private_key = TRY(::Crypto::PK::MLKEMPrivateKey::generate(*public_key.size(), buffer(0)));
+ if (private_key.public_key().bytes() != buffer(1))
+ return Error::from_string_literal("The stored ML-KEM public key does not match its seed");
+ return private_key;
+ }
case HandleTag::OKPPublicKey:
return OKPPublicKey { TRY(copy(0)) };
case HandleTag::OKPPrivateKey:
diff --git a/Libraries/LibCrypto/OpenSSL.cpp b/Libraries/LibCrypto/OpenSSL.cpp
index 632d592f7d9..eeab74a51f2 100644
--- a/Libraries/LibCrypto/OpenSSL.cpp
+++ b/Libraries/LibCrypto/OpenSSL.cpp
@@ -85,14 +85,14 @@ ErrorOr<UnsignedBigInteger> openssl_bignum_to_unsigned_big_integer(OpenSSL_BN co
return UnsignedBigInteger::import_data(buf);
}
-ErrorOr<ByteBuffer> get_byte_buffer_param_from_key(OpenSSL_PKEY& key, char const* key_name)
+ErrorOr<ByteBuffer> get_byte_buffer_param_from_key(EVP_PKEY* key, char const* key_name)
{
size_t size;
- OPENSSL_TRY(EVP_PKEY_get_octet_string_param(key.ptr(), key_name, nullptr, 0, &size));
+ OPENSSL_TRY(EVP_PKEY_get_octet_string_param(key, key_name, nullptr, 0, &size));
auto buffer = TRY(ByteBuffer::create_uninitialized(size));
- OPENSSL_TRY(EVP_PKEY_get_octet_string_param(key.ptr(), key_name, buffer.data(), buffer.size(), &size));
+ OPENSSL_TRY(EVP_PKEY_get_octet_string_param(key, key_name, buffer.data(), buffer.size(), &size));
return buffer;
}
diff --git a/Libraries/LibCrypto/OpenSSL.h b/Libraries/LibCrypto/OpenSSL.h
index e36d1bab82c..6a9df68021a 100644
--- a/Libraries/LibCrypto/OpenSSL.h
+++ b/Libraries/LibCrypto/OpenSSL.h
@@ -156,6 +156,6 @@ public:
ErrorOr<OpenSSL_BN> unsigned_big_integer_to_openssl_bignum(UnsignedBigInteger const& integer);
ErrorOr<UnsignedBigInteger> openssl_bignum_to_unsigned_big_integer(OpenSSL_BN const& bn);
-ErrorOr<ByteBuffer> get_byte_buffer_param_from_key(OpenSSL_PKEY& key, char const* key_name);
+ErrorOr<ByteBuffer> get_byte_buffer_param_from_key(EVP_PKEY* key, char const* key_name);
}
diff --git a/Libraries/LibCrypto/PK/MLDSA.cpp b/Libraries/LibCrypto/PK/MLDSA.cpp
index 846b7ac9e5b..58c81b3a983 100644
--- a/Libraries/LibCrypto/PK/MLDSA.cpp
+++ b/Libraries/LibCrypto/PK/MLDSA.cpp
@@ -4,28 +4,22 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Array.h>
#include <AK/Memory.h>
-#include <LibCrypto/PK/MLDSA.h>
-
+#include <AK/ScopeGuard.h>
#include <LibCrypto/ASN1/DER.h>
#include <LibCrypto/OpenSSL.h>
+#include <LibCrypto/PK/MLDSA.h>
#include <LibCrypto/PK/ModuleLatticePrivateKey.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
-#include <openssl/param_build.h>
namespace Crypto::PK {
-void MLDSAPrivateKey::clear_sensitive_data()
-{
- secure_zero(m_seed.data(), m_seed.size());
- secure_zero(m_private_key.data(), m_private_key.size());
-}
-
-namespace {
+static constexpr MLDSASize sizes[] { MLDSA44, MLDSA65, MLDSA87 };
-char const* mldsa_size_to_openssl_name(MLDSASize size)
+static char const* openssl_name(MLDSASize size)
{
switch (size) {
case MLDSA44:
@@ -34,14 +28,24 @@ char const* mldsa_size_to_openssl_name(MLDSASize size)
return "ML-DSA-65";
case MLDSA87:
return "ML-DSA-87";
- default:
- VERIFY_NOT_REACHED();
}
+ VERIFY_NOT_REACHED();
}
+static size_t public_key_size(MLDSASize size)
+{
+ switch (size) {
+ case MLDSA44:
+ return 1312;
+ case MLDSA65:
+ return 1952;
+ case MLDSA87:
+ return 2592;
+ }
+ VERIFY_NOT_REACHED();
}
-static size_t mldsa_expanded_key_size(MLDSASize size)
+static size_t expanded_key_size(MLDSASize size)
{
switch (size) {
case MLDSA44:
@@ -50,156 +54,163 @@ static size_t mldsa_expanded_key_size(MLDSASize size)
return 4032;
case MLDSA87:
return 4896;
- default:
- VERIFY_NOT_REACHED();
}
+ VERIFY_NOT_REACHED();
}
-ErrorOr<ByteBuffer> MLDSAPrivateKey::export_as_der() const
+static ErrorOr<MLDSASize> size_for_length(ReadonlyBytes bytes, size_t (*size_of)(MLDSASize))
{
- // NB: The key is exported in the seed-only form, which a key without its seed cannot be.
- if (m_seed.is_empty())
- return Error::from_string_literal("Cannot export an ML-DSA private key without its seed");
-
- ASN1::Encoder encoder;
- TRY(encoder.write<ReadonlyBytes>(m_seed, ASN1::Class::Context, static_cast<ASN1::Kind>(0)));
-
- return encoder.finish();
+ for (auto size : sizes) {
+ if (size_of(size) == bytes.size())
+ return size;
+ }
+ return Error::from_string_literal("Invalid ML-DSA key length");
}
-ErrorOr<MLDSA::KeyPairType> MLDSA::parse_mldsa_key(MLDSASize size, ReadonlyBytes der)
+static ErrorOr<OpenSSL_SharedPKEY> key_from_octets(MLDSASize size, int selection, char const* name, ReadonlyBytes octets)
{
- auto encoded_key = TRY(parse_module_lattice_private_key(der, 32, mldsa_expanded_key_size(size)));
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, openssl_name(size), nullptr)));
+ OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));
- // NB: Web Crypto rejects a key in the expandedKey form before it validates the key, so that form is kept as it is.
- if (encoded_key.seed.is_empty())
- return KeyPairType { {}, { {}, {}, TRY(ByteBuffer::copy(encoded_key.expanded_key)) } };
+ OSSL_PARAM params[] {
+ OSSL_PARAM_octet_string(name, const_cast<u8*>(octets.data()), octets.size()),
+ OSSL_PARAM_END,
+ };
- auto key_pair = TRY(generate_key_pair(size, TRY(ByteBuffer::copy(encoded_key.seed))));
- if (!encoded_key.expanded_key.is_empty() && key_pair.private_key.private_key() != encoded_key.expanded_key)
- return Error::from_string_literal("The expanded key does not match the seed");
- return key_pair;
+ EVP_PKEY* key = nullptr;
+ OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key, selection, params));
+ return OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(key)) };
}
-ErrorOr<MLDSA::KeyPairType> MLDSA::generate_key_pair(MLDSASize size, ByteBuffer seed)
+ErrorOr<MLDSAPublicKey> MLDSAPublicKey::from_bytes(ReadonlyBytes bytes)
{
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, mldsa_size_to_openssl_name(size), nullptr)));
+ auto size = TRY(size_for_length(bytes, public_key_size));
+ auto key = TRY(key_from_octets(size, EVP_PKEY_PUBLIC_KEY, OSSL_PKEY_PARAM_PUB_KEY, bytes));
+ return MLDSAPublicKey { move(key), TRY(ByteBuffer::copy(bytes)), size };
+}
+ErrorOr<MLDSAPrivateKey> MLDSAPrivateKey::generate(MLDSASize size, ReadonlyBytes seed)
+{
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, openssl_name(size), nullptr)));
OPENSSL_TRY(EVP_PKEY_keygen_init(ctx.ptr()));
- OSSL_PARAM params[2] = {
- OSSL_PARAM_END,
- OSSL_PARAM_END
- };
-
if (!seed.is_empty()) {
- params[0] = OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ML_DSA_SEED, seed.data(), seed.size());
+ OSSL_PARAM params[] {
+ OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ML_DSA_SEED, const_cast<u8*>(seed.data()), seed.size()),
+ OSSL_PARAM_END,
+ };
+ OPENSSL_TRY(EVP_PKEY_CTX_set_params(ctx.ptr(), params));
}
- OPENSSL_TRY(EVP_PKEY_CTX_set_params(ctx.ptr(), params));
- auto key = TRY(OpenSSL_PKEY::create());
- auto* key_ptr = key.ptr();
- OPENSSL_TRY(EVP_PKEY_generate(ctx.ptr(), &key_ptr));
+ EVP_PKEY* generated = nullptr;
+ OPENSSL_TRY(EVP_PKEY_generate(ctx.ptr(), &generated));
+ auto key = OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(generated)) };
- auto pub = TRY(get_byte_buffer_param_from_key(key, OSSL_PKEY_PARAM_PUB_KEY));
- auto priv = TRY(get_byte_buffer_param_from_key(key, OSSL_PKEY_PARAM_PRIV_KEY));
- seed = TRY(get_byte_buffer_param_from_key(key, OSSL_PKEY_PARAM_ML_DSA_SEED));
+ auto public_key = TRY(get_byte_buffer_param_from_key(key.ptr(), OSSL_PKEY_PARAM_PUB_KEY));
+ return MLDSAPrivateKey { move(key), move(public_key), size };
+}
- return KeyPairType {
- { pub },
- { seed, pub, priv }
- };
+MLDSAPrivateKey MLDSAPrivateKey::in_expanded_key_form(MLDSASize size)
+{
+ MLDSAPrivateKey private_key;
+ private_key.m_size = size;
+ return private_key;
}
-static ErrorOr<OpenSSL_PKEY> private_key_to_openssl_pkey(MLDSASize size, MLDSAPrivateKey const& private_key)
+ErrorOr<ReadonlyBytes> MLDSAPrivateKey::seed(Bytes buffer) const
{
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, mldsa_size_to_openssl_name(size), nullptr)));
+ if (!m_key.ptr())
+ return ReadonlyBytes {};
+ size_t size = 0;
+ OPENSSL_TRY(EVP_PKEY_get_octet_string_param(m_key.ptr(), OSSL_PKEY_PARAM_ML_DSA_SEED, buffer.data(), buffer.size(), &size));
+ return buffer.trim(size);
+}
- OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));
+ErrorOr<ByteBuffer> MLDSAPrivateKey::expanded_key() const
+{
+ if (!m_key.ptr())
+ return ByteBuffer {};
+ return get_byte_buffer_param_from_key(m_key.ptr(), OSSL_PKEY_PARAM_PRIV_KEY);
+}
- auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());
- ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); };
+ErrorOr<ByteBuffer> MLDSAPrivateKey::export_as_der() const
+{
+ // NB: The key is exported in the seed-only form, which a key without its seed cannot be.
+ Array<u8, seed_size> buffer;
+ ScopeGuard const clear_buffer = [&] { secure_zero(buffer.data(), buffer.size()); };
+ auto seed = TRY(this->seed(buffer));
+ if (seed.is_empty())
+ return Error::from_string_literal("Cannot export an ML-DSA private key without its seed");
- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_ML_DSA_SEED, private_key.seed().data(), private_key.seed().size()));
- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_PUB_KEY, private_key.public_key().data(), private_key.public_key().size()));
- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_PRIV_KEY, private_key.private_key().data(), private_key.private_key().size()));
+ ASN1::Encoder encoder;
+ TRY(encoder.write<ReadonlyBytes>(seed, ASN1::Class::Context, static_cast<ASN1::Kind>(0)));
- auto* params = OSSL_PARAM_BLD_to_param(params_bld);
- ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };
+ return encoder.finish();
+}
- auto key = TRY(OpenSSL_PKEY::create());
- auto* key_ptr = key.ptr();
- OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key_ptr, EVP_PKEY_KEYPAIR, params));
+ErrorOr<MLDSA::KeyPairType> MLDSA::parse_mldsa_key(MLDSASize size, ReadonlyBytes der)
+{
+ auto encoded_key = TRY(parse_module_lattice_private_key(der, 32, expanded_key_size(size)));
- return key;
+ if (encoded_key.seed.is_empty())
+ return KeyPairType { {}, MLDSAPrivateKey::in_expanded_key_form(size) };
+
+ auto key_pair = TRY(generate_key_pair(size, encoded_key.seed));
+ if (!encoded_key.expanded_key.is_empty()) {
+ auto expanded_key = TRY(key_pair.private_key.expanded_key());
+ ScopeGuard const clear_expanded_key = [&] { secure_zero(expanded_key.data(), expanded_key.size()); };
+ if (expanded_key != encoded_key.expanded_key)
+ return Error::from_string_literal("The expanded key does not match the seed");
+ }
+ return key_pair;
}
-ErrorOr<ByteBuffer> mldsa_sign(MLDSASize size, MLDSAPrivateKey const& private_key, ReadonlyBytes context, ReadonlyBytes message)
+ErrorOr<MLDSA::KeyPairType> MLDSA::generate_key_pair(MLDSASize size, ReadonlyBytes seed)
{
- OSSL_PARAM params[2] = {
- OSSL_PARAM_END,
- OSSL_PARAM_END
- };
+ auto private_key = TRY(MLDSAPrivateKey::generate(size, seed));
+ auto public_key = TRY(MLDSAPublicKey::from_bytes(private_key.public_key()));
+ return KeyPairType { move(public_key), move(private_key) };
+}
- if (!context.is_empty()) {
- params[0] = OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, const_cast<u8*>(context.data()), context.size());
- }
+static Array<OSSL_PARAM, 2> context_parameters(ReadonlyBytes context)
+{
+ Array<OSSL_PARAM, 2> params { OSSL_PARAM_construct_end(), OSSL_PARAM_construct_end() };
+ if (!context.is_empty())
+ params[0] = OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, const_cast<u8*>(context.data()), context.size());
+ return params;
+}
- auto key = TRY(private_key_to_openssl_pkey(size, private_key));
+ErrorOr<ByteBuffer> mldsa_sign(MLDSASize size, MLDSAPrivateKey const& private_key, ReadonlyBytes context, ReadonlyBytes message)
+{
+ if (private_key.size() != size)
+ return Error::from_string_literal("The key is for a different ML-DSA parameter set");
- EVP_PKEY_CTX* sign_ctx = OPENSSL_TRY_PTR(EVP_PKEY_CTX_new_from_pkey(nullptr, key.ptr(), nullptr));
- ScopeGuard const free_sign_ctx = [&] { EVP_PKEY_CTX_free(sign_ctx); };
- auto* sign_algorithm = OPENSSL_TRY_PTR(EVP_SIGNATURE_fetch(nullptr, mldsa_size_to_openssl_name(size), nullptr));
+ auto params = context_parameters(context);
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, private_key.openssl_key(), nullptr)));
+ auto* sign_algorithm = OPENSSL_TRY_PTR(EVP_SIGNATURE_fetch(nullptr, openssl_name(size), nullptr));
ScopeGuard const free_sign_algorithm = [&] { EVP_SIGNATURE_free(sign_algorithm); };
size_t sign_size;
- OPENSSL_TRY(EVP_PKEY_sign_message_init(sign_ctx, sign_algorithm, params));
- OPENSSL_TRY(EVP_PKEY_sign(sign_ctx, nullptr, &sign_size, message.data(), message.size()));
+ OPENSSL_TRY(EVP_PKEY_sign_message_init(ctx.ptr(), sign_algorithm, params.data()));
+ OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), nullptr, &sign_size, message.data(), message.size()));
auto result = TRY(ByteBuffer::create_uninitialized(sign_size));
- OPENSSL_TRY(EVP_PKEY_sign(sign_ctx, result.data(), &sign_size, message.data(), message.size()));
+ OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), result.data(), &sign_size, message.data(), message.size()));
return result;
}
-static ErrorOr<OpenSSL_PKEY> public_key_to_openssl_pkey(MLDSASize size, MLDSAPublicKey const& public_key)
-{
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, mldsa_size_to_openssl_name(size), nullptr)));
-
- OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));
-
- auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());
- ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); };
-
- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_PUB_KEY, public_key.public_key().data(), public_key.public_key().size()));
-
- auto* params = OSSL_PARAM_BLD_to_param(params_bld);
- ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };
-
- auto key = TRY(OpenSSL_PKEY::create());
- auto* key_ptr = key.ptr();
- OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key_ptr, EVP_PKEY_KEYPAIR, params));
-
- return key;
-}
-
ErrorOr<bool> mldsa_verify(MLDSASize size, MLDSAPublicKey const& public_key, ReadonlyBytes context, ReadonlyBytes message, ReadonlyBytes signature)
{
- OSSL_PARAM params[2] = {
- OSSL_PARAM_END,
- OSSL_PARAM_END
- };
-
- if (!context.is_empty()) {
- params[0] = OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, const_cast<u8*>(context.data()), context.size());
- }
+ if (public_key.size() != size)
+ return Error::from_string_literal("The key is for a different ML-DSA parameter set");
- auto key = TRY(public_key_to_openssl_pkey(size, public_key));
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new(key.ptr(), nullptr)));
- auto* sign_algorithm = OPENSSL_TRY_PTR(EVP_SIGNATURE_fetch(nullptr, mldsa_size_to_openssl_name(size), nullptr));
+ auto params = context_parameters(context);
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, public_key.openssl_key(), nullptr)));
+ auto* sign_algorithm = OPENSSL_TRY_PTR(EVP_SIGNATURE_fetch(nullptr, openssl_name(size), nullptr));
ScopeGuard const free_sign_algorithm = [&] { EVP_SIGNATURE_free(sign_algorithm); };
- OPENSSL_TRY(EVP_PKEY_verify_message_init(ctx.ptr(), sign_algorithm, params));
+ OPENSSL_TRY(EVP_PKEY_verify_message_init(ctx.ptr(), sign_algorithm, params.data()));
auto ret = EVP_PKEY_verify(ctx.ptr(), signature.data(), signature.size(), message.data(), message.size());
if (ret == 1)
diff --git a/Libraries/LibCrypto/PK/MLDSA.h b/Libraries/LibCrypto/PK/MLDSA.h
index e0d6bda36cb..5cae105348a 100644
--- a/Libraries/LibCrypto/PK/MLDSA.h
+++ b/Libraries/LibCrypto/PK/MLDSA.h
@@ -6,8 +6,9 @@
#pragma once
+#include <AK/ByteBuffer.h>
#include <AK/Error.h>
-#include <LibCrypto/PK/PK.h>
+#include <LibCrypto/OpenSSL.h>
namespace Crypto::PK {
@@ -19,56 +20,77 @@ enum MLDSASize {
class MLDSAPublicKey {
public:
- MLDSAPublicKey(ByteBuffer m_public_key)
- : m_public_key(move(m_public_key))
- {
- }
-
MLDSAPublicKey() = default;
+ static ErrorOr<MLDSAPublicKey> from_bytes(ReadonlyBytes);
+
+ MLDSASize size() const { return m_size; }
ByteBuffer const& public_key() const { return m_public_key; }
+ EVP_PKEY* openssl_key() const { return m_key.ptr(); }
+
private:
+ MLDSAPublicKey(OpenSSL_SharedPKEY key, ByteBuffer public_key, MLDSASize size)
+ : m_key(move(key))
+ , m_public_key(move(public_key))
+ , m_size(size)
+ {
+ }
+
+ OpenSSL_SharedPKEY m_key;
ByteBuffer m_public_key;
+ MLDSASize m_size { MLDSA44 };
};
class MLDSAPrivateKey {
public:
- MLDSAPrivateKey(ByteBuffer seed, ByteBuffer public_key, ByteBuffer private_key)
- : m_seed(move(seed))
- , m_public_key(move(public_key))
- , m_private_key(move(private_key))
- {
- }
-
MLDSAPrivateKey() = default;
- void clear_sensitive_data();
+ // An empty seed generates a new key.
+ static ErrorOr<MLDSAPrivateKey> generate(MLDSASize, ReadonlyBytes seed);
+
+ // A key that was given in the expandedKey form, which Web Crypto rejects once it has parsed it. It has no seed,
+ // public key or OpenSSL key, since OpenSSL would refuse an expanded key that is not valid.
+ static MLDSAPrivateKey in_expanded_key_form(MLDSASize);
+
+ MLDSASize size() const { return m_size; }
+ static constexpr size_t seed_size = 32;
- ByteBuffer const& seed() const { return m_seed; }
+ bool has_seed() const { return m_key.ptr(); }
+ // NB: OpenSSL keeps the seed, so that no copy of it is left behind when a key is moved or replaced. It is written
+ // into the caller's buffer, which the caller clears.
+ ErrorOr<ReadonlyBytes> seed(Bytes buffer) const;
ByteBuffer const& public_key() const { return m_public_key; }
- ByteBuffer const& private_key() const { return m_private_key; }
+ ErrorOr<ByteBuffer> expanded_key() const;
ErrorOr<ByteBuffer> export_as_der() const;
+ EVP_PKEY* openssl_key() const { return m_key.ptr(); }
+
private:
- ByteBuffer m_seed;
+ MLDSAPrivateKey(OpenSSL_SharedPKEY key, ByteBuffer public_key, MLDSASize size)
+ : m_key(move(key))
+ , m_public_key(move(public_key))
+ , m_size(size)
+ {
+ }
+
+ OpenSSL_SharedPKEY m_key;
ByteBuffer m_public_key;
- ByteBuffer m_private_key;
+ MLDSASize m_size { MLDSA44 };
};
-template<typename PubKey, typename PrivKey>
struct MLDSAKeyPair {
- PubKey public_key;
- PrivKey private_key;
+ MLDSAPublicKey public_key;
+ MLDSAPrivateKey private_key;
};
class MLDSA {
public:
- using KeyPairType = MLDSAKeyPair<MLDSAPublicKey, MLDSAPrivateKey>;
+ using KeyPairType = MLDSAKeyPair;
static ErrorOr<KeyPairType> parse_mldsa_key(MLDSASize, ReadonlyBytes der);
- static ErrorOr<KeyPairType> generate_key_pair(MLDSASize, ByteBuffer seed = {});
+ static ErrorOr<KeyPairType> generate_key_pair(MLDSASize, ReadonlyBytes seed = {});
};
ErrorOr<ByteBuffer> mldsa_sign(MLDSASize, MLDSAPrivateKey const&, ReadonlyBytes context, ReadonlyBytes message);
diff --git a/Libraries/LibCrypto/PK/MLKEM.cpp b/Libraries/LibCrypto/PK/MLKEM.cpp
index 699bc32e9dd..9b7e8ab6f19 100644
--- a/Libraries/LibCrypto/PK/MLKEM.cpp
+++ b/Libraries/LibCrypto/PK/MLKEM.cpp
@@ -4,26 +4,22 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Array.h>
#include <AK/Memory.h>
-#include <LibCrypto/PK/MLKEM.h>
-
+#include <AK/ScopeGuard.h>
#include <LibCrypto/ASN1/DER.h>
#include <LibCrypto/OpenSSL.h>
+#include <LibCrypto/PK/MLKEM.h>
#include <LibCrypto/PK/ModuleLatticePrivateKey.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
-#include <openssl/param_build.h>
namespace Crypto::PK {
-void MLKEMPrivateKey::clear_sensitive_data()
-{
- secure_zero(m_seed.data(), m_seed.size());
- secure_zero(m_private_key.data(), m_private_key.size());
-}
+static constexpr MLKEMSize sizes[] { MLKEMSize::MLKEM512, MLKEMSize::MLKEM768, MLKEMSize::MLKEM1024 };
-static char const* mlkem_size_to_openssl_name(MLKEMSize size)
+static char const* openssl_name(MLKEMSize size)
{
switch (size) {
case MLKEMSize::MLKEM512:
@@ -32,12 +28,24 @@ static char const* mlkem_size_to_openssl_name(MLKEMSize size)
return "ML-KEM-768";
case MLKEMSize::MLKEM1024:
return "ML-KEM-1024";
- default:
- VERIFY_NOT_REACHED();
}
+ VERIFY_NOT_REACHED();
}
-static size_t mlkem_expanded_key_size(MLKEMSize size)
+static size_t public_key_size(MLKEMSize size)
+{
+ switch (size) {
+ case MLKEMSize::MLKEM512:
+ return 800;
+ case MLKEMSize::MLKEM768:
+ return 1184;
+ case MLKEMSize::MLKEM1024:
+ return 1568;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+static size_t expanded_key_size(MLKEMSize size)
{
switch (size) {
case MLKEMSize::MLKEM512:
@@ -46,42 +54,142 @@ static size_t mlkem_expanded_key_size(MLKEMSize size)
return 2400;
case MLKEMSize::MLKEM1024:
return 3168;
- default:
- VERIFY_NOT_REACHED();
}
+ VERIFY_NOT_REACHED();
+}
+
+static ErrorOr<MLKEMSize> size_for_length(ReadonlyBytes bytes, size_t (*size_of)(MLKEMSize))
+{
+ for (auto size : sizes) {
+ if (size_of(size) == bytes.size())
+ return size;
+ }
+ return Error::from_string_literal("Invalid ML-KEM key length");
+}
+
+static ErrorOr<OpenSSL_SharedPKEY> key_from_octets(MLKEMSize size, int selection, char const* name, ReadonlyBytes octets)
+{
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, openssl_name(size), nullptr)));
+ OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));
+
+ OSSL_PARAM params[] {
+ OSSL_PARAM_octet_string(name, const_cast<u8*>(octets.data()), octets.size()),
+ OSSL_PARAM_END,
+ };
+
+ EVP_PKEY* key = nullptr;
+ OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key, selection, params));
+ return OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(key)) };
+}
+
+ErrorOr<MLKEMPublicKey> MLKEMPublicKey::from_bytes(ReadonlyBytes bytes)
+{
+ MLKEMPublicKey public_key;
+ public_key.m_public_key = TRY(ByteBuffer::copy(bytes));
+
+ // NB: OpenSSL builds a key only from bytes of a parameter set's length whose coefficients are all below q, which
+ // are the two parts of the encapsulation key check.
+ auto size = size_for_length(bytes, public_key_size);
+ if (size.is_error())
+ return public_key;
+ auto key = key_from_octets(size.value(), EVP_PKEY_PUBLIC_KEY, OSSL_PKEY_PARAM_PUB_KEY, bytes);
+ if (key.is_error())
+ return public_key;
+
+ public_key.m_key = key.release_value();
+ public_key.m_size = size.value();
+ return public_key;
+}
+
+ErrorOr<MLKEMPrivateKey> MLKEMPrivateKey::generate(MLKEMSize size, ReadonlyBytes seed)
+{
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, openssl_name(size), nullptr)));
+ OPENSSL_TRY(EVP_PKEY_keygen_init(ctx.ptr()));
+
+ if (!seed.is_empty()) {
+ OSSL_PARAM params[] {
+ OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ML_KEM_SEED, const_cast<u8*>(seed.data()), seed.size()),
+ OSSL_PARAM_END,
+ };
+ OPENSSL_TRY(EVP_PKEY_CTX_set_params(ctx.ptr(), params));
+ }
+
+ EVP_PKEY* generated = nullptr;
+ OPENSSL_TRY(EVP_PKEY_generate(ctx.ptr(), &generated));
+ auto key = OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(generated)) };
+
+ auto public_key = TRY(get_byte_buffer_param_from_key(key.ptr(), OSSL_PKEY_PARAM_PUB_KEY));
+ return MLKEMPrivateKey { move(key), move(public_key), size };
+}
+
+MLKEMPrivateKey MLKEMPrivateKey::in_expanded_key_form(MLKEMSize size)
+{
+ MLKEMPrivateKey private_key;
+ private_key.m_size = size;
+ return private_key;
+}
+
+ErrorOr<ReadonlyBytes> MLKEMPrivateKey::seed(Bytes buffer) const
+{
+ if (!m_key.ptr())
+ return ReadonlyBytes {};
+ size_t size = 0;
+ OPENSSL_TRY(EVP_PKEY_get_octet_string_param(m_key.ptr(), OSSL_PKEY_PARAM_ML_KEM_SEED, buffer.data(), buffer.size(), &size));
+ return buffer.trim(size);
+}
+
+ErrorOr<ByteBuffer> MLKEMPrivateKey::expanded_key() const
+{
+ if (!m_key.ptr())
+ return ByteBuffer {};
+ return get_byte_buffer_param_from_key(m_key.ptr(), OSSL_PKEY_PARAM_PRIV_KEY);
}
ErrorOr<ByteBuffer> MLKEMPrivateKey::export_as_der() const
{
// NB: The key is exported in the seed-only form, which a key without its seed cannot be.
- if (m_seed.is_empty())
+ Array<u8, seed_size> buffer;
+ ScopeGuard const clear_buffer = [&] { secure_zero(buffer.data(), buffer.size()); };
+ auto seed = TRY(this->seed(buffer));
+ if (seed.is_empty())
return Error::from_string_literal("Cannot export an ML-KEM private key without its seed");
ASN1::Encoder encoder;
- TRY(encoder.write<ReadonlyBytes>(m_seed, ASN1::Class::Context, static_cast<ASN1::Kind>(0)));
+ TRY(encoder.write<ReadonlyBytes>(seed, ASN1::Class::Context, static_cast<ASN1::Kind>(0)));
return encoder.finish();
}
ErrorOr<MLKEM::KeyPairType> MLKEM::parse_mlkem_key(MLKEMSize size, ReadonlyBytes der)
{
- auto encoded_key = TRY(parse_module_lattice_private_key(der, 64, mlkem_expanded_key_size(size)));
+ auto encoded_key = TRY(parse_module_lattice_private_key(der, 64, expanded_key_size(size)));
- // NB: Web Crypto rejects a key in the expandedKey form before it validates the key, so that form is kept as it is.
if (encoded_key.seed.is_empty())
- return KeyPairType { {}, { {}, {}, TRY(ByteBuffer::copy(encoded_key.expanded_key)) } };
-
- auto key_pair = TRY(generate_key_pair(size, TRY(ByteBuffer::copy(encoded_key.seed))));
- if (!encoded_key.expanded_key.is_empty() && key_pair.private_key.private_key() != encoded_key.expanded_key)
- return Error::from_string_literal("The expanded key does not match the seed");
+ return KeyPairType { {}, MLKEMPrivateKey::in_expanded_key_form(size) };
+
+ auto key_pair = TRY(generate_key_pair(size, encoded_key.seed));
+ if (!encoded_key.expanded_key.is_empty()) {
+ auto expanded_key = TRY(key_pair.private_key.expanded_key());
+ ScopeGuard const clear_expanded_key = [&] { secure_zero(expanded_key.data(), expanded_key.size()); };
+ if (expanded_key != encoded_key.expanded_key)
+ return Error::from_string_literal("The expanded key does not match the seed");
+ }
return key_pair;
}
+ErrorOr<MLKEM::KeyPairType> MLKEM::generate_key_pair(MLKEMSize size, ReadonlyBytes seed)
+{
+ auto private_key = TRY(MLKEMPrivateKey::generate(size, seed));
+ auto public_key = TRY(MLKEMPublicKey::from_bytes(private_key.public_key()));
+ return KeyPairType { move(public_key), move(private_key) };
+}
+
ErrorOr<MLKEMEncapsulation> MLKEM::encapsulate(MLKEMSize size, MLKEMPublicKey const& key)
{
- auto public_key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_public_key_ex(nullptr, mlkem_size_to_openssl_name(size), nullptr, key.public_key().data(), key.public_key().size())));
+ if (!key.size().has_value() || *key.size() != size)
+ return Error::from_string_literal("The key fails the encapsulation key check");
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, public_key.ptr(), nullptr)));
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.openssl_key(), nullptr)));
OPENSSL_TRY(EVP_PKEY_encapsulate_init(ctx.ptr(), nullptr));
@@ -94,37 +202,15 @@ ErrorOr<MLKEMEncapsulation> MLKEM::encapsulate(MLKEMSize size, MLKEMPublicKey co
OPENSSL_TRY(EVP_PKEY_encapsulate(ctx.ptr(), ciphertext.data(), &ciphertext_length, shared_key.data(), &shared_key_size));
- return MLKEMEncapsulation { shared_key, ciphertext };
-}
-
-static ErrorOr<OpenSSL_PKEY> private_key_to_openssl_pkey(MLKEMSize size, MLKEMPrivateKey const& private_key)
-{
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, mlkem_size_to_openssl_name(size), nullptr)));
-
- OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));
-
- auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());
- ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); };
-
- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_ML_KEM_SEED, private_key.seed().data(), private_key.seed().size()));
- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, private_key.public_key().data(), private_key.public_key().size()));
- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(params_bld, OSSL_PKEY_PARAM_PRIV_KEY, private_key.private_key().data(), private_key.private_key().size()));
-
- auto* params = OSSL_PARAM_BLD_to_param(params_bld);
- ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };
-
- auto key = TRY(OpenSSL_PKEY::create());
- auto* key_ptr = key.ptr();
- OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key_ptr, EVP_PKEY_KEYPAIR, params));
-
- return key;
+ return MLKEMEncapsulation { move(shared_key), move(ciphertext) };
}
-ErrorOr<ByteBuffer> MLKEM::decapsulate(MLKEMSize size, MLKEMPrivateKey const& key, ByteBuffer ciphertext)
+ErrorOr<ByteBuffer> MLKEM::decapsulate(MLKEMSize size, MLKEMPrivateKey const& key, ReadonlyBytes ciphertext)
{
- auto private_key = TRY(private_key_to_openssl_pkey(size, key));
+ if (key.size() != size)
+ return Error::from_string_literal("The key is for a different ML-KEM parameter set");
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, private_key.ptr(), nullptr)));
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.openssl_key(), nullptr)));
OPENSSL_TRY(EVP_PKEY_decapsulate_init(ctx.ptr(), nullptr));
@@ -137,34 +223,4 @@ ErrorOr<ByteBuffer> MLKEM::decapsulate(MLKEMSize size, MLKEMPrivateKey const& ke
return shared_key;
}
-ErrorOr<MLKEM::KeyPairType> MLKEM::generate_key_pair(MLKEMSize size, ByteBuffer seed)
-{
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, mlkem_size_to_openssl_name(size), nullptr)));
-
- OPENSSL_TRY(EVP_PKEY_keygen_init(ctx.ptr()));
-
- OSSL_PARAM params[2] = {
- OSSL_PARAM_END,
- OSSL_PARAM_END
- };
-
- if (!seed.is_empty()) {
- params[0] = OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ML_KEM_SEED, seed.data(), seed.size());
- }
-
- OPENSSL_TRY(EVP_PKEY_CTX_set_params(ctx.ptr(), params));
- auto key = TRY(OpenSSL_PKEY::create());
- auto* key_ptr = key.ptr();
- OPENSSL_TRY(EVP_PKEY_generate(ctx.ptr(), &key_ptr));
-
- auto pub = TRY(get_byte_buffer_param_from_key(key, OSSL_PKEY_PARAM_PUB_KEY));
- auto priv = TRY(get_byte_buffer_param_from_key(key, OSSL_PKEY_PARAM_PRIV_KEY));
- seed = TRY(get_byte_buffer_param_from_key(key, OSSL_PKEY_PARAM_ML_KEM_SEED));
-
- return KeyPairType {
- MLKEMPublicKey { pub },
- { seed, pub, priv }
- };
-}
-
}
diff --git a/Libraries/LibCrypto/PK/MLKEM.h b/Libraries/LibCrypto/PK/MLKEM.h
index 4b6b3a7e4df..f57982b165f 100644
--- a/Libraries/LibCrypto/PK/MLKEM.h
+++ b/Libraries/LibCrypto/PK/MLKEM.h
@@ -8,6 +8,8 @@
#include <AK/ByteBuffer.h>
#include <AK/Error.h>
+#include <AK/Optional.h>
+#include <LibCrypto/OpenSSL.h>
namespace Crypto::PK {
@@ -19,48 +21,66 @@ enum class MLKEMSize {
class MLKEMPublicKey {
public:
- explicit MLKEMPublicKey(ByteBuffer m_public_key)
- : m_public_key(move(m_public_key))
- {
- }
-
MLKEMPublicKey() = default;
+ // NB: Any bytes make a key. Web Crypto only runs the encapsulation key check of FIPS 203, section 7.2, when the key
+ // is used, so its result is kept for then.
+ static ErrorOr<MLKEMPublicKey> from_bytes(ReadonlyBytes);
+
+ // The parameter set that the key passes the encapsulation key check for, if any.
+ Optional<MLKEMSize> size() const { return m_size; }
ByteBuffer const& public_key() const { return m_public_key; }
+ // NB: A key that fails the encapsulation key check has none.
+ EVP_PKEY* openssl_key() const { return m_key.ptr(); }
+
private:
+ OpenSSL_SharedPKEY m_key;
ByteBuffer m_public_key;
+ Optional<MLKEMSize> m_size;
};
class MLKEMPrivateKey {
public:
- MLKEMPrivateKey(ByteBuffer seed, ByteBuffer public_key, ByteBuffer private_key)
- : m_seed(move(seed))
- , m_public_key(move(public_key))
- , m_private_key(move(private_key))
- {
- }
-
MLKEMPrivateKey() = default;
- void clear_sensitive_data();
+ // An empty seed generates a new key.
+ static ErrorOr<MLKEMPrivateKey> generate(MLKEMSize, ReadonlyBytes seed);
- ByteBuffer const& seed() const { return m_seed; }
+ // A key that was given in the expandedKey form, which Web Crypto rejects once it has parsed it. It has no seed,
+ // public key or OpenSSL key, since OpenSSL would refuse an expanded key that is not valid.
+ static MLKEMPrivateKey in_expanded_key_form(MLKEMSize);
+
+ MLKEMSize size() const { return m_size; }
+ static constexpr size_t seed_size = 64;
+
+ bool has_seed() const { return m_key.ptr(); }
+ // NB: OpenSSL keeps the seed, so that no copy of it is left behind when a key is moved or replaced. It is written
+ // into the caller's buffer, which the caller clears.
+ ErrorOr<ReadonlyBytes> seed(Bytes buffer) const;
ByteBuffer const& public_key() const { return m_public_key; }
- ByteBuffer const& private_key() const { return m_private_key; }
+ ErrorOr<ByteBuffer> expanded_key() const;
ErrorOr<ByteBuffer> export_as_der() const;
+ EVP_PKEY* openssl_key() const { return m_key.ptr(); }
+
private:
- ByteBuffer m_seed;
+ MLKEMPrivateKey(OpenSSL_SharedPKEY key, ByteBuffer public_key, MLKEMSize size)
+ : m_key(move(key))
+ , m_public_key(move(public_key))
+ , m_size(size)
+ {
+ }
+
+ OpenSSL_SharedPKEY m_key;
ByteBuffer m_public_key;
- ByteBuffer m_private_key;
+ MLKEMSize m_size { MLKEMSize::MLKEM512 };
};
-template<typename PubKey, typename PrivKey>
struct MLKEMKeyPair {
- PubKey public_key;
- PrivKey private_key;
+ MLKEMPublicKey public_key;
+ MLKEMPrivateKey private_key;
};
struct MLKEMEncapsulation {
@@ -69,17 +89,14 @@ struct MLKEMEncapsulation {
};
class MLKEM {
- using PublicKeyType = MLKEMPublicKey;
- using PrivateKeyType = MLKEMPrivateKey;
-
public:
- using KeyPairType = MLKEMKeyPair<PublicKeyType, PrivateKeyType>;
+ using KeyPairType = MLKEMKeyPair;
static ErrorOr<KeyPairType> parse_mlkem_key(MLKEMSize, ReadonlyBytes der);
+ static ErrorOr<KeyPairType> generate_key_pair(MLKEMSize, ReadonlyBytes seed = {});
- static ErrorOr<MLKEMEncapsulation> encapsulate(MLKEMSize size, MLKEMPublicKey const& key);
- static ErrorOr<ByteBuffer> decapsulate(MLKEMSize size, MLKEMPrivateKey const& key, ByteBuffer ciphertext);
- static ErrorOr<KeyPairType> generate_key_pair(MLKEMSize size, ByteBuffer seed = {});
+ static ErrorOr<MLKEMEncapsulation> encapsulate(MLKEMSize, MLKEMPublicKey const&);
+ static ErrorOr<ByteBuffer> decapsulate(MLKEMSize, MLKEMPrivateKey const&, ReadonlyBytes ciphertext);
};
-};
+}
diff --git a/Libraries/LibCrypto/Rust/src/ffi.rs b/Libraries/LibCrypto/Rust/src/ffi.rs
index 89a6e56786b..e40fcb3e042 100644
--- a/Libraries/LibCrypto/Rust/src/ffi.rs
+++ b/Libraries/LibCrypto/Rust/src/ffi.rs
@@ -381,7 +381,7 @@ unsafe extern "C" {
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_seed_bytes(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> bool;
pub(super) fn crypto_mldsa_export_der(
key: *const c_void,
is_public: bool,
@@ -398,7 +398,8 @@ unsafe extern "C" {
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_seed_bytes(key: *const c_void, state: *mut c_void, receive: ReceiveBytes) -> bool;
+ pub(super) fn crypto_ml_private_key_has_seed(key: *const c_void) -> bool;
pub(super) fn crypto_mlkem_export_der(
key: *const c_void,
is_public: bool,
diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rs
index 65579abd0ed..9716557c1b6 100644
--- a/Libraries/LibCrypto/Rust/src/lib.rs
+++ b/Libraries/LibCrypto/Rust/src/lib.rs
@@ -845,11 +845,11 @@ pub fn mldsa_generate_key_pair(size: MlDsaSize, seed: &[u8]) -> Result<KeyPair,
Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
}
-pub fn mldsa_read_public_key(bytes: &[u8]) -> KeyHandle {
+pub fn mldsa_read_public_key(bytes: &[u8]) -> Option<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")
+ // SAFETY: A non-null result transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }
}
pub fn mldsa_public_bytes(key: &KeyHandle) -> &[u8] {
@@ -859,11 +859,12 @@ pub fn mldsa_public_bytes(key: &KeyHandle) -> &[u8] {
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_seed_bytes(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_mldsa_seed_bytes(key.as_raw(), state, receive) });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
}
pub fn mldsa_export_der(key: &KeyHandle, is_public: bool, oid: &[u32]) -> Result<Vec<u8>, BackendError> {
@@ -886,11 +887,11 @@ pub fn mlkem_generate_key_pair(size: MlKemSize, seed: &[u8]) -> Result<KeyPair,
Ok(unsafe { KeyPair::from_raw(public_key, private_key) })
}
-pub fn mlkem_read_public_key(bytes: &[u8]) -> KeyHandle {
+pub fn mlkem_read_public_key(bytes: &[u8]) -> Option<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")
+ // SAFETY: A non-null result transfers ownership of the key.
+ unsafe { KeyHandle::from_raw(raw) }
}
pub fn mlkem_public_bytes(key: &KeyHandle) -> Vec<u8> {
@@ -900,11 +901,18 @@ pub fn mlkem_public_bytes(key: &KeyHandle) -> Vec<u8> {
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_seed_bytes(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_mlkem_seed_bytes(key.as_raw(), state, receive) });
+ status.then_some(()).ok_or(BackendError)?;
+ Ok(bytes)
+}
+
+/// Whether an ML-DSA or ML-KEM private key has its seed, which a key given in the expandedKey form does not.
+pub fn ml_private_key_has_seed(key: &KeyHandle) -> bool {
+ // SAFETY: The key is borrowed for the call.
+ unsafe { ffi::crypto_ml_private_key_has_seed(key.as_raw()) }
}
pub fn mlkem_export_der(key: &KeyHandle, is_public: bool, oid: &[u32]) -> Result<Vec<u8>, BackendError> {
diff --git a/Libraries/LibCrypto/RustBindings.cpp b/Libraries/LibCrypto/RustBindings.cpp
index 61f644406db..9cfe7c762e0 100644
--- a/Libraries/LibCrypto/RustBindings.cpp
+++ b/Libraries/LibCrypto/RustBindings.cpp
@@ -9,6 +9,7 @@
*/
#include <AK/AnyOf.h>
+#include <AK/Array.h>
#include <AK/Memory.h>
#include <AK/Random.h>
#include <LibCrypto/ASN1/ASN1.h>
@@ -29,6 +30,7 @@
#include <LibCrypto/PK/EC.h>
#include <LibCrypto/PK/MLDSA.h>
#include <LibCrypto/PK/MLKEM.h>
+#include <LibCrypto/PK/PK.h>
#include <LibCrypto/PK/RSA.h>
namespace Crypto {
@@ -135,8 +137,6 @@ void crypto_asn1_delete_key_info(Asn1Structure structure, void* key_info)
}
VERIFY(structure == Asn1Structure::PrivateKeyInfo);
auto* storage = static_cast<PrivateKeyStorage*>(key_info);
- storage->value.mldsa.clear_sensitive_data();
- storage->value.mlkem.clear_sensitive_data();
secure_zero(storage->value.raw_key.data(), storage->value.raw_key.size());
delete storage;
}
@@ -767,7 +767,7 @@ void crypto_asn1_key_info_identifier(Asn1Structure, void const*, ReadonlySpan<u3
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_seed_bytes(KeyHandle const*, void*, ReceiveEncodedBytes);
bool crypto_mldsa_export_der(KeyHandle const*, bool, ReadonlySpan<u32>, void*, ReceiveEncodedBytes);
}
@@ -792,7 +792,7 @@ bool crypto_mldsa_verify(::Crypto::PK::MLDSASize size, KeyHandle const* key, Rea
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)));
+ auto key_pair = ::Crypto::PK::MLDSA::generate_key_pair(size, 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));
@@ -812,7 +812,10 @@ KeyHandle* crypto_mldsa_key_info_read_private_key(void const* key_info)
KeyHandle* crypto_mldsa_read_public_key(ReadonlyBytes bytes)
{
- return new KeyHandle(::Crypto::PK::MLDSAPublicKey { MUST(ByteBuffer::copy(bytes)) });
+ auto public_key = ::Crypto::PK::MLDSAPublicKey::from_bytes(bytes);
+ if (public_key.is_error())
+ return nullptr;
+ return new KeyHandle(public_key.release_value());
}
void crypto_mldsa_public_bytes(KeyHandle const* key, ReadonlyBytes* bytes)
@@ -823,9 +826,15 @@ void crypto_mldsa_public_bytes(KeyHandle const* key, ReadonlyBytes* bytes)
[](auto const&) -> ReadonlyBytes { VERIFY_NOT_REACHED(); });
}
-void crypto_mldsa_seed_bytes(KeyHandle const* key, ReadonlyBytes* bytes)
+bool crypto_mldsa_seed_bytes(KeyHandle const* key, void* state, ReceiveEncodedBytes receive)
{
- *bytes = key->get<::Crypto::PK::MLDSAPrivateKey>().seed();
+ Array<u8, ::Crypto::PK::MLDSAPrivateKey::seed_size> buffer;
+ ScopeGuard const clear_buffer = [&] { secure_zero(buffer.data(), buffer.size()); };
+ auto seed = key->get<::Crypto::PK::MLDSAPrivateKey>().seed(buffer);
+ if (seed.is_error())
+ return false;
+ receive(state, seed.value());
+ return true;
}
bool crypto_mldsa_export_der(KeyHandle const* key, bool is_public, ReadonlySpan<u32> oid, void* state, ReceiveEncodedBytes receive)
@@ -845,7 +854,7 @@ FlatPtr crypto_mlkem_generate_key_pair(::Crypto::PK::MLKEMSize, ReadonlyBytes, K
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_seed_bytes(KeyHandle const*, void*, ReceiveEncodedBytes);
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);
@@ -857,7 +866,7 @@ 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)));
+ auto key_pair = ::Crypto::PK::MLKEM::generate_key_pair(size, 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));
@@ -872,7 +881,10 @@ KeyHandle* crypto_mlkem_key_info_read_private_key(void const* key_info)
KeyHandle* crypto_mlkem_read_public_key(ReadonlyBytes bytes)
{
- return new KeyHandle(::Crypto::PK::MLKEMPublicKey { MUST(ByteBuffer::copy(bytes)) });
+ auto public_key = ::Crypto::PK::MLKEMPublicKey::from_bytes(bytes);
+ if (public_key.is_error())
+ return nullptr;
+ return new KeyHandle(public_key.release_value());
}
void crypto_mlkem_public_bytes(KeyHandle const* key, void* state, ReceiveEncodedBytes receive)
@@ -880,9 +892,25 @@ void crypto_mlkem_public_bytes(KeyHandle const* key, void* state, ReceiveEncoded
receive(state, key->get<::Crypto::PK::MLKEMPublicKey>().public_key());
}
-void crypto_mlkem_seed_bytes(KeyHandle const* key, ReadonlyBytes* bytes)
+bool crypto_mlkem_seed_bytes(KeyHandle const* key, void* state, ReceiveEncodedBytes receive)
{
- *bytes = key->get<::Crypto::PK::MLKEMPrivateKey>().seed();
+ Array<u8, ::Crypto::PK::MLKEMPrivateKey::seed_size> buffer;
+ ScopeGuard const clear_buffer = [&] { secure_zero(buffer.data(), buffer.size()); };
+ auto seed = key->get<::Crypto::PK::MLKEMPrivateKey>().seed(buffer);
+ if (seed.is_error())
+ return false;
+ receive(state, seed.value());
+ return true;
+}
+
+extern "C" bool crypto_ml_private_key_has_seed(KeyHandle const*);
+
+bool crypto_ml_private_key_has_seed(KeyHandle const* key)
+{
+ return key->visit(
+ [](::Crypto::PK::MLDSAPrivateKey const& private_key) { return private_key.has_seed(); },
+ [](::Crypto::PK::MLKEMPrivateKey const& private_key) { return private_key.has_seed(); },
+ [](auto const&) -> bool { VERIFY_NOT_REACHED(); });
}
bool crypto_mlkem_export_der(KeyHandle const* key, bool is_public, ReadonlySpan<u32> oid, void* state, ReceiveEncodedBytes receive)
@@ -904,15 +932,17 @@ FlatPtr crypto_mlkem_encapsulate(::Crypto::PK::MLKEMSize size, KeyHandle const*
return Utf16String::formatted("{}", result.error()).into_raw();
receive(shared_key, result.value().shared_key);
receive(ciphertext, result.value().ciphertext);
+ secure_zero(result.value().shared_key.data(), result.value().shared_key.size());
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)));
+ auto result = ::Crypto::PK::MLKEM::decapsulate(size, key->get<::Crypto::PK::MLKEMPrivateKey>(), ciphertext);
if (result.is_error())
return Utf16String::formatted("{}", result.error()).into_raw();
receive(state, result.value());
+ secure_zero(result.value().data(), result.value().size());
return 0;
}
@@ -1055,10 +1085,10 @@ KeyHandle* crypto_public_key_for_private_key(KeyHandle const* key, FlatPtr raw_n
return TRY(private_key.derive_public_key());
},
[](::Crypto::PK::MLDSAPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
- return ::Crypto::PK::MLDSAPublicKey { private_key.public_key() };
+ return TRY(::Crypto::PK::MLDSAPublicKey::from_bytes(private_key.public_key()));
},
[](::Crypto::PK::MLKEMPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
- return ::Crypto::PK::MLKEMPublicKey { private_key.public_key() };
+ return TRY(::Crypto::PK::MLKEMPublicKey::from_bytes(private_key.public_key()));
},
[&](OKPPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
auto name = Utf16String::from_raw(raw_name);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index f67b2b809d8..3e398eba736 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -12412,8 +12412,11 @@ const ML_DSA_44_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 3, 17];
const ML_DSA_65_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 3, 18];
const ML_DSA_87_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 3, 19];
-fn mldsa_read_public_key(vm: &Vm, bytes: &[u8]) -> Ref<CryptoKey> {
- CryptoKey::create(vm, libcrypto_rust::mldsa_read_public_key(bytes))
+fn mldsa_read_public_key(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Ref<CryptoKey>> {
+ let Some(key) = libcrypto_rust::mldsa_read_public_key(bytes) else {
+ return Err(dom_error("DataError", b"Invalid key"));
+ };
+ Ok(CryptoKey::create(vm, key))
}
fn generate_mldsa_key_pair_from_seed(name: &Utf16String, seed: &Bytes) -> Result<KeyPair, Utf16String> {
@@ -12733,7 +12736,7 @@ impl AlgorithmMethods for MlDsa {
let public_key = spki.raw_key();
// 8. Let key be a new CryptoKey that represents publicKey.
- key = mldsa_read_public_key(cx.vm(), public_key);
+ key = mldsa_read_public_key(cx.vm(), public_key)?;
// 9. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -12808,7 +12811,7 @@ impl AlgorithmMethods for MlDsa {
// represents an ML-DSA key in the both format and the both format is not supported, throw a
// NotSupportedError.
// NB: A key in the expandedKey format has no seed.
- if libcrypto_rust::mldsa_seed_bytes(&ml_dsa_private_key).is_empty() {
+ if !libcrypto_rust::ml_private_key_has_seed(&ml_dsa_private_key) {
return Err(dom_error(
"NotSupportedError",
b"ML-DSA private keys in the expandedKey format are not supported",
@@ -12848,7 +12851,7 @@ impl AlgorithmMethods for MlDsa {
let ImportKeyData::Bytes(key_data) = key_data else {
unreachable!("raw key data contains bytes")
};
- key = mldsa_read_public_key(cx.vm(), key_data.as_slice());
+ key = mldsa_read_public_key(cx.vm(), key_data.as_slice())?;
// 5. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -13004,7 +13007,7 @@ impl AlgorithmMethods for MlDsa {
// 2. Let key be a new CryptoKey object that represents the ML-DSA public key
// identified by interpreting the pub attribute of jwk as a base64url encoded public key.
- key = mldsa_read_public_key(cx.vm(), public_key.as_slice());
+ key = mldsa_read_public_key(cx.vm(), public_key.as_slice())?;
// 3. Set the [[type]] internal slot of key to "public".
key.set_type(KeyType::Public);
@@ -13156,8 +13159,8 @@ impl AlgorithmMethods for MlDsa {
// 2. Let data be a byte sequence containing the ξ seed variable of the key represented by the [[handle]] internal slot of key.
// Note: The ξ value is the seed from which the key was generated or imported, as used by
// ML-DSA.KeyGen_internal in Section 6.1 of [FIPS-204].
- let bytes = libcrypto_rust::mldsa_seed_bytes(handle);
- let data = Bytes::new(copy_bytes(vm, bytes)?);
+ let seed = libcrypto_rust::mldsa_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
+ let data = Bytes::new(seed);
// 3. Let result be data.
ExportKeyResult::Bytes(data)
@@ -13182,8 +13185,8 @@ impl AlgorithmMethods for MlDsa {
// 6. -> If the [[type]] internal slot of key is "private":
// Set the priv attribute of jwk to the base64url encoded seed represented by the [[handle]] internal slot of key.
if key.key_type() == KeyType::Private {
- let seed = libcrypto_rust::mldsa_seed_bytes(handle);
- jwk.r#priv = Some(base64_url_bytes_encode(seed));
+ let seed = libcrypto_rust::mldsa_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
+ jwk.r#priv = Some(base64_url_bytes_encode(&seed));
}
// 7. Set the key_ops attribute of jwk to the usages attribute of key.
@@ -13219,8 +13222,11 @@ const ML_KEM_512_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 1];
const ML_KEM_768_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 2];
const ML_KEM_1024_OID: [u32; 9] = [2, 16, 840, 1, 101, 3, 4, 4, 3];
-fn mlkem_read_public_key(vm: &Vm, bytes: &[u8]) -> Ref<CryptoKey> {
- CryptoKey::create(vm, libcrypto_rust::mlkem_read_public_key(bytes))
+fn mlkem_read_public_key(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Ref<CryptoKey>> {
+ let Some(key) = libcrypto_rust::mlkem_read_public_key(bytes) else {
+ return Err(dom_error("DataError", b"Invalid key"));
+ };
+ Ok(CryptoKey::create(vm, key))
}
fn mlkem_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, oid: &[u32]) -> WebIdlResult<Bytes> {
@@ -13404,7 +13410,7 @@ impl AlgorithmMethods for MlKem {
let public_key = spki.raw_key();
// 8. Let key be a new CryptoKey that represents publicKey.
- key = mlkem_read_public_key(cx.vm(), public_key);
+ key = mlkem_read_public_key(cx.vm(), public_key)?;
// 9. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -13479,7 +13485,7 @@ impl AlgorithmMethods for MlKem {
// represents an ML-KEM key in the both format and the both format is not supported, throw a
// NotSupportedError.
// NB: A key in the expandedKey format has no seed.
- if libcrypto_rust::mlkem_seed_bytes(&ml_kem_private_key).is_empty() {
+ if !libcrypto_rust::ml_private_key_has_seed(&ml_kem_private_key) {
return Err(dom_error(
"NotSupportedError",
b"ML-KEM private keys in the expandedKey format are not supported",
@@ -13521,7 +13527,7 @@ impl AlgorithmMethods for MlKem {
};
// 3. Let key be a new CryptoKey that represents the ML-KEM public key data in data.
- key = mlkem_read_public_key(cx.vm(), data.as_slice());
+ key = mlkem_read_public_key(cx.vm(), data.as_slice())?;
// 4. Set the [[type]] internal slot of key to "public"
key.set_type(KeyType::Public);
@@ -13766,8 +13772,8 @@ impl AlgorithmMethods for MlKem {
// key represented by the [[handle]] internal slot of key.
// Note: The d and z values are the seed from which the key was generated or imported, as used by
// ML-KEM.KeyGen_internal in Section 6.1 of [FIPS-203].
- let seed = libcrypto_rust::mlkem_seed_bytes(handle);
- let data = Bytes::new(copy_bytes(vm, seed)?);
+ let seed = libcrypto_rust::mlkem_seed_bytes(handle).map_err(|_| out_of_memory(vm))?;
+ let data = Bytes::new(seed);
// 3. Let result be data.
ExportKeyResult::Bytes(data)
@@ -13818,7 +13824,7 @@ impl AlgorithmMethods for MlKem {
// Note: The result of this check may be cached or precomputed for the CryptoKey object if desirable for
// performance.
// 3. If the encapsulation key check failed, throw an OperationError.
- // NOTE: Presumably done by OpenSSL for us
+ // NB: LibCrypto does this check when it builds the key, and encapsulation fails for a key that failed it.
// 4. Let sharedKey and ciphertext be the outputs that result from performing the ML-KEM.Encaps function
// described in Section 7.2 of [FIPS-203] with the parameter set indicated by the name member of algorithm,
@@ -13874,7 +13880,7 @@ impl AlgorithmMethods for MlKem {
// Note: The result of the decapsulation key type check and the hash check may be cached or precomputed for the
// CryptoKey object if desirable for performance.
// 3. If the decapsulation input check failed, throw an OperationError.
- // NOTE: Presumably done by OpenSSL for us
+ // NB: LibCrypto does this check when it builds the key, and encapsulation fails for a key that failed it.
// 4. Let sharedKey be the output that results from performing the ML-KEM.Decaps function described in Section
// 7.3 of [FIPS-203] with the parameter set indicated by the name member of algorithm, using the key
diff --git a/Tests/LibCrypto/TestMLDSA.cpp b/Tests/LibCrypto/TestMLDSA.cpp
index c471a43a12c..44e1042b2da 100644
--- a/Tests/LibCrypto/TestMLDSA.cpp
+++ b/Tests/LibCrypto/TestMLDSA.cpp
@@ -8,15 +8,20 @@
#include <LibCrypto/PK/MLDSA.h>
#include <LibTest/TestCase.h>
+static ByteBuffer seed_of(Crypto::PK::MLDSAPrivateKey const& key)
+{
+ Array<u8, Crypto::PK::MLDSAPrivateKey::seed_size> buffer;
+ return MUST(ByteBuffer::copy(MUST(key.seed(buffer))));
+}
+
TEST_CASE(TEST_SIGN_AND_VERIFY)
{
u8 message_bytes[12] = { 0x48, 0X65, 0X6C, 0X6C, 0X6F, 0X20, 0X57, 0X6F, 0X72, 0X6C, 0X64, 0X21 }; // "Hello World!"
ReadonlyBytes message(message_bytes, 12);
- auto [_, private_key] = TRY_OR_FAIL(Crypto::PK::MLDSA::generate_key_pair(Crypto::PK::MLDSA65));
+ auto [public_key, private_key] = TRY_OR_FAIL(Crypto::PK::MLDSA::generate_key_pair(Crypto::PK::MLDSA65));
- Crypto::PK::MLDSAPublicKey public_key { private_key.public_key() };
auto size = Crypto::PK::MLDSA65;
auto const signed_message = TRY_OR_FAIL(Crypto::PK::mldsa_sign(size, private_key, {}, message));
@@ -51,24 +56,26 @@ static ByteBuffer encode_both(ReadonlyBytes seed, ReadonlyBytes expanded_key)
TEST_CASE(expanded_key)
{
auto key_pair = generate_key_pair_from_seed(0);
+ auto expanded_key = TRY_OR_FAIL(key_pair.private_key.expanded_key());
Crypto::ASN1::Encoder encoder;
- MUST(encoder.write<ReadonlyBytes>(key_pair.private_key.private_key(), Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::OctetString));
+ MUST(encoder.write<ReadonlyBytes>(expanded_key, Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::OctetString));
auto der = encoder.finish();
auto parsed = TRY_OR_FAIL(Crypto::PK::MLDSA::parse_mldsa_key(Crypto::PK::MLDSA44, der));
- EXPECT(parsed.private_key.seed().is_empty());
- EXPECT_EQ(parsed.private_key.private_key(), key_pair.private_key.private_key());
+ EXPECT(!parsed.private_key.has_seed());
+ EXPECT(TRY_OR_FAIL(parsed.private_key.expanded_key()).is_empty());
EXPECT(parsed.private_key.export_as_der().is_error());
}
TEST_CASE(expanded_key_in_a_constructed_octet_string)
{
auto key_pair = generate_key_pair_from_seed(0);
+ auto expanded_key = TRY_OR_FAIL(key_pair.private_key.expanded_key());
Crypto::ASN1::Encoder encoder;
MUST(encoder.write_constructed(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::OctetString, [&] {
- return encoder.write<ReadonlyBytes>(key_pair.private_key.private_key(), Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::OctetString);
+ return encoder.write<ReadonlyBytes>(expanded_key, Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::OctetString);
}));
auto der = encoder.finish();
@@ -78,18 +85,22 @@ TEST_CASE(expanded_key_in_a_constructed_octet_string)
TEST_CASE(seed_and_expanded_key)
{
auto key_pair = generate_key_pair_from_seed(0);
- auto der = encode_both(key_pair.private_key.seed(), key_pair.private_key.private_key());
+ auto expanded_key = TRY_OR_FAIL(key_pair.private_key.expanded_key());
+ auto seed = seed_of(key_pair.private_key);
+ auto der = encode_both(seed, expanded_key);
auto parsed = TRY_OR_FAIL(Crypto::PK::MLDSA::parse_mldsa_key(Crypto::PK::MLDSA44, der));
- EXPECT_EQ(parsed.private_key.seed(), key_pair.private_key.seed());
- EXPECT_EQ(parsed.private_key.private_key(), key_pair.private_key.private_key());
+ EXPECT_EQ(seed_of(parsed.private_key), seed_of(key_pair.private_key));
+ EXPECT_EQ(TRY_OR_FAIL(parsed.private_key.expanded_key()), expanded_key);
}
TEST_CASE(seed_and_expanded_key_of_another_seed)
{
auto key_pair = generate_key_pair_from_seed(0);
auto other_key_pair = generate_key_pair_from_seed(1);
- auto der = encode_both(key_pair.private_key.seed(), other_key_pair.private_key.private_key());
+ auto other_expanded_key = TRY_OR_FAIL(other_key_pair.private_key.expanded_key());
+ auto seed = seed_of(key_pair.private_key);
+ auto der = encode_both(seed, other_expanded_key);
EXPECT(Crypto::PK::MLDSA::parse_mldsa_key(Crypto::PK::MLDSA44, der).is_error());
}
@@ -107,5 +118,5 @@ TEST_CASE(expanded_key_that_is_not_a_valid_key)
u8 header[] = { 0x04, 0x82, 0x0a, 0x00 };
der.overwrite(0, header, sizeof(header));
auto parsed = TRY_OR_FAIL(Crypto::PK::MLDSA::parse_mldsa_key(Crypto::PK::MLDSA44, der));
- EXPECT(parsed.private_key.seed().is_empty());
+ EXPECT(!parsed.private_key.has_seed());
}
diff --git a/Tests/LibCrypto/TestMLKEM.cpp b/Tests/LibCrypto/TestMLKEM.cpp
index e1bce5d9170..bc0c71a8160 100644
--- a/Tests/LibCrypto/TestMLKEM.cpp
+++ b/Tests/LibCrypto/TestMLKEM.cpp
@@ -13,6 +13,12 @@ using Crypto::ASN1::Kind;
using Crypto::PK::MLKEM;
using Crypto::PK::MLKEMSize;
+static ByteBuffer seed_of(Crypto::PK::MLKEMPrivateKey const& key)
+{
+ Array<u8, Crypto::PK::MLKEMPrivateKey::seed_size> buffer;
+ return MUST(ByteBuffer::copy(MUST(key.seed(buffer))));
+}
+
static MLKEM::KeyPairType generate_key_pair(u8 first_seed_byte)
{
auto seed = MUST(ByteBuffer::create_zeroed(64));
@@ -35,24 +41,26 @@ static ByteBuffer encode_both(ReadonlyBytes seed, ReadonlyBytes expanded_key)
TEST_CASE(expanded_key)
{
auto key_pair = generate_key_pair(0);
+ auto expanded_key = TRY_OR_FAIL(key_pair.private_key.expanded_key());
Crypto::ASN1::Encoder encoder;
- MUST(encoder.write<ReadonlyBytes>(key_pair.private_key.private_key(), Class::Universal, Kind::OctetString));
+ MUST(encoder.write<ReadonlyBytes>(expanded_key, Class::Universal, Kind::OctetString));
auto der = encoder.finish();
auto parsed = TRY_OR_FAIL(MLKEM::parse_mlkem_key(MLKEMSize::MLKEM512, der));
- EXPECT(parsed.private_key.seed().is_empty());
- EXPECT_EQ(parsed.private_key.private_key(), key_pair.private_key.private_key());
+ EXPECT(!parsed.private_key.has_seed());
+ EXPECT(TRY_OR_FAIL(parsed.private_key.expanded_key()).is_empty());
EXPECT(parsed.private_key.export_as_der().is_error());
}
TEST_CASE(expanded_key_in_a_constructed_octet_string)
{
auto key_pair = generate_key_pair(0);
+ auto expanded_key = TRY_OR_FAIL(key_pair.private_key.expanded_key());
Crypto::ASN1::Encoder encoder;
MUST(encoder.write_constructed(Class::Universal, Kind::OctetString, [&] {
- return encoder.write<ReadonlyBytes>(key_pair.private_key.private_key(), Class::Universal, Kind::OctetString);
+ return encoder.write<ReadonlyBytes>(expanded_key, Class::Universal, Kind::OctetString);
}));
auto der = encoder.finish();
@@ -62,18 +70,22 @@ TEST_CASE(expanded_key_in_a_constructed_octet_string)
TEST_CASE(seed_and_expanded_key)
{
auto key_pair = generate_key_pair(0);
- auto der = encode_both(key_pair.private_key.seed(), key_pair.private_key.private_key());
+ auto expanded_key = TRY_OR_FAIL(key_pair.private_key.expanded_key());
+ auto seed = seed_of(key_pair.private_key);
+ auto der = encode_both(seed, expanded_key);
auto parsed = TRY_OR_FAIL(MLKEM::parse_mlkem_key(MLKEMSize::MLKEM512, der));
- EXPECT_EQ(parsed.private_key.seed(), key_pair.private_key.seed());
- EXPECT_EQ(parsed.private_key.private_key(), key_pair.private_key.private_key());
+ EXPECT_EQ(seed_of(parsed.private_key), seed_of(key_pair.private_key));
+ EXPECT_EQ(TRY_OR_FAIL(parsed.private_key.expanded_key()), expanded_key);
}
TEST_CASE(seed_and_expanded_key_of_another_seed)
{
auto key_pair = generate_key_pair(0);
auto other_key_pair = generate_key_pair(1);
- auto der = encode_both(key_pair.private_key.seed(), other_key_pair.private_key.private_key());
+ auto other_expanded_key = TRY_OR_FAIL(other_key_pair.private_key.expanded_key());
+ auto seed = seed_of(key_pair.private_key);
+ auto der = encode_both(seed, other_expanded_key);
EXPECT(MLKEM::parse_mlkem_key(MLKEMSize::MLKEM512, der).is_error());
}
@@ -91,13 +103,14 @@ TEST_CASE(expanded_key_that_is_not_a_valid_key)
u8 header[] = { 0x04, 0x82, 0x06, 0x60 };
der.overwrite(0, header, sizeof(header));
auto parsed = TRY_OR_FAIL(MLKEM::parse_mlkem_key(MLKEMSize::MLKEM512, der));
- EXPECT(parsed.private_key.seed().is_empty());
+ EXPECT(!parsed.private_key.has_seed());
}
TEST_CASE(encodings_that_are_not_der)
{
auto key_pair = generate_key_pair(0);
- auto const& seed = key_pair.private_key.seed();
+ auto expanded_key = TRY_OR_FAIL(key_pair.private_key.expanded_key());
+ auto const& seed = seed_of(key_pair.private_key);
auto parse = [](Vector<u8> const& der) { return MLKEM::parse_mlkem_key(MLKEMSize::MLKEM512, der); };
auto encode = [&](Vector<u8> header, ReadonlyBytes contents, Vector<u8> trailer = {}) {
header.append(contents.data(), contents.size());
@@ -110,7 +123,7 @@ TEST_CASE(encodings_that_are_not_der)
EXPECT(parse(encode({ 0x80, 0x81, 0x40 }, seed)).is_error());
EXPECT(parse(encode({ 0x81, 0x40 }, seed)).is_error());
- auto both = encode_both(seed, key_pair.private_key.private_key());
+ auto both = encode_both(seed, expanded_key);
EXPECT(!parse(encode({}, both)).is_error());
auto both_with_extra_element = encode({ 0x30, 0x82, static_cast<u8>((both.size() - 2) >> 8), static_cast<u8>(both.size() - 2) }, both.bytes().slice(4), { 0x05, 0x00 });
EXPECT(parse(both_with_extra_element).is_error());
diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index fe9ac8e1df6..7adce81ee6d 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -17,6 +17,8 @@
#include <AK/String.h>
#include <AK/Utf16String.h>
#include <AK/Vector.h>
+#include <LibCrypto/PK/MLDSA.h>
+#include <LibCrypto/PK/MLKEM.h>
#include <LibGC/Root.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Color.h>
@@ -671,6 +673,30 @@ inline Vector<CryptoAlgorithmGolden> crypto_algorithm_goldens()
return goldens;
}
+// ML-DSA and ML-KEM key handles must hold real keys, so these come from fixed seeds.
+inline ::Crypto::PK::MLDSA::KeyPairType mldsa_44_key_pair()
+{
+ Array<u8, 32> seed;
+ for (size_t i = 0; i < seed.size(); ++i)
+ seed[i] = i;
+ return MUST(::Crypto::PK::MLDSA::generate_key_pair(::Crypto::PK::MLDSA44, seed));
+}
+
+inline ::Crypto::PK::MLKEM::KeyPairType mlkem_512_key_pair()
+{
+ Array<u8, 64> seed;
+ for (size_t i = 0; i < seed.size(); ++i)
+ seed[i] = i;
+ return MUST(::Crypto::PK::MLKEM::generate_key_pair(::Crypto::PK::MLKEMSize::MLKEM512, seed));
+}
+
+template<typename PrivateKey>
+inline ByteBuffer seed_of(PrivateKey const& key)
+{
+ Array<u8, PrivateKey::seed_size> buffer;
+ return MUST(ByteBuffer::copy(MUST(key.seed(buffer))));
+}
+
inline Vector<CryptoHandleGolden> crypto_handle_goldens()
{
using Web::Crypto::HandleTag;
@@ -680,9 +706,12 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()
auto x = p256_base_point_x();
auto y = p256_base_point_y();
auto d = ec_coordinate(0x33);
- auto seed = "seedseedseedseed"sv.bytes();
- auto pub = "publicpublicpubl"sv.bytes();
- auto priv = "privprivprivpriv"sv.bytes();
+ auto mldsa = mldsa_44_key_pair();
+ auto mldsa_expanded_key = MUST(mldsa.private_key.expanded_key());
+ auto mlkem = mlkem_512_key_pair();
+ auto mlkem_expanded_key = MUST(mlkem.private_key.expanded_key());
+ auto mldsa_seed = seed_of(mldsa.private_key);
+ auto mlkem_seed = seed_of(mlkem.private_key);
auto okp = "okpokpokpokpokpo"sv.bytes();
Array<ReadonlyBytes, 8> rsa_components { modulus, exponent, exponent, modulus, modulus, exponent, exponent, modulus };
@@ -694,10 +723,10 @@ inline Vector<CryptoHandleGolden> crypto_handle_goldens()
alg_rsa_hashed_key_algorithm("RSASSA-PKCS1-v1_5"sv, 2048, exponent, "SHA-256"sv), handle_rsa_private_key(rsa_components) });
goldens.append({ HandleTag::ECPublicKey, "public"sv, "verify"sv, alg_ec_key_algorithm("ECDSA"sv, "P-256"sv), handle_ec_public_key(x, y) });
goldens.append({ HandleTag::ECPrivateKey, "private"sv, "sign"sv, alg_ec_key_algorithm("ECDSA"sv, "P-256"sv), handle_ec_private_key(d, {}, {}) });
- goldens.append({ HandleTag::MLDSAPublicKey, "public"sv, "verify"sv, alg_key_algorithm("ML-DSA-44"sv), handle_single_buffer(5, pub) });
- goldens.append({ HandleTag::MLDSAPrivateKey, "private"sv, "sign"sv, alg_key_algorithm("ML-DSA-44"sv), handle_triple_buffer(6, seed, pub, priv) });
- goldens.append({ HandleTag::MLKEMPublicKey, "public"sv, "encapsulateKey"sv, alg_key_algorithm("ML-KEM-512"sv), handle_single_buffer(7, pub) });
- goldens.append({ HandleTag::MLKEMPrivateKey, "private"sv, "decapsulateKey"sv, alg_key_algorithm("ML-KEM-512"sv), handle_triple_buffer(8, seed, pub, priv) });
+ goldens.append({ HandleTag::MLDSAPublicKey, "public"sv, "verify"sv, alg_key_algorithm("ML-DSA-44"sv), handle_single_buffer(5, mldsa.public_key.public_key()) });
+ goldens.append({ HandleTag::MLDSAPrivateKey, "private"sv, "sign"sv, alg_key_algorithm("ML-DSA-44"sv), handle_triple_buffer(6, mldsa_seed, mldsa.private_key.public_key(), mldsa_expanded_key) });
+ goldens.append({ HandleTag::MLKEMPublicKey, "public"sv, "encapsulateKey"sv, alg_key_algorithm("ML-KEM-512"sv), handle_single_buffer(7, mlkem.public_key.public_key()) });
+ goldens.append({ HandleTag::MLKEMPrivateKey, "private"sv, "decapsulateKey"sv, alg_key_algorithm("ML-KEM-512"sv), handle_triple_buffer(8, mlkem_seed, mlkem.private_key.public_key(), mlkem_expanded_key) });
goldens.append({ HandleTag::OKPPublicKey, "public"sv, "verify"sv, alg_key_algorithm("Ed25519"sv), handle_single_buffer(9, okp) });
goldens.append({ HandleTag::OKPPrivateKey, "private"sv, "sign"sv, alg_key_algorithm("Ed25519"sv), handle_single_buffer(10, okp) });
return goldens;
diff --git a/Tests/LibWeb/TestStructuredSerializeDurability.cpp b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
index f1555bb9c7d..5db8c8779f1 100644
--- a/Tests/LibWeb/TestStructuredSerializeDurability.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
@@ -614,6 +614,35 @@ TEST_CASE(crypto_key_with_an_invalid_ec_point_is_a_data_clone_error)
EXPECT_EQ(unwrap_wrappable<Web::WebIDL::DOMException>(result.error_value()).name(), "DataCloneError"_utf16);
}
+TEST_CASE(crypto_key_with_an_ml_dsa_seed_that_does_not_match_its_public_key_is_a_data_clone_error)
+{
+ auto key_pair = mldsa_44_key_pair();
+ Array<u8, 32> other_seed;
+ other_seed.fill(0xff);
+ auto other_key_pair = MUST(::Crypto::PK::MLDSA::generate_key_pair(::Crypto::PK::MLDSA44, other_seed));
+ auto expanded_key = MUST(key_pair.private_key.expanded_key());
+ auto seed = seed_of(key_pair.private_key);
+ auto record = crypto_key_full_record("private"sv, "sign"sv, alg_key_algorithm("ML-DSA-44"sv), handle_triple_buffer(6, seed, other_key_pair.public_key.public_key(), expanded_key));
+ auto& realm = principal_test_realm();
+ auto result = Web::WebIDL::throw_dom_exception_if_needed(realm.vm(), realm, [&] {
+ return principal_storage_deserialize(record);
+ });
+ EXPECT(result.is_error());
+ if (result.is_error())
+ EXPECT_EQ(unwrap_wrappable<Web::WebIDL::DOMException>(result.error_value()).name(), "DataCloneError"_utf16);
+}
+
+TEST_CASE(crypto_key_with_an_ml_kem_public_key_that_fails_the_encapsulation_key_check_decodes)
+{
+ Array<u8, 800> public_key;
+ public_key.fill(0xff);
+ auto record = crypto_key_full_record("public"sv, "encapsulateBits"sv, alg_key_algorithm("ML-KEM-512"sv), handle_single_buffer(7, public_key));
+ auto value = MUST(principal_storage_deserialize(record));
+ auto& key = unwrap_wrappable<Web::Crypto::CryptoKey>(value);
+ EXPECT(key.handle().has<::Crypto::PK::MLKEMPublicKey>());
+ EXPECT(!key.handle().get<::Crypto::PK::MLKEMPublicKey>().size().has_value());
+}
+
TEST_CASE(crypto_key_handle_variants_decode_from_frozen_bytes)
{
for (auto const& golden : crypto_handle_goldens()) {
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.txt
new file mode 100644
index 00000000000..f96d98c6f95
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.txt
@@ -0,0 +1,3 @@
+a valid key: imported, encapsulated
+800 bytes of 0xff: imported, encapsulate OperationError
+799 bytes: imported, encapsulate OperationError
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.html
new file mode 100644
index 00000000000..b1a0f157217
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.html
@@ -0,0 +1,30 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const algorithm = { name: "ML-KEM-512" };
+ const { publicKey } = await crypto.subtle.generateKey(algorithm, true, ["encapsulateBits", "decapsulateBits"]);
+ const valid = new Uint8Array(await crypto.subtle.exportKey("raw-public", publicKey));
+
+ const keys = [
+ ["a valid key", valid],
+ ["800 bytes of 0xff", new Uint8Array(800).fill(0xff)],
+ ["799 bytes", valid.slice(0, 799)],
+ ];
+ for (const [name, data] of keys) {
+ let key;
+ try {
+ key = await crypto.subtle.importKey("raw-public", data, algorithm, true, ["encapsulateBits"]);
+ } catch (error) {
+ println(`${name}: import ${error.name}`);
+ continue;
+ }
+ try {
+ await crypto.subtle.encapsulateBits(algorithm, key);
+ println(`${name}: imported, encapsulated`);
+ } catch (error) {
+ println(`${name}: imported, encapsulate ${error.name}`);
+ }
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-5.bin b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-5.bin
index 964a80dccea..cb7a8185ecf 100644
Binary files a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-5.bin and b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-5.bin differ
diff --git a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-6.bin b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-6.bin
index ae7a1a78762..cc350b0df6b 100644
Binary files a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-6.bin and b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-6.bin differ
diff --git a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-7.bin b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-7.bin
index 9b2f6bb89d4..c390f726868 100644
Binary files a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-7.bin and b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-7.bin differ
diff --git a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-8.bin b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-8.bin
index 044c5f0f6f7..c981fff5463 100644
Binary files a/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-8.bin and b/Tests/LibWeb/test-inputs/structured-serialize-corpus/cryptokey-handle-8.bin differ