Truly independent web browser
LibCrypto: Remove the C++ that Web Crypto no longer uses
Shannon Booth6a717ac9b74f
diff --git a/Libraries/LibCrypto/ASN1/ASN1.h b/Libraries/LibCrypto/ASN1/ASN1.hdeleted file mode 100644index 60f3f571031..00000000000--- a/Libraries/LibCrypto/ASN1/ASN1.h+++ /dev/null@@ -1,67 +0,0 @@-/*- * Copyright (c) 2020, Ali Mohammad Pur <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/StringView.h>-#include <AK/Types.h>--namespace Crypto::ASN1 {--// ITU-T X.680, section 8, table 1-enum class Kind : u8 {- Eol = 0x00,- Boolean = 0x01,- Integer = 0x02,- BitString = 0x03,- OctetString = 0x04,- Null = 0x05,- ObjectIdentifier = 0x06,- ObjectDescriptor = 0x07,- External = 0x08,- Real = 0x09,- Enumerated = 0x0A,- EmbeddedPdv = 0x0B,- Utf8String = 0x0C,- RelativeOid = 0x0D,- Time = 0x0E,- Reserved = 0x0F,- Sequence = 0x10,- Set = 0x11,- NumericString = 0x12,- PrintableString = 0x13,- T61String = 0x14,- VideotexString = 0x15,- IA5String = 0x16,- UTCTime = 0x017,- GeneralizedTime = 0x18,- GraphicString = 0x19,- VisibleString = 0x1A,- GeneralString = 0x1B,- UniversalString = 0x1C,- CharacterString = 0x1D,- BMPString = 0x1E,- Date = 0x1F,- TimeOfDay = 0x20,- DateTime = 0x21,- Duration = 0x22,- OidIri = 0x23,- RelativeOidIri = 0x24,-};--enum class Class : u8 {- Universal = 0,- Application = 0x40,- Context = 0x80,- Private = 0xc0,-};--enum class Type : u8 {- Primitive = 0,- Constructed = 0x20,-};--}diff --git a/Libraries/LibCrypto/ASN1/Constants.h b/Libraries/LibCrypto/ASN1/Constants.hdeleted file mode 100644index c44ae8316c7..00000000000--- a/Libraries/LibCrypto/ASN1/Constants.h+++ /dev/null@@ -1,40 +0,0 @@-/*- * Copyright (c) 2020-2023, the SerenityOS developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibCrypto/ASN1/DER.h>--namespace Crypto::ASN1 {--constexpr static Array<u32, 7>- rsa_encryption_oid { 1, 2, 840, 113549, 1, 1, 1 },- secp256r1_oid { 1, 2, 840, 10045, 3, 1, 7 };--constexpr static Array<u32, 6>- ec_public_key_encryption_oid { 1, 2, 840, 10045, 2, 1 };--constexpr static Array<u32, 5>- secp384r1_oid { 1, 3, 132, 0, 34 },- secp521r1_oid { 1, 3, 132, 0, 35 };--constexpr static Array<u32, 4>- x25519_oid { 1, 3, 101, 110 },- x448_oid { 1, 3, 101, 111 },- ed25519_oid { 1, 3, 101, 112 },- ed448_oid { 1, 3, 101, 113 };--constexpr static Array<u32, 9>- ml_dsa_44_oid { 2, 16, 840, 1, 101, 3, 4, 3, 17 },- ml_dsa_65_oid { 2, 16, 840, 1, 101, 3, 4, 3, 18 },- ml_dsa_87_oid { 2, 16, 840, 1, 101, 3, 4, 3, 19 };--constexpr static Array<u32, 9>- ml_kem_512_oid { 2, 16, 840, 1, 101, 3, 4, 4, 1 },- ml_kem_768_oid { 2, 16, 840, 1, 101, 3, 4, 4, 2 },- ml_kem_1024_oid { 2, 16, 840, 1, 101, 3, 4, 4, 3 };--}diff --git a/Libraries/LibCrypto/ASN1/DER.cpp b/Libraries/LibCrypto/ASN1/DER.cppdeleted file mode 100644index 39d9c8d2b56..00000000000--- a/Libraries/LibCrypto/ASN1/DER.cpp+++ /dev/null@@ -1,172 +0,0 @@-/*- * Copyright (c) 2021, the SerenityOS developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/IntegralMath.h>-#include <AK/Math.h>-#include <AK/Try.h>-#include <LibCrypto/ASN1/DER.h>--namespace Crypto::ASN1 {--ErrorOr<void> Encoder::write_tag(Class class_, Type type, Kind kind)-{- auto class_byte = to_underlying(class_);- auto type_byte = to_underlying(type);- auto kind_byte = to_underlying(kind);-- auto byte = class_byte | type_byte | kind_byte;- if (kind_byte > 0x1f) {- auto high = kind_byte >> 7;- byte = class_byte | type_byte | 0x1f;- TRY(write_byte(byte));- byte = (kind_byte & 0x7f) | high;- }-- return write_byte(byte);-}--ErrorOr<void> Encoder::write_byte(u8 byte)-{- return write_bytes({ &byte, 1 });-}--ErrorOr<void> Encoder::write_length(size_t value)-{- if (value < 0x80)- return write_byte(value);-- double minimum_bits = AK::log2(value);- size_t size_in_bits = AK::floor(minimum_bits) + 1;- size_t size = ceil_div(size_in_bits, 8uz);- TRY(write_byte(0x80 | size));-- for (size_t i = 0; i < size; i++) {- auto shift = (size - i - 1) * 8;- auto byte = (value >> shift) & 0xff;- TRY(write_byte(byte));- }-- return {};-}--ErrorOr<void> Encoder::write_bytes(ReadonlyBytes bytes)-{- auto output = TRY(m_buffer_stack.last().get_bytes_for_writing(bytes.size()));- bytes.copy_to(output);- return {};-}--ErrorOr<void> Encoder::write_integer(u64 value, Optional<Class> class_override, Optional<Kind> kind_override)-{- auto class_ = class_override.value_or(Class::Universal);- auto type = Type::Primitive;- auto kind = kind_override.value_or(Kind::Integer);- TRY(write_tag(class_, type, kind));-- // NB: The contents are the fewest big-endian bytes that hold the value, at least one, after a zero byte if the top- // bit is set, which keeps the integer positive.- u8 bytes[sizeof(u64) + 1] {};- for (size_t i = 0; i < sizeof(u64); ++i)- bytes[sizeof(bytes) - 1 - i] = static_cast<u8>(value >> (8 * i));- size_t start = 1;- while (start < sizeof(bytes) - 1 && bytes[start] == 0)- ++start;- if ((bytes[start] & 0x80) != 0)- --start;-- ReadonlyBytes contents { bytes + start, sizeof(bytes) - start };- TRY(write_length(contents.size()));- return write_bytes(contents);-}--ErrorOr<void> Encoder::write_octet_string(ReadonlyBytes bytes, Optional<Class> class_override, Optional<Kind> kind_override)-{- auto class_ = class_override.value_or(Class::Universal);- auto type = Type::Primitive;- auto kind = kind_override.value_or(Kind::OctetString);-- TRY(write_tag(class_, type, kind));- TRY(write_length(bytes.size()));- return write_bytes(bytes);-}--ErrorOr<void> Encoder::write_null(Optional<Class> class_override, Optional<Kind> kind_override)-{- auto class_ = class_override.value_or(Class::Universal);- auto type = Type::Primitive;- auto kind = kind_override.value_or(Kind::Null);-- TRY(write_tag(class_, type, kind));- TRY(write_length(0));- return {};-}--ErrorOr<void> Encoder::write_object_identifier(Span<u32 const> segments, Optional<Class> class_override, Optional<Kind> kind_override)-{- auto class_ = class_override.value_or(Class::Universal);- auto type = Type::Primitive;- auto kind = kind_override.value_or(Kind::ObjectIdentifier);-- if (segments.size() < 2)- return Error::from_string_literal("ASN1::Encoder: Object identifier must have at least two segments");-- TRY(write_tag(class_, type, kind));- size_t length = 1;- for (size_t i = 2; i < segments.size(); i++) {- auto segment = segments[i];- if (segment < 0x80)- length += 1;- else if (segment < 0x4000)- length += 2;- else if (segment < 0x200000)- length += 3;- else- length += 4;- }-- TRY(write_length(length));-- auto first_byte = (segments[0] * 40) + segments[1];- TRY(write_byte(first_byte));-- for (size_t i = 2; i < segments.size(); i++) {- auto segment = segments[i];- if (segment < 0x80) {- TRY(write_byte(segment));- } else if (segment < 0x4000) {- TRY(write_byte((segment >> 7) | 0x80));- TRY(write_byte(segment & 0x7f));- } else if (segment < 0x200000) {- TRY(write_byte((segment >> 14) | 0x80));- TRY(write_byte(((segment >> 7) & 0x7f) | 0x80));- TRY(write_byte(segment & 0x7f));- } else {- TRY(write_byte((segment >> 21) | 0x80));- TRY(write_byte(((segment >> 14) & 0x7f) | 0x80));- TRY(write_byte(((segment >> 7) & 0x7f) | 0x80));- TRY(write_byte(segment & 0x7f));- }- }-- return {};-}--ErrorOr<void> Encoder::write_bit_string(BitStringView view, Optional<Class> class_override, Optional<Kind> kind_override)-{- auto class_ = class_override.value_or(Class::Universal);- auto type = Type::Primitive;- auto kind = kind_override.value_or(Kind::BitString);-- auto unused_bits = view.unused_bits();- auto total_size_in_bits = view.byte_length() * 8 - unused_bits;-- TRY(write_tag(class_, type, kind));- TRY(write_length(ceil_div(total_size_in_bits, 8uz) + 1));- TRY(write_byte(unused_bits));- return write_bytes(view.underlying_bytes());-}--}diff --git a/Libraries/LibCrypto/ASN1/DER.h b/Libraries/LibCrypto/ASN1/DER.hdeleted file mode 100644index 9b797ad93af..00000000000--- a/Libraries/LibCrypto/ASN1/DER.h+++ /dev/null@@ -1,110 +0,0 @@-/*- * Copyright (c) 2020, Ali Mohammad Pur <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Array.h>-#include <AK/ByteBuffer.h>-#include <AK/Types.h>-#include <AK/Vector.h>-#include <LibCrypto/ASN1/ASN1.h>--namespace Crypto::ASN1 {--using ObjectIdentifier = Vector<u32, 12>;--class BitStringView {-public:- BitStringView(ReadonlyBytes data, size_t unused_bits)- : m_data(data)- , m_unused_bits(unused_bits)- {- }-- size_t unused_bits() const { return m_unused_bits; }- size_t byte_length() const { return m_data.size(); }-- ReadonlyBytes underlying_bytes() const { return m_data; }--private:- ReadonlyBytes m_data;- size_t m_unused_bits;-};--class Encoder {-public:- Encoder()- {- m_buffer_stack.empend();- }-- ReadonlyBytes active_bytes() const LIFETIME_BOUND { return m_buffer_stack.last().bytes(); }- ByteBuffer finish()- {- VERIFY(m_buffer_stack.size() == 1);- return m_buffer_stack.take_last();- }-- template<typename ValueType>- ErrorOr<void> write(ValueType const& value, Optional<Class> class_override = {}, Optional<Kind> kind_override = {})- {- if constexpr (IsIntegral<ValueType> && IsUnsigned<ValueType> && !IsSame<ValueType, bool>) {- return write_integer(value, class_override, kind_override);- } else if constexpr (IsOneOf<ValueType, ReadonlyBytes, ByteBuffer>) {- return write_octet_string(value, class_override, kind_override);- } else if constexpr (IsSame<ValueType, nullptr_t>) {- return write_null(class_override, kind_override);- } else if constexpr (IsOneOf<ValueType, ObjectIdentifier, Span<u32 const>, Span<u32>>) {- return write_object_identifier(value, class_override, kind_override);- } else if constexpr (IsSame<ValueType, BitStringView>) {- return write_bit_string(value, class_override, kind_override);- } else {- dbgln("Unsupported type: {}", __PRETTY_FUNCTION__);- return Error::from_string_literal("ASN1::Encoder: Trying to encode a value of an unsupported type");- }- }-- template<typename Fn>- ErrorOr<void> write_constructed(Class class_, Kind kind, Fn&& fn)- {- return write_constructed(bit_cast<u8>(class_), bit_cast<u8>(kind), forward<Fn>(fn));- }-- template<typename Fn>- ErrorOr<void> write_constructed(u8 class_, u8 kind, Fn&& fn)- {- m_buffer_stack.empend();- using ResultType = decltype(fn());- if constexpr (IsSpecializationOf<ResultType, ErrorOr>) {- TRY(fn());- } else {- fn();- }- auto buffer = m_buffer_stack.take_last();-- TRY(write_tag(bit_cast<Class>(class_), Type::Constructed, bit_cast<Kind>(kind)));- TRY(write_length(buffer.size()));- TRY(write_bytes(buffer.bytes()));-- return {};- }--private:- ErrorOr<void> write_tag(Class, Type, Kind);- ErrorOr<void> write_length(size_t);- ErrorOr<void> write_bytes(ReadonlyBytes);- ErrorOr<void> write_byte(u8);-- ErrorOr<void> write_integer(u64, Optional<Class>, Optional<Kind>);- ErrorOr<void> write_octet_string(ReadonlyBytes, Optional<Class>, Optional<Kind>);- ErrorOr<void> write_null(Optional<Class>, Optional<Kind>);- ErrorOr<void> write_object_identifier(Span<u32 const>, Optional<Class>, Optional<Kind>);- ErrorOr<void> write_bit_string(BitStringView, Optional<Class>, Optional<Kind>);-- Vector<ByteBuffer> m_buffer_stack;-};--}diff --git a/Libraries/LibCrypto/Authentication/KMAC.cpp b/Libraries/LibCrypto/Authentication/KMAC.cppdeleted file mode 100644index 4296649d8b4..00000000000--- a/Libraries/LibCrypto/Authentication/KMAC.cpp+++ /dev/null@@ -1,84 +0,0 @@-/*- * Copyright (c) 2026, mikiubo <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Vector.h>-#include <LibCrypto/Authentication/KMAC.h>-#include <LibCrypto/OpenSSL.h>--#include <openssl/core_names.h>-#include <openssl/evp.h>--namespace Crypto::Authentication {--u32 KMAC::default_key_length(KMACKind kind)-{- switch (kind) {- case KMACKind::KMAC128:- return 128;- case KMACKind::KMAC256:- return 256;- }- VERIFY_NOT_REACHED();-}--KMAC::KMAC(KMACKind kind)- : m_kind(kind)-{-}--ErrorOr<void> KMAC::validate_parameters(u32 output_length_bits, Optional<ReadonlyBytes> customization)-{- // OpenSSL's KMAC implementation rejects longer outputs and customization strings.- static constexpr size_t maximum_output_length = 0xFFFFFF / 8;- static constexpr size_t maximum_customization_length = 512;-- if (output_length_bits == 0)- return Error::from_string_literal("KMAC output length must be greater than zero");-- if ((output_length_bits % 8) != 0)- return Error::from_string_literal("KMAC output length must be a multiple of 8");-- if (output_length_bits / 8 > maximum_output_length)- return Error::from_string_literal("KMAC output length is too large");-- if (customization.has_value() && customization->size() > maximum_customization_length)- return Error::from_string_literal("KMAC customization is too long");-- return {};-}--// https://wicg.github.io/webcrypto-modern-algos/#kmac-operations-sign-ErrorOr<ByteBuffer> KMAC::sign(ReadonlyBytes key, ReadonlyBytes message, u32 output_length_bits, Optional<ReadonlyBytes> customization) const-{- TRY(validate_parameters(output_length_bits, customization));-- auto const* mac_name = (m_kind == KMACKind::KMAC128) ? OSSL_MAC_NAME_KMAC128 : OSSL_MAC_NAME_KMAC256;-- auto mac = TRY(OpenSSL_MAC::wrap(EVP_MAC_fetch(nullptr, mac_name, nullptr)));- auto ctx = TRY(OpenSSL_MAC_CTX::wrap(EVP_MAC_CTX_new(mac.ptr())));-- size_t output_size = output_length_bits / 8;-- Vector<OSSL_PARAM> params;- params.append(OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, &output_size));- if (customization.has_value())- params.append(OSSL_PARAM_octet_string(OSSL_MAC_PARAM_CUSTOM, const_cast<u8*>(customization.value().data()), customization.value().size()));- params.append(OSSL_PARAM_END);-- OPENSSL_TRY(EVP_MAC_init(ctx.ptr(), key.data(), key.size(), params.data()));- OPENSSL_TRY(EVP_MAC_update(ctx.ptr(), message.data(), message.size()));-- auto buf = TRY(ByteBuffer::create_uninitialized(output_size));- size_t written = 0;- OPENSSL_TRY(EVP_MAC_final(ctx.ptr(), buf.data(), &written, output_size));-- if (written != output_size)- return Error::from_string_literal("EVP_MAC_final returned an unexpected output length");-- return buf;-}--}diff --git a/Libraries/LibCrypto/Authentication/KMAC.h b/Libraries/LibCrypto/Authentication/KMAC.hdeleted file mode 100644index ce29fe0e18b..00000000000--- a/Libraries/LibCrypto/Authentication/KMAC.h+++ /dev/null@@ -1,42 +0,0 @@-/*- * Copyright (c) 2026, mikiubo <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Error.h>-#include <AK/Noncopyable.h>-#include <LibCrypto/OpenSSLForward.h>--namespace Crypto::Authentication {--enum class KMACKind {- KMAC128,- KMAC256,-};--class KMAC {- AK_MAKE_NONCOPYABLE(KMAC);--public:- explicit KMAC(KMACKind kind);-- ~KMAC() = default;-- static u32 default_key_length(KMACKind);- static ErrorOr<void> validate_parameters(u32 output_length_bits, Optional<ReadonlyBytes> customization);-- ErrorOr<ByteBuffer> sign(- ReadonlyBytes key,- ReadonlyBytes message,- u32 output_length_bits,- Optional<ReadonlyBytes> customization) const;--private:- KMACKind m_kind;-};--}diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txtindex 41f72565376..56198018f37 100644--- a/Libraries/LibCrypto/CMakeLists.txt+++ b/Libraries/LibCrypto/CMakeLists.txt@@ -1,26 +1,11 @@add_cxx_compile_options(-Wvla)set(SOURCES- KeyHandle.cppOpenSSL.cpp- RustBindings.cpp- ASN1/DER.cppAuthentication/HMAC.cpp- Authentication/KMAC.cpp- Cipher/AES.cpp- Cipher/ChaCha.cppCurves/EdwardsCurve.cpp- Hash/Argon2.cppHash/Hash.cpp- Hash/SHAKE.cpp- Hash/HKDF.cpp- Hash/PBKDF2.cppPK/EC.cpp- PK/KeyInfo.cpp- PK/MLDSA.cpp- PK/MLKEM.cpp- PK/ModuleLatticePrivateKey.cpp- PK/PK.cppPK/RSA.cpp)diff --git a/Libraries/LibCrypto/Cipher/AES.cpp b/Libraries/LibCrypto/Cipher/AES.cppdeleted file mode 100644index bdb8545c3a8..00000000000--- a/Libraries/LibCrypto/Cipher/AES.cpp+++ /dev/null@@ -1,288 +0,0 @@-/*- * Copyright (c) 2020, Ali Mohammad Pur <[email protected]>- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Cipher/AES.h>-#include <LibCrypto/OpenSSL.h>--#include <openssl/evp.h>--namespace Crypto::Cipher {--#define GET_CIPHER(key, mode) \- [&key] { \- switch (key.size()) { \- case 16: \- return EVP_aes_128_##mode(); \- case 24: \- return EVP_aes_192_##mode(); \- case 32: \- return EVP_aes_256_##mode(); \- default: \- VERIFY_NOT_REACHED(); \- } \- }()--size_t AESCipher::block_size() const-{- auto size = EVP_CIPHER_get_block_size(m_cipher);- VERIFY(size != 0);- return size;-}--AESCBCCipher::AESCBCCipher(ReadonlyBytes key, bool no_padding)- : AESCipher(GET_CIPHER(key, cbc), key)- , m_no_padding(no_padding)-{-}--ErrorOr<ByteBuffer> AESCBCCipher::encrypt(ReadonlyBytes plaintext, ReadonlyBytes iv) const-{- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_EncryptInit(ctx.ptr(), m_cipher, m_key.data(), iv.data()));- OPENSSL_TRY(EVP_CIPHER_CTX_set_padding(ctx.ptr(), m_no_padding ? 0 : 1));-- auto out = TRY(ByteBuffer::create_uninitialized(plaintext.size() + block_size()));- int out_size = 0;- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), out.data(), &out_size, plaintext.data(), plaintext.size()));-- int final_size = 0;- OPENSSL_TRY(EVP_EncryptFinal(ctx.ptr(), out.data() + out_size, &final_size));-- return out.slice(0, out_size + final_size);-}--ErrorOr<ByteBuffer> AESCBCCipher::decrypt(ReadonlyBytes ciphertext, ReadonlyBytes iv) const-{- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_DecryptInit(ctx.ptr(), m_cipher, m_key.data(), iv.data()));- OPENSSL_TRY(EVP_CIPHER_CTX_set_padding(ctx.ptr(), m_no_padding ? 0 : 1));-- auto out = TRY(ByteBuffer::create_uninitialized(ciphertext.size() + block_size()));- int out_size = 0;- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), out.data(), &out_size, ciphertext.data(), ciphertext.size()));-- int final_size = 0;- OPENSSL_TRY(EVP_DecryptFinal(ctx.ptr(), out.data() + out_size, &final_size));-- return out.slice(0, out_size + final_size);-}--AESCTRCipher::AESCTRCipher(ReadonlyBytes key)- : AESCipher(GET_CIPHER(key, ctr), key)-{-}--ErrorOr<ByteBuffer> AESCTRCipher::encrypt(ReadonlyBytes plaintext, ReadonlyBytes iv) const-{- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_EncryptInit(ctx.ptr(), m_cipher, m_key.data(), iv.data()));-- auto out = TRY(ByteBuffer::create_uninitialized(plaintext.size() + block_size()));- int out_size = 0;- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), out.data(), &out_size, plaintext.data(), plaintext.size()));-- int final_size = 0;- OPENSSL_TRY(EVP_EncryptFinal(ctx.ptr(), out.data() + out_size, &final_size));-- return out.slice(0, out_size + final_size);-}--ErrorOr<ByteBuffer> AESCTRCipher::decrypt(ReadonlyBytes ciphertext, ReadonlyBytes iv) const-{- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_DecryptInit(ctx.ptr(), m_cipher, m_key.data(), iv.data()));-- auto out = TRY(ByteBuffer::create_uninitialized(ciphertext.size() + block_size()));- int out_size = 0;- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), out.data(), &out_size, ciphertext.data(), ciphertext.size()));-- int final_size = 0;- OPENSSL_TRY(EVP_DecryptFinal(ctx.ptr(), out.data() + out_size, &final_size));-- return out.slice(0, out_size + final_size);-}--AESGCMCipher::AESGCMCipher(ReadonlyBytes key)- : AESCipher(GET_CIPHER(key, gcm), key)-{-}--ErrorOr<AESGCMCipher::EncryptedData> AESGCMCipher::encrypt(ReadonlyBytes plaintext, ReadonlyBytes iv, ReadonlyBytes aad, size_t taglen) const-{- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_EncryptInit(ctx.ptr(), m_cipher, nullptr, nullptr));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_GCM_SET_IVLEN, iv.size(), nullptr));-- OPENSSL_TRY(EVP_EncryptInit(ctx.ptr(), nullptr, m_key.data(), iv.data()));-- // To specify additional authenticated data (AAD), a call to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made- // with the output parameter out set to NULL.- if (!aad.is_empty()) {- int aad_size = 0;- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), nullptr, &aad_size, aad.data(), aad.size()));- }-- auto out = TRY(ByteBuffer::create_uninitialized(plaintext.size() + block_size()));- int out_size = 0;- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), out.data(), &out_size, plaintext.data(), plaintext.size()));-- int final_size = 0;- OPENSSL_TRY(EVP_EncryptFinal(ctx.ptr(), out.data() + out_size, &final_size));-- auto tag = TRY(ByteBuffer::create_uninitialized(taglen));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_GCM_GET_TAG, taglen, tag.data()));-- return EncryptedData {- .ciphertext = TRY(out.slice(0, out_size + final_size)),- .tag = tag- };-}--ErrorOr<ByteBuffer> AESGCMCipher::decrypt(ReadonlyBytes ciphertext, ReadonlyBytes iv, ReadonlyBytes aad, ReadonlyBytes tag) const-{- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_DecryptInit(ctx.ptr(), m_cipher, nullptr, nullptr));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_GCM_SET_IVLEN, iv.size(), nullptr));-- OPENSSL_TRY(EVP_DecryptInit(ctx.ptr(), nullptr, m_key.data(), iv.data()));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_GCM_SET_TAG, tag.size(), const_cast<u8*>(tag.data())));-- // To specify additional authenticated data (AAD), a call to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made- // with the output parameter out set to NULL.- if (!aad.is_empty()) {- int aad_size = 0;- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), nullptr, &aad_size, aad.data(), aad.size()));- }-- auto out = TRY(ByteBuffer::create_uninitialized(ciphertext.size() + block_size()));- int out_size = 0;- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), out.data(), &out_size, ciphertext.data(), ciphertext.size()));-- int final_size = 0;- OPENSSL_TRY(EVP_DecryptFinal(ctx.ptr(), out.data() + out_size, &final_size));-- return out.slice(0, out_size + final_size);-}--AESOCBCipher::AESOCBCipher(ReadonlyBytes key)- : AESCipher(GET_CIPHER(key, ocb), key)-{-}--ErrorOr<ByteBuffer> AESOCBCipher::encrypt(ReadonlyBytes plaintext, ReadonlyBytes iv, ReadonlyBytes aad, size_t tag_length) const-{- auto tag_length_bytes = tag_length / 8;- VERIFY(tag_length_bytes >= 1 && tag_length_bytes <= 16);- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());- OPENSSL_TRY(EVP_EncryptInit_ex(ctx.ptr(), m_cipher, nullptr, nullptr, nullptr));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_SET_IVLEN, iv.size(), nullptr));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_SET_TAG, tag_length_bytes, nullptr));- OPENSSL_TRY(EVP_EncryptInit_ex(ctx.ptr(), nullptr, nullptr, m_key.data(), iv.data()));-- if (!aad.is_empty()) {- int aad_len = 0;- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), nullptr, &aad_len, aad.data(), aad.size()));- }-- auto ciphertext = TRY(ByteBuffer::create_uninitialized(plaintext.size()));- int out_len = 0;- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), ciphertext.data(), &out_len, plaintext.data(), plaintext.size()));-- int final_len = 0;- OPENSSL_TRY(EVP_EncryptFinal_ex(ctx.ptr(), ciphertext.data() + out_len, &final_len));-- auto tag = TRY(ByteBuffer::create_uninitialized(tag_length_bytes));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_GET_TAG, tag_length_bytes, tag.data()));-- auto result = TRY(ByteBuffer::create_uninitialized(ciphertext.size() + tag.size()));- result.overwrite(0, ciphertext.data(), ciphertext.size());- result.overwrite(ciphertext.size(), tag.data(), tag.size());-- return result;-}--ErrorOr<ByteBuffer> AESOCBCipher::decrypt(ReadonlyBytes ciphertext_with_tag, ReadonlyBytes iv, ReadonlyBytes aad, size_t tag_length) const-{- auto tag_length_bytes = tag_length / 8;- VERIFY(tag_length_bytes >= 1 && tag_length_bytes <= 16);- auto split_index = ciphertext_with_tag.size() - tag_length_bytes;- auto ciphertext = ciphertext_with_tag.slice(0, split_index);- auto tag = ciphertext_with_tag.slice(split_index);-- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());- OPENSSL_TRY(EVP_DecryptInit_ex(ctx.ptr(), m_cipher, nullptr, nullptr, nullptr));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_SET_IVLEN, iv.size(), nullptr));-- // NOTE: In OCB mode, calling this with tag set to NULL sets the tag length.- // The tag length can only be set before specifying an IV.- // If this is not called prior to setting the IV, then a default tag length is used.- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_SET_TAG, tag_length_bytes, nullptr));- OPENSSL_TRY(EVP_DecryptInit_ex(ctx.ptr(), nullptr, nullptr, m_key.data(), iv.data()));-- if (!aad.is_empty()) {- int aad_len = 0;- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), nullptr, &aad_len, aad.data(), aad.size()));- }-- auto plaintext = TRY(ByteBuffer::create_uninitialized(ciphertext.size()));-- int out_len = 0;- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), plaintext.data(), &out_len, ciphertext.data(), ciphertext.size()));-- auto* mutable_tag = const_cast<u8*>(tag.data());- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_SET_TAG, tag_length_bytes, mutable_tag));-- int final_len = 0;- OPENSSL_TRY(EVP_DecryptFinal_ex(ctx.ptr(), plaintext.data() + out_len, &final_len));-- return plaintext;-}--AESKWCipher::AESKWCipher(ReadonlyBytes key)- : AESCipher(GET_CIPHER(key, wrap), key)-{-}--ErrorOr<ByteBuffer> AESKWCipher::wrap(ReadonlyBytes plaintext) const-{- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_EncryptInit(ctx.ptr(), m_cipher, m_key.data(), nullptr));-- auto out = TRY(ByteBuffer::create_uninitialized(plaintext.size() + block_size()));- int out_size = 0;- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), out.data(), &out_size, plaintext.data(), plaintext.size()));-- int final_size = 0;- OPENSSL_TRY(EVP_EncryptFinal(ctx.ptr(), out.data() + out_size, &final_size));-- return out.slice(0, out_size + final_size);-}--ErrorOr<ByteBuffer> AESKWCipher::unwrap(ReadonlyBytes ciphertext) const-{- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_DecryptInit(ctx.ptr(), m_cipher, m_key.data(), nullptr));-- auto out = TRY(ByteBuffer::create_uninitialized(ciphertext.size() + block_size()));- int out_size = 0;- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), out.data(), &out_size, ciphertext.data(), ciphertext.size()));-- int final_size = 0;- OPENSSL_TRY(EVP_DecryptFinal(ctx.ptr(), out.data() + out_size, &final_size));-- return out.slice(0, out_size + final_size);-}--}diff --git a/Libraries/LibCrypto/Cipher/AES.h b/Libraries/LibCrypto/Cipher/AES.hdeleted file mode 100644index 77cba1659cb..00000000000--- a/Libraries/LibCrypto/Cipher/AES.h+++ /dev/null@@ -1,79 +0,0 @@-/*- * Copyright (c) 2020, Ali Mohammad Pur <[email protected]>- * Copyright (c) 2022, the SerenityOS developers.- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <LibCrypto/OpenSSLForward.h>--namespace Crypto::Cipher {--class AESCipher {-public:- size_t block_size() const;--protected:- explicit AESCipher(EVP_CIPHER const* cipher, ReadonlyBytes key)- : m_cipher(cipher)- , m_key(key)- {- }-- EVP_CIPHER const* m_cipher;- ReadonlyBytes m_key;-};--class AESCBCCipher final : public AESCipher {-public:- explicit AESCBCCipher(ReadonlyBytes key, bool no_padding = false);-- ErrorOr<ByteBuffer> encrypt(ReadonlyBytes plaintext, ReadonlyBytes iv) const;- ErrorOr<ByteBuffer> decrypt(ReadonlyBytes ciphertext, ReadonlyBytes iv) const;--private:- bool m_no_padding { false };-};--class AESCTRCipher final : public AESCipher {-public:- explicit AESCTRCipher(ReadonlyBytes key);-- ErrorOr<ByteBuffer> encrypt(ReadonlyBytes plaintext, ReadonlyBytes iv) const;- ErrorOr<ByteBuffer> decrypt(ReadonlyBytes ciphertext, ReadonlyBytes iv) const;-};--class AESGCMCipher final : public AESCipher {-public:- explicit AESGCMCipher(ReadonlyBytes key);-- struct EncryptedData {- ByteBuffer ciphertext;- ByteBuffer tag;- };-- ErrorOr<EncryptedData> encrypt(ReadonlyBytes plaintext, ReadonlyBytes iv, ReadonlyBytes aad, size_t taglen) const;- ErrorOr<ByteBuffer> decrypt(ReadonlyBytes ciphertext, ReadonlyBytes iv, ReadonlyBytes aad, ReadonlyBytes tag) const;-};--class AESOCBCipher final : public AESCipher {-public:- explicit AESOCBCipher(ReadonlyBytes key);-- ErrorOr<ByteBuffer> encrypt(ReadonlyBytes plaintext, ReadonlyBytes iv, ReadonlyBytes aad, size_t tag_length) const;- ErrorOr<ByteBuffer> decrypt(ReadonlyBytes ciphertext, ReadonlyBytes iv, ReadonlyBytes aad, size_t tag_length) const;-};--class AESKWCipher final : public AESCipher {-public:- explicit AESKWCipher(ReadonlyBytes key);-- ErrorOr<ByteBuffer> wrap(ReadonlyBytes) const;- ErrorOr<ByteBuffer> unwrap(ReadonlyBytes) const;-};--}diff --git a/Libraries/LibCrypto/Cipher/ChaCha.cpp b/Libraries/LibCrypto/Cipher/ChaCha.cppdeleted file mode 100644index 60a775b08ea..00000000000--- a/Libraries/LibCrypto/Cipher/ChaCha.cpp+++ /dev/null@@ -1,99 +0,0 @@-/*- * Copyright (c) 2026, mikiubo <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Cipher/ChaCha.h>-#include <LibCrypto/OpenSSL.h>--#include <openssl/evp.h>--namespace Crypto::Cipher {--static EVP_CIPHER const* chacha20_poly1305_cipher()-{- return EVP_chacha20_poly1305();-}--ErrorOr<ByteBuffer> ChaCha20Poly1305::encrypt(ReadonlyBytes key, ReadonlyBytes nonce, ReadonlyBytes plaintext, ReadonlyBytes aad)-{- if (key.size() != key_size)- return Error::from_string_literal("ChaCha20-Poly1305 key must be 32 bytes");-- if (nonce.size() != nonce_size)- return Error::from_string_literal("ChaCha20-Poly1305 nonce must be 12 bytes");-- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_EncryptInit_ex(ctx.ptr(), chacha20_poly1305_cipher(), nullptr, nullptr, nullptr));-- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_SET_IVLEN, nonce.size(), nullptr));-- OPENSSL_TRY(EVP_EncryptInit_ex(ctx.ptr(), nullptr, nullptr, key.data(), nonce.data()));-- if (!aad.is_empty()) {- int aad_len = 0;- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), nullptr, &aad_len, aad.data(), aad.size()));- }-- auto ciphertext = TRY(ByteBuffer::create_uninitialized(plaintext.size()));- int out_len = 0;-- OPENSSL_TRY(EVP_EncryptUpdate(ctx.ptr(), ciphertext.data(), &out_len, plaintext.data(), plaintext.size()));-- int final_len = 0;- OPENSSL_TRY(EVP_EncryptFinal_ex(ctx.ptr(), ciphertext.data() + out_len, &final_len));-- auto tag = TRY(ByteBuffer::create_uninitialized(tag_size));- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_GET_TAG, tag_size, tag.data()));-- auto result = TRY(ByteBuffer::create_uninitialized(ciphertext.size() + tag_size));- result.overwrite(0, ciphertext.data(), ciphertext.size());- result.overwrite(ciphertext.size(), tag.data(), tag.size());-- return result;-}--ErrorOr<ByteBuffer> ChaCha20Poly1305::decrypt(ReadonlyBytes key, ReadonlyBytes nonce, ReadonlyBytes ciphertext_and_tag, ReadonlyBytes aad)-{- if (key.size() != key_size)- return Error::from_string_literal("ChaCha20-Poly1305 key must be 32 bytes");-- if (nonce.size() != nonce_size)- return Error::from_string_literal("ChaCha20-Poly1305 nonce must be 12 bytes");-- if (ciphertext_and_tag.size() < tag_size)- return Error::from_string_literal("Ciphertext too short");-- auto ciphertext_size = ciphertext_and_tag.size() - tag_size;- auto ciphertext = ciphertext_and_tag.slice(0, ciphertext_size);- auto tag = ciphertext_and_tag.slice(ciphertext_size, tag_size);-- auto ctx = TRY(OpenSSL_CIPHER_CTX::create());-- OPENSSL_TRY(EVP_DecryptInit_ex(ctx.ptr(), chacha20_poly1305_cipher(), nullptr, nullptr, nullptr));-- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_SET_IVLEN, nonce.size(), nullptr));-- OPENSSL_TRY(EVP_DecryptInit_ex(ctx.ptr(), nullptr, nullptr, key.data(), nonce.data()));-- OPENSSL_TRY(EVP_CIPHER_CTX_ctrl(ctx.ptr(), EVP_CTRL_AEAD_SET_TAG, tag.size(), const_cast<u8*>(tag.data())));-- if (!aad.is_empty()) {- int aad_len = 0;- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), nullptr, &aad_len, aad.data(), aad.size()));- }-- auto plaintext = TRY(ByteBuffer::create_uninitialized(ciphertext.size()));- int out_len = 0;-- OPENSSL_TRY(EVP_DecryptUpdate(ctx.ptr(), plaintext.data(), &out_len, ciphertext.data(), ciphertext.size()));-- int final_len = 0;- OPENSSL_TRY(EVP_DecryptFinal_ex(ctx.ptr(), plaintext.data() + out_len, &final_len));-- return plaintext.slice(0, out_len + final_len);-}--}diff --git a/Libraries/LibCrypto/Cipher/ChaCha.h b/Libraries/LibCrypto/Cipher/ChaCha.hdeleted file mode 100644index eb7640dfa0e..00000000000--- a/Libraries/LibCrypto/Cipher/ChaCha.h+++ /dev/null@@ -1,38 +0,0 @@-/*- * Copyright (c) 2026, mikiubo <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Error.h>--namespace Crypto::Cipher {--class ChaCha20Poly1305 {-public:- // 256 bits- static constexpr size_t key_size = 32;-- // 96 bits- static constexpr size_t nonce_size = 12;-- // 128 bits- static constexpr size_t tag_size = 16;-- static ErrorOr<ByteBuffer> encrypt(- ReadonlyBytes key,- ReadonlyBytes nonce,- ReadonlyBytes plaintext,- ReadonlyBytes aad);-- static ErrorOr<ByteBuffer> decrypt(- ReadonlyBytes key,- ReadonlyBytes nonce,- ReadonlyBytes ciphertext_and_tag,- ReadonlyBytes aad);-};--}diff --git a/Libraries/LibCrypto/Hash/Argon2.cpp b/Libraries/LibCrypto/Hash/Argon2.cppdeleted file mode 100644index ebae41d3a11..00000000000--- a/Libraries/LibCrypto/Hash/Argon2.cpp+++ /dev/null@@ -1,105 +0,0 @@-/*- * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Hash/Argon2.h>--#include <AK/ByteBuffer.h>-#include <LibCrypto/OpenSSL.h>--#include <openssl/core_names.h>-#include <openssl/kdf.h>-#include <openssl/params.h>-#include <openssl/thread.h>--namespace Crypto::Hash {--static char const* argon2_type_to_openssl_name(Argon2Type type)-{- switch (type) {- case Argon2Type::Argon2d:- return "ARGON2d";- case Argon2Type::Argon2i:- return "ARGON2i";- case Argon2Type::Argon2id:- return "ARGON2id";- default:- VERIFY_NOT_REACHED();- }-}--Argon2::Argon2(Argon2Type type)- : m_kdf(EVP_KDF_fetch(nullptr, argon2_type_to_openssl_name(type), nullptr))-{-}--Argon2::~Argon2()-{- EVP_KDF_free(m_kdf);-}--ErrorOr<void> Argon2::validate_parameters(ReadonlyBytes nonce)-{- // OpenSSL's Argon2 implementation rejects shorter salts.- static constexpr size_t minimum_nonce_length = 8;-- if (nonce.size() < minimum_nonce_length)- return Error::from_string_literal("Argon2 nonce must be at least 8 bytes");-- return {};-}--ErrorOr<ByteBuffer> Argon2::derive_key(- ReadonlyBytes message,- ReadonlyBytes nonce,- u32 parallelism,- u32 memory,- u32 passes,- u32 version,- Optional<ReadonlyBytes> secret_value,- Optional<ReadonlyBytes> associated_data,- u32 tag_length) const-{- TRY(validate_parameters(nonce));-- auto ctx = TRY(OpenSSL_KDF_CTX::wrap(EVP_KDF_CTX_new(m_kdf)));-- auto threads = min(OSSL_get_max_threads(nullptr), parallelism);-- OSSL_PARAM params[] = {- OSSL_PARAM_uint32(OSSL_KDF_PARAM_ARGON2_LANES, ¶llelism),- OSSL_PARAM_uint32(OSSL_KDF_PARAM_ARGON2_MEMCOST, &memory),- OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, const_cast<u8*>(nonce.data()), nonce.size()),- OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, const_cast<u8*>(message.data()), message.size()),- OSSL_PARAM_uint32(OSSL_KDF_PARAM_ARGON2_VERSION, &version),- OSSL_PARAM_uint32(OSSL_KDF_PARAM_ITER, &passes),- OSSL_PARAM_uint32(OSSL_KDF_PARAM_SIZE, &tag_length),- OSSL_PARAM_END,- OSSL_PARAM_END,- OSSL_PARAM_END,- OSSL_PARAM_END,- };-- auto insertion_point = 7;-- if (threads != 0) {- params[insertion_point++] = OSSL_PARAM_uint32(OSSL_KDF_PARAM_THREADS, &threads);- }-- if (secret_value.has_value()) {- params[insertion_point++] = OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SECRET, const_cast<u8*>(secret_value->data()), secret_value->size());- }-- if (associated_data.has_value()) {- params[insertion_point++] = OSSL_PARAM_octet_string(OSSL_KDF_PARAM_ARGON2_AD, const_cast<u8*>(associated_data->data()), associated_data->size());- }-- auto buf = TRY(ByteBuffer::create_uninitialized(tag_length));- OPENSSL_TRY(EVP_KDF_derive(ctx.ptr(), buf.data(), tag_length, params));-- return buf;-}--}diff --git a/Libraries/LibCrypto/Hash/Argon2.h b/Libraries/LibCrypto/Hash/Argon2.hdeleted file mode 100644index 2cea4e9b408..00000000000--- a/Libraries/LibCrypto/Hash/Argon2.h+++ /dev/null@@ -1,45 +0,0 @@-/*- * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Error.h>-#include <LibCrypto/OpenSSLForward.h>--namespace Crypto::Hash {--enum class Argon2Type {- Argon2d,- Argon2i,- Argon2id-};--class Argon2 {- AK_MAKE_NONCOPYABLE(Argon2);--public:- explicit Argon2(Argon2Type);-- ~Argon2();-- static ErrorOr<void> validate_parameters(ReadonlyBytes nonce);-- ErrorOr<ByteBuffer> derive_key(- ReadonlyBytes message,- ReadonlyBytes nonce,- u32 parallelism,- u32 memory,- u32 passes,- u32 version,- Optional<ReadonlyBytes> secret_value,- Optional<ReadonlyBytes> associated_data,- u32 tag_length) const;--private:- EVP_KDF* m_kdf;-};--}diff --git a/Libraries/LibCrypto/Hash/HKDF.cpp b/Libraries/LibCrypto/Hash/HKDF.cppdeleted file mode 100644index 02a7032db1e..00000000000--- a/Libraries/LibCrypto/Hash/HKDF.cpp+++ /dev/null@@ -1,53 +0,0 @@-/*- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Hash/HKDF.h>-#include <LibCrypto/OpenSSL.h>--#include <openssl/core_names.h>-#include <openssl/kdf.h>-#include <openssl/params.h>--namespace Crypto::Hash {--HKDF::HKDF(HashKind hash_kind)- : m_kdf(EVP_KDF_fetch(nullptr, "HKDF", nullptr))- , m_hash_kind(hash_kind)-{-}--ErrorOr<ByteBuffer> HKDF::derive_key(Optional<ReadonlyBytes> maybe_salt, ReadonlyBytes key, ReadonlyBytes info, u32 key_length_bytes)-{- auto const* hash_name = TRY(openssl_digest_name(m_hash_kind));-- auto ctx = TRY(OpenSSL_KDF_CTX::wrap(EVP_KDF_CTX_new(m_kdf)));-- OSSL_PARAM params[] = {- OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, const_cast<char*>(hash_name), strlen(hash_name)),- OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, const_cast<u8*>(key.data()), key.size()),- OSSL_PARAM_octet_string(OSSL_KDF_PARAM_INFO, const_cast<u8*>(info.data()), info.size()),- OSSL_PARAM_END,- OSSL_PARAM_END,- };-- if (maybe_salt.has_value()) {- static constexpr u8 empty_salt[0] {};-- // FIXME: As of openssl 3.5.1, we can no longer pass a null salt pointer. This seems like a mistake; we should- // check if this is still the case in the next openssl release. See:- // https://github.com/openssl/openssl/pull/27305#discussion_r2198316685- auto salt = maybe_salt->is_null() ? ReadonlySpan<u8> { empty_salt, 0 } : *maybe_salt;-- params[3] = OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, const_cast<u8*>(salt.data()), salt.size());- }-- auto buf = TRY(ByteBuffer::create_uninitialized(key_length_bytes));- OPENSSL_TRY(EVP_KDF_derive(ctx.ptr(), buf.data(), key_length_bytes, params));-- return buf;-}--}diff --git a/Libraries/LibCrypto/Hash/HKDF.h b/Libraries/LibCrypto/Hash/HKDF.hdeleted file mode 100644index 15d339f2173..00000000000--- a/Libraries/LibCrypto/Hash/HKDF.h+++ /dev/null@@ -1,37 +0,0 @@-/*- * Copyright (c) 2023, stelar7 <[email protected]>- * Copyright (c) 2024, Ben Wiederhake <[email protected]>- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Optional.h>-#include <LibCrypto/Hash/Hash.h>--namespace Crypto::Hash {--class HKDF {- AK_MAKE_NONCOPYABLE(HKDF);--public:- HKDF(HashKind hash_kind);-- ~HKDF()- {- EVP_KDF_free(m_kdf);- }-- // Note: The output is different for a salt of length zero and an absent salt,- // so Optional<ReadonlyBytes> really is the correct type.- ErrorOr<ByteBuffer> derive_key(Optional<ReadonlyBytes> maybe_salt, ReadonlyBytes input_keying_material, ReadonlyBytes info, u32 key_length_bytes);--private:- EVP_KDF* m_kdf;- HashKind m_hash_kind;-};--}diff --git a/Libraries/LibCrypto/Hash/Hash.h b/Libraries/LibCrypto/Hash/Hash.hindex 8ca4142d163..5558df2b2c4 100644--- a/Libraries/LibCrypto/Hash/Hash.h+++ b/Libraries/LibCrypto/Hash/Hash.h@@ -15,7 +15,6 @@namespace Crypto::Hash {-// NB: libcrypto_rust passes these values across the FFI.enum class HashKind {Unknown,None,diff --git a/Libraries/LibCrypto/Hash/PBKDF2.cpp b/Libraries/LibCrypto/Hash/PBKDF2.cppdeleted file mode 100644index a4f0aea4987..00000000000--- a/Libraries/LibCrypto/Hash/PBKDF2.cpp+++ /dev/null@@ -1,42 +0,0 @@-/*- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Hash/PBKDF2.h>-#include <LibCrypto/OpenSSL.h>--#include <openssl/core_names.h>-#include <openssl/kdf.h>-#include <openssl/params.h>--namespace Crypto::Hash {--PBKDF2::PBKDF2(HashKind hash_kind)- : m_kdf(EVP_KDF_fetch(nullptr, "PBKDF2", nullptr))- , m_hash_kind(hash_kind)-{-}--ErrorOr<ByteBuffer> PBKDF2::derive_key(ReadonlyBytes password, ReadonlyBytes salt, u32 iterations, u32 key_length_bytes)-{- auto const* hash_name = TRY(openssl_digest_name(m_hash_kind));-- auto ctx = TRY(OpenSSL_KDF_CTX::wrap(EVP_KDF_CTX_new(m_kdf)));-- OSSL_PARAM params[] = {- OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, const_cast<char*>(hash_name), strlen(hash_name)),- OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, const_cast<u8*>(password.data()), password.size()),- OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, const_cast<u8*>(salt.data()), salt.size()),- OSSL_PARAM_uint32(OSSL_KDF_PARAM_ITER, &iterations),- OSSL_PARAM_END,- };-- auto buf = TRY(ByteBuffer::create_uninitialized(key_length_bytes));- OPENSSL_TRY(EVP_KDF_derive(ctx.ptr(), buf.data(), key_length_bytes, params));-- return buf;-}--}diff --git a/Libraries/LibCrypto/Hash/PBKDF2.h b/Libraries/LibCrypto/Hash/PBKDF2.hdeleted file mode 100644index 6ae783ea6f8..00000000000--- a/Libraries/LibCrypto/Hash/PBKDF2.h+++ /dev/null@@ -1,33 +0,0 @@-/*- * Copyright (c) 2023, stelar7 <[email protected]>- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <LibCrypto/Hash/Hash.h>--namespace Crypto::Hash {--class PBKDF2 {- AK_MAKE_NONCOPYABLE(PBKDF2);--public:- PBKDF2(HashKind hash_kind);-- ~PBKDF2()- {- EVP_KDF_free(m_kdf);- }-- ErrorOr<ByteBuffer> derive_key(ReadonlyBytes password, ReadonlyBytes salt, u32 iterations, u32 key_length_bytes);--private:- EVP_KDF* m_kdf;- HashKind m_hash_kind;-};--}diff --git a/Libraries/LibCrypto/Hash/SHAKE.cpp b/Libraries/LibCrypto/Hash/SHAKE.cppdeleted file mode 100644index 049e14b67ce..00000000000--- a/Libraries/LibCrypto/Hash/SHAKE.cpp+++ /dev/null@@ -1,96 +0,0 @@-/*- * Copyright (c) 2025, mikiubo <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/ByteBuffer.h>-#include <LibCrypto/Hash/SHAKE.h>-#include <LibCrypto/OpenSSL.h>-#include <openssl/evp.h>--namespace Crypto::Hash {--SHAKE::SHAKE(SHAKEKind kind)- : m_kind(kind)-{-}--ErrorOr<void> SHAKE::validate_parameters(u32 length)-{- if (length % 8 != 0) {- return Error::from_string_literal("SHAKE output length must be a multiple of 8 bits");- }-- return {};-}--// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf-static ErrorOr<void> left_encode(ByteBuffer& output, u64 value)-{- u8 bytes[sizeof(u64)];- size_t length = 0;- do {- bytes[sizeof(u64) - ++length] = static_cast<u8>(value);- value >>= 8;- } while (value != 0);-- TRY(output.try_append(static_cast<u8>(length)));- return output.try_append(bytes + sizeof(u64) - length, length);-}--// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf-static ErrorOr<void> encode_string(ByteBuffer& output, ReadonlyBytes string)-{- TRY(left_encode(output, static_cast<u64>(string.size()) * 8));- return output.try_append(string);-}--ErrorOr<ByteBuffer> SHAKE::digest(- ReadonlyBytes data,- u32 length,- Optional<ReadonlyBytes> customization,- Optional<ReadonlyBytes> function_name) const-{- TRY(validate_parameters(length));-- size_t output_bytes = length / 8;- auto buf = TRY(ByteBuffer::create_uninitialized(output_bytes));-- auto ctx = TRY(OpenSSL_MD_CTX::wrap(EVP_MD_CTX_new()));-- auto name = function_name.value_or({});- auto customization_string = customization.value_or({});-- // If N = "" and S = "", return SHAKE128(X, L) (or SHAKE256(X, L) for cSHAKE256).- if (name.is_empty() && customization_string.is_empty()) {- OPENSSL_TRY(EVP_DigestInit_ex(ctx.ptr(), m_kind == SHAKEKind::CSHAKE128 ? EVP_shake128() : EVP_shake256(), nullptr));- OPENSSL_TRY(EVP_DigestUpdate(ctx.ptr(), data.data(), data.size()));- OPENSSL_TRY(EVP_DigestFinalXOF(ctx.ptr(), buf.data(), output_bytes));- return buf;- }-- // Else return KECCAK[256](bytepad(encode_string(N) || encode_string(S), 168) || X || 00, L) for cSHAKE128, or- // KECCAK[512](bytepad(encode_string(N) || encode_string(S), 136) || X || 00, L) for cSHAKE256.- // NB: OpenSSL's KECCAK-KMAC digests are KECCAK[c](M || 00, L), the function that KMAC builds on.- size_t rate = m_kind == SHAKEKind::CSHAKE128 ? 168 : 136;- auto const* keccak_name = m_kind == SHAKEKind::CSHAKE128 ? "KECCAK-KMAC-128" : "KECCAK-KMAC-256";-- ByteBuffer prefix;- TRY(left_encode(prefix, rate));- TRY(encode_string(prefix, name));- TRY(encode_string(prefix, customization_string));- TRY(prefix.try_resize(ceil_div(prefix.size(), rate) * rate, ByteBuffer::ZeroFillNewElements::Yes));-- auto* keccak = OPENSSL_TRY_PTR(EVP_MD_fetch(nullptr, keccak_name, nullptr));- auto init_result = EVP_DigestInit_ex(ctx.ptr(), keccak, nullptr);- EVP_MD_free(keccak);- OPENSSL_TRY(init_result);-- OPENSSL_TRY(EVP_DigestUpdate(ctx.ptr(), prefix.data(), prefix.size()));- OPENSSL_TRY(EVP_DigestUpdate(ctx.ptr(), data.data(), data.size()));- OPENSSL_TRY(EVP_DigestFinalXOF(ctx.ptr(), buf.data(), output_bytes));- return buf;-}--}diff --git a/Libraries/LibCrypto/Hash/SHAKE.h b/Libraries/LibCrypto/Hash/SHAKE.hdeleted file mode 100644index 76b97efbf3e..00000000000--- a/Libraries/LibCrypto/Hash/SHAKE.h+++ /dev/null@@ -1,41 +0,0 @@-/*- * Copyright (c) 2025, mikiubo <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Error.h>-#include <AK/Noncopyable.h>-#include <LibCrypto/OpenSSLForward.h>--namespace Crypto::Hash {--enum class SHAKEKind {- CSHAKE128,- CSHAKE256-};--class SHAKE {- AK_MAKE_NONCOPYABLE(SHAKE);--public:- explicit SHAKE(SHAKEKind);-- ~SHAKE() = default;-- static ErrorOr<void> validate_parameters(u32 length);-- ErrorOr<ByteBuffer> digest(- ReadonlyBytes data,- u32 length,- Optional<ReadonlyBytes> customization,- Optional<ReadonlyBytes> function_name) const;--private:- SHAKEKind m_kind;-};--}diff --git a/Libraries/LibCrypto/KeyHandle.cpp b/Libraries/LibCrypto/KeyHandle.cppdeleted file mode 100644index b26cfb82532..00000000000--- a/Libraries/LibCrypto/KeyHandle.cpp+++ /dev/null@@ -1,242 +0,0 @@-/*- * 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 };-};--// NB: libcrypto_rust passes these values across the FFI.-enum class KeyDecodeResult : u8 {- Decoded,- InvalidComponents,- OutOfMemory,-};--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*));-KeyDecodeResult 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()); },- [](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);--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; };- // 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());- };- 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(MUST(rsa_key.modulus()));- add_exported(MUST(rsa_key.public_exponent()));- },- [&](::Crypto::PK::RSAPrivateKey const& rsa_key) {- fields.handle_tag = to_underlying(HandleTag::RSAPrivateKey);- using Component = ::Crypto::PK::RSAPrivateKey::Component;- // NB: The stored order puts the private exponent before the public one.- for (auto component : { Component::Modulus, Component::PrivateExponent, Component::PublicExponent, Component::Prime1, Component::Prime2, Component::Exponent1, Component::Exponent2, Component::Coefficient })- add_exported(MUST(rsa_key.component(component)));- },- [&](::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(MUST(mldsa_key.seed(seed_buffer)));- add(mldsa_key.public_key().bytes());- add_exported(MUST(mldsa_key.expanded_key()));- },- [&](::Crypto::PK::MLKEMPublicKey const& mlkem_key) {- fields.handle_tag = to_underlying(HandleTag::MLKEMPublicKey);- add(mlkem_key.public_key().bytes());- },- [&](::Crypto::PK::MLKEMPrivateKey const& mlkem_key) {- fields.handle_tag = to_underlying(HandleTag::MLKEMPrivateKey);- add(MUST(mlkem_key.seed(seed_buffer)));- add(mlkem_key.public_key().bytes());- add_exported(MUST(mlkem_key.expanded_key()));- },- [&](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());- secure_zero(seed_buffer.data(), seed_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)));- };-- switch (static_cast<HandleTag>(fields.handle_tag)) {- case HandleTag::ByteBuffer:- return TRY(copy(0));- case HandleTag::RSAPublicKey:- return TRY(::Crypto::PK::RSAPublicKey::from_components(buffer(0), buffer(1)));- case HandleTag::RSAPrivateKey: {- // NB: A key without CRT components stores them empty.- Optional<::Crypto::PK::RSACRTComponents> crt_components;- if (!buffer(3).is_empty())- crt_components = ::Crypto::PK::RSACRTComponents { buffer(3), buffer(4), buffer(5), buffer(6), buffer(7) };- return TRY(::Crypto::PK::RSAPrivateKey::from_components(buffer(0), buffer(2), buffer(1), crt_components));- }- case HandleTag::ECPublicKey:- return TRY(::Crypto::PK::ECPublicKey::from_coordinates(buffer(0), buffer(1)));- 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 = 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 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 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:- return OKPPrivateKey { TRY(copy(0)) };- }- VERIFY_NOT_REACHED();-}--KeyDecodeResult crypto_key_decode_handle(CryptoKeyHandleFields const* fields, KeyHandle** out_handle)-{- auto handle = handle_from_fields(*fields);- if (handle.is_error()) {- // NB: An allocation fails with ENOMEM. Any other error is a component that does not make a valid key.- if (handle.error().is_errno() && handle.error().code() == ENOMEM)- return KeyDecodeResult::OutOfMemory;- return KeyDecodeResult::InvalidComponents;- }- *out_handle = new KeyHandle(handle.release_value());- return KeyDecodeResult::Decoded;-}--}diff --git a/Libraries/LibCrypto/KeyHandle.h b/Libraries/LibCrypto/KeyHandle.hdeleted file mode 100644index e48a9964e02..00000000000--- a/Libraries/LibCrypto/KeyHandle.h+++ /dev/null@@ -1,49 +0,0 @@-/*- * 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/OpenSSL.cpp b/Libraries/LibCrypto/OpenSSL.cppindex da4612cf0b7..1535197a0ff 100644--- a/Libraries/LibCrypto/OpenSSL.cpp+++ b/Libraries/LibCrypto/OpenSSL.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/ByteBuffer.h>#include <LibCrypto/OpenSSL.h>#include <openssl/bn.h>@@ -12,11 +11,6 @@namespace Crypto {-ErrorOr<OpenSSL_BN> OpenSSL_BN::create()-{- return OpenSSL_BN(OPENSSL_TRY_PTR(BN_new()));-}-ErrorOr<OpenSSL_PKEY> OpenSSL_PKEY::create(){return OpenSSL_PKEY(OPENSSL_TRY_PTR(EVP_PKEY_new()));@@ -63,20 +57,4 @@ ErrorOr<OpenSSL_MD_CTX> OpenSSL_MD_CTX::create()return OpenSSL_MD_CTX(OPENSSL_TRY_PTR(EVP_MD_CTX_new()));}-ErrorOr<OpenSSL_CIPHER_CTX> OpenSSL_CIPHER_CTX::create()-{- return OpenSSL_CIPHER_CTX(OPENSSL_TRY_PTR(EVP_CIPHER_CTX_new()));-}--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, key_name, nullptr, 0, &size));-- auto buffer = TRY(ByteBuffer::create_uninitialized(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.hindex db81dbd7e2e..63ede93b22a 100644--- a/Libraries/LibCrypto/OpenSSL.h+++ b/Libraries/LibCrypto/OpenSSL.h@@ -85,13 +85,6 @@ class OpenSSL_X509 {OPENSSL_WRAPPER_CLASS(OpenSSL_X509, X509, X509);};-class OpenSSL_BN {- OPENSSL_WRAPPER_CLASS(OpenSSL_BN, BIGNUM, BN);--public:- static ErrorOr<OpenSSL_BN> create();-};-class OpenSSL_PKEY {OPENSSL_WRAPPER_CLASS(OpenSSL_PKEY, EVP_PKEY, EVP_PKEY);@@ -124,14 +117,6 @@ class OpenSSL_PKEY_CTX {OPENSSL_WRAPPER_CLASS(OpenSSL_PKEY_CTX, EVP_PKEY_CTX, EVP_PKEY_CTX);};-class OpenSSL_MAC {- OPENSSL_WRAPPER_CLASS(OpenSSL_MAC, EVP_MAC, EVP_MAC);-};--class OpenSSL_MAC_CTX {- OPENSSL_WRAPPER_CLASS(OpenSSL_MAC_CTX, EVP_MAC_CTX, EVP_MAC_CTX);-};-class OpenSSL_MD_CTX {OPENSSL_WRAPPER_CLASS(OpenSSL_MD_CTX, EVP_MD_CTX, EVP_MD_CTX);@@ -139,19 +124,6 @@ public:static ErrorOr<OpenSSL_MD_CTX> create();};-class OpenSSL_KDF_CTX {- OPENSSL_WRAPPER_CLASS(OpenSSL_KDF_CTX, EVP_KDF_CTX, EVP_KDF_CTX);-};--class OpenSSL_CIPHER_CTX {- OPENSSL_WRAPPER_CLASS(OpenSSL_CIPHER_CTX, EVP_CIPHER_CTX, EVP_CIPHER_CTX);--public:- static ErrorOr<OpenSSL_CIPHER_CTX> create();-};-#undef OPENSSL_WRAPPER_CLASS-ErrorOr<ByteBuffer> get_byte_buffer_param_from_key(EVP_PKEY* key, char const* key_name);-}diff --git a/Libraries/LibCrypto/OpenSSLForward.h b/Libraries/LibCrypto/OpenSSLForward.hindex 5b699467343..b274d249179 100644--- a/Libraries/LibCrypto/OpenSSLForward.h+++ b/Libraries/LibCrypto/OpenSSLForward.h@@ -8,17 +8,10 @@extern "C" {typedef struct engine_st ENGINE;-typedef struct bignum_st BIGNUM;typedef struct evp_md_st EVP_MD;typedef struct evp_md_ctx_st EVP_MD_CTX;typedef struct evp_pkey_st EVP_PKEY;typedef struct evp_pkey_ctx_st EVP_PKEY_CTX;-typedef struct evp_kdf_st EVP_KDF;-typedef struct evp_kdf_ctx_st EVP_KDF_CTX;-typedef struct evp_mac_st EVP_MAC;-typedef struct evp_mac_ctx_st EVP_MAC_CTX;-typedef struct evp_cipher_st EVP_CIPHER;-typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX;typedef struct x509_st X509;void ERR_print_errors_cb(int (*cb)(char const* str, size_t len, void* u), void* u);@@ -28,12 +21,6 @@ void X509_free(X509*);EVP_MD_CTX* EVP_MD_CTX_new();void EVP_MD_CTX_free(EVP_MD_CTX*);-void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX*);void EVP_PKEY_CTX_free(EVP_PKEY_CTX*);void EVP_PKEY_free(EVP_PKEY*);-void EVP_KDF_CTX_free(EVP_KDF_CTX* ctx);-void EVP_KDF_free(EVP_KDF* kdf);-void EVP_MAC_CTX_free(EVP_MAC_CTX*);-void EVP_MAC_free(EVP_MAC*);-void BN_free(BIGNUM*);}diff --git a/Libraries/LibCrypto/PK/EC.cpp b/Libraries/LibCrypto/PK/EC.cppindex e127e4bc1f5..50608c9c900 100644--- a/Libraries/LibCrypto/PK/EC.cpp+++ b/Libraries/LibCrypto/PK/EC.cpp@@ -8,7 +8,6 @@#include <AK/Memory.h>#include <AK/ScopeGuard.h>#include <AK/StringView.h>-#include <LibCrypto/ASN1/DER.h>#include <LibCrypto/OpenSSL.h>#include <LibCrypto/PK/EC.h>@@ -122,157 +121,6 @@ ErrorOr<ByteBuffer> ECPublicKey::to_uncompressed() constreturn bytes;}-ErrorOr<ECPrivateKey> ECPrivateKey::generate(size_t scalar_size)-{- auto key = OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(EVP_PKEY_Q_keygen(nullptr, nullptr, "EC", TRY(curve_name(scalar_size))))) };- ECPrivateKey private_key { move(key), scalar_size, {}, {} };- private_key.m_public_key = TRY(private_key.derive_public_key());- return private_key;-}--ErrorOr<ECPrivateKey> ECPrivateKey::from_scalar(ReadonlyBytes d_bytes, Optional<ASN1::ObjectIdentifier> parameters, Optional<ECPublicKey> public_key)-{- auto const* group_name = TRY(curve_name(d_bytes.size()));-- auto* group = OPENSSL_TRY_PTR(EC_GROUP_new_by_curve_name(EC_curve_nist2nid(group_name)));- ScopeGuard const free_group = [&] { EC_GROUP_free(group); };-- auto* d = OPENSSL_TRY_PTR(BN_secure_new());- ScopeGuard const free_d = [&] { BN_clear_free(d); };- OPENSSL_TRY_PTR(BN_bin2bn(d_bytes.data(), d_bytes.size(), d));-- // NB: SEC 1 requires d to be in [1, n − 1].- if (BN_is_zero(d) || BN_cmp(d, EC_GROUP_get0_order(group)) >= 0)- return Error::from_string_literal("EC private key is out of range");-- auto* point = OPENSSL_TRY_PTR(EC_POINT_new(group));- ScopeGuard const free_point = [&] { EC_POINT_free(point); };- OPENSSL_TRY(EC_POINT_mul(group, point, d, nullptr, nullptr, nullptr));-- auto public_octets = TRY(ByteBuffer::create_uninitialized(1 + 2 * d_bytes.size()));- if (EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, public_octets.data(), public_octets.size(), nullptr) != public_octets.size())- return Error::from_string_literal("Failed to encode EC public key");-- if (public_key.has_value() && TRY(public_key->to_uncompressed()) != public_octets)- return Error::from_string_literal("EC public key does not match the private key");-- auto* builder = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());- ScopeGuard const free_builder = [&] { OSSL_PARAM_BLD_free(builder); };- OPENSSL_TRY(OSSL_PARAM_BLD_push_utf8_string(builder, OSSL_PKEY_PARAM_GROUP_NAME, group_name, 0));- OPENSSL_TRY(OSSL_PARAM_BLD_push_BN(builder, OSSL_PKEY_PARAM_PRIV_KEY, d));- OPENSSL_TRY(OSSL_PARAM_BLD_push_octet_string(builder, OSSL_PKEY_PARAM_PUB_KEY, public_octets.data(), public_octets.size()));- auto key = TRY(key_from_parameters(EVP_PKEY_KEYPAIR, builder));-- return ECPrivateKey { move(key), d_bytes.size(), move(parameters), move(public_key) };-}--// https://www.rfc-editor.org/rfc/rfc5915#section-3-static ErrorOr<ByteBuffer> encode_private_key(ReadonlyBytes d, Optional<ASN1::ObjectIdentifier> const& parameters, Optional<ReadonlyBytes> public_point)-{- ASN1::Encoder encoder;- TRY(encoder.write_constructed(ASN1::Class::Universal, ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {- TRY(encoder.write(1u)); // version- TRY(encoder.write<ReadonlyBytes>(d));-- if (parameters.has_value()) {- TRY(encoder.write_constructed(ASN1::Class::Context, static_cast<ASN1::Kind>(0), [&]() -> ErrorOr<void> {- TRY(encoder.write<ASN1::ObjectIdentifier>(*parameters, {}, ASN1::Kind::ObjectIdentifier));- return {};- }));- }-- if (public_point.has_value()) {- TRY(encoder.write_constructed(ASN1::Class::Context, static_cast<ASN1::Kind>(1), [&]() -> ErrorOr<void> {- TRY(encoder.write(ASN1::BitStringView(*public_point, 0)));- return {};- }));- }-- return {};- }));-- return encoder.finish();-}--ErrorOr<ECPrivateKey> ECPrivateKey::from_private_key_info(EVP_PKEY* key, ASN1::ObjectIdentifier const& curve, ReadonlyBytes encoded)-{- auto scalar_size = (EVP_PKEY_get_bits(key) + 7) / 8;- auto d = TRY(integer_parameter(key, OSSL_PKEY_PARAM_PRIV_KEY, scalar_size));- ScopeGuard const clear_d = [&] { secure_zero(d.data(), d.size()); };- auto public_key = TRY(TRY(from_scalar(d, {}, {})).derive_public_key());-- auto uncompressed = TRY(public_key.to_uncompressed());- auto compressed = TRY(ByteBuffer::copy(uncompressed.bytes().trim(1 + scalar_size)));- compressed[0] = 0x02 | (uncompressed.bytes().last() & 1);-- // NB: OpenSSL accepts BER, and a privateKey of any width. The parameters and the public key are optional, and the- // public key may be compressed, so the encoding must be the DER encoding of the key in one of those forms.- for (auto with_parameters : { false, true }) {- for (auto public_point : { Optional<ReadonlyBytes> {}, Optional<ReadonlyBytes> { uncompressed }, Optional<ReadonlyBytes> { compressed } }) {- Optional<ASN1::ObjectIdentifier> parameters;- if (with_parameters)- parameters = curve;- auto candidate_encoding = TRY(encode_private_key(d, parameters, public_point));- ScopeGuard const clear_candidate_encoding = [&] { secure_zero(candidate_encoding.data(), candidate_encoding.size()); };- if (candidate_encoding != encoded)- continue;-- Optional<ECPublicKey> maybe_public_key;- if (public_point.has_value())- maybe_public_key = public_key;- return from_scalar(d, move(parameters), move(maybe_public_key));- }- }- return Error::from_string_literal("Invalid ECPrivateKey");-}--ErrorOr<ByteBuffer> ECPrivateKey::d_bytes() const-{- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_PRIV_KEY, m_scalar_size);-}--ErrorOr<ECPublicKey> ECPrivateKey::derive_public_key() const-{- auto x = TRY(integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_EC_PUB_X, m_scalar_size));- auto y = TRY(integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_EC_PUB_Y, m_scalar_size));- return ECPublicKey::from_coordinates(x, y);-}--ErrorOr<ByteBuffer> ECPrivateKey::export_as_der() const-{- auto d = TRY(d_bytes());- ScopeGuard const clear_d = [&] { secure_zero(d.data(), d.size()); };- Optional<ByteBuffer> public_point;- if (m_public_key.has_value())- public_point = TRY(m_public_key->to_uncompressed());- return encode_private_key(d, m_parameters, public_point.map([](auto const& point) { return point.bytes(); }));-}--ErrorOr<ECDSASignature> ecdsa_sign(ECPrivateKey const& private_key, ReadonlyBytes digest)-{- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, private_key.openssl_key(), nullptr)));- OPENSSL_TRY(EVP_PKEY_sign_init(ctx.ptr()));-- size_t signature_size = 0;- OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), nullptr, &signature_size, digest.data(), digest.size()));-- auto signature = TRY(ByteBuffer::create_uninitialized(signature_size));- OPENSSL_TRY(EVP_PKEY_sign(ctx.ptr(), signature.data(), &signature_size, digest.data(), digest.size()));-- auto const* signature_data = signature.data();- auto* signature_object = OPENSSL_TRY_PTR(d2i_ECDSA_SIG(nullptr, &signature_data, signature_size));- ScopeGuard const free_signature_object = [&] { ECDSA_SIG_free(signature_object); };-- auto size = private_key.scalar_size();- ECDSASignature result {- TRY(ByteBuffer::create_uninitialized(size)),- TRY(ByteBuffer::create_uninitialized(size)),- };- if (BN_bn2binpad(ECDSA_SIG_get0_r(signature_object), result.r.data(), size) < 0 || BN_bn2binpad(ECDSA_SIG_get0_s(signature_object), result.s.data(), size) < 0)- return Error::from_string_literal("ECDSA signature is too large");- return result;-}-ErrorOr<bool> ecdsa_verify(ECPublicKey const& public_key, ReadonlyBytes digest, ReadonlyBytes r, ReadonlyBytes s){if (r.size() != public_key.scalar_size() || s.size() != public_key.scalar_size())@@ -307,22 +155,4 @@ ErrorOr<bool> ecdsa_verify(ECPublicKey const& public_key, ReadonlyBytes digest,VERIFY_NOT_REACHED();}-ErrorOr<ByteBuffer> ecdh_derive(ECPrivateKey const& private_key, ECPublicKey const& peer)-{- if (private_key.scalar_size() != peer.scalar_size())- return Error::from_string_literal("EC keys are on different curves");-- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, private_key.openssl_key(), nullptr)));- OPENSSL_TRY(EVP_PKEY_derive_init(ctx.ptr()));- OPENSSL_TRY(EVP_PKEY_derive_set_peer_ex(ctx.ptr(), peer.openssl_key(), 1));-- size_t secret_size = 0;- OPENSSL_TRY(EVP_PKEY_derive(ctx.ptr(), nullptr, &secret_size));-- auto secret = TRY(ByteBuffer::create_uninitialized(secret_size));- OPENSSL_TRY(EVP_PKEY_derive(ctx.ptr(), secret.data(), &secret_size));- secret.resize(secret_size);- return secret;-}-}diff --git a/Libraries/LibCrypto/PK/EC.h b/Libraries/LibCrypto/PK/EC.hindex a89a06280af..fef68589ecb 100644--- a/Libraries/LibCrypto/PK/EC.h+++ b/Libraries/LibCrypto/PK/EC.h@@ -9,7 +9,6 @@#include <AK/ByteBuffer.h>#include <AK/Optional.h>#include <AK/StringView.h>-#include <LibCrypto/ASN1/DER.h>#include <LibCrypto/OpenSSL.h>// NB: Each key's curve is the NIST prime curve whose coordinates have the key's scalar size: 32 bytes for P-256, 48 for@@ -42,52 +41,6 @@ private:size_t m_scalar_size { 0 };};-// https://www.rfc-editor.org/rfc/rfc5915#section-3-class ECPrivateKey {-public:- ECPrivateKey() = default;-- static ErrorOr<ECPrivateKey> generate(size_t scalar_size);- static ErrorOr<ECPrivateKey> from_scalar(ReadonlyBytes d, Optional<ASN1::ObjectIdentifier> parameters, Optional<ECPublicKey> public_key);-- // The ECPrivateKey inside a PKCS#8 PrivateKeyInfo, whose key OpenSSL has decoded, and whose AlgorithmIdentifier names the curve.- static ErrorOr<ECPrivateKey> from_private_key_info(EVP_PKEY*, ASN1::ObjectIdentifier const& curve, ReadonlyBytes encoded);-- size_t scalar_size() const { return m_scalar_size; }-- ErrorOr<ByteBuffer> d_bytes() const;- ErrorOr<ECPublicKey> derive_public_key() const;-- Optional<ASN1::ObjectIdentifier> const& parameters() const { return m_parameters; }- Optional<ECPublicKey> const& public_key() const { return m_public_key; }-- ErrorOr<ByteBuffer> export_as_der() const;-- EVP_PKEY* openssl_key() const { return m_key.ptr(); }--private:- ECPrivateKey(OpenSSL_SharedPKEY key, size_t scalar_size, Optional<ASN1::ObjectIdentifier> parameters, Optional<ECPublicKey> public_key)- : m_key(move(key))- , m_scalar_size(scalar_size)- , m_parameters(move(parameters))- , m_public_key(move(public_key))- {- }-- OpenSSL_SharedPKEY m_key;- size_t m_scalar_size { 0 };- Optional<ASN1::ObjectIdentifier> m_parameters;- Optional<ECPublicKey> m_public_key;-};--struct ECDSASignature {- ByteBuffer r;- ByteBuffer s;-};--ErrorOr<ECDSASignature> ecdsa_sign(ECPrivateKey const&, ReadonlyBytes digest);ErrorOr<bool> ecdsa_verify(ECPublicKey const&, ReadonlyBytes digest, ReadonlyBytes r, ReadonlyBytes s);-ErrorOr<ByteBuffer> ecdh_derive(ECPrivateKey const&, ECPublicKey const& peer);-}diff --git a/Libraries/LibCrypto/PK/KeyInfo.cpp b/Libraries/LibCrypto/PK/KeyInfo.cppdeleted file mode 100644index 8764a10da9c..00000000000--- a/Libraries/LibCrypto/PK/KeyInfo.cpp+++ /dev/null@@ -1,267 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/CharacterTypes.h>-#include <AK/Memory.h>-#include <AK/ScopeGuard.h>-#include <LibCrypto/ASN1/Constants.h>-#include <LibCrypto/OpenSSL.h>-#include <LibCrypto/PK/KeyInfo.h>--#include <openssl/bn.h>-#include <openssl/core_names.h>-#include <openssl/evp.h>-#include <openssl/objects.h>-#include <openssl/x509.h>--namespace Crypto::PK {--static ErrorOr<ASN1::ObjectIdentifier> object_identifier(ASN1_OBJECT const* object)-{- char text[256];- auto length = OBJ_obj2txt(text, sizeof(text), object, 1);- if (length <= 0 || static_cast<size_t>(length) >= sizeof(text))- return Error::from_string_literal("Invalid object identifier");-- ASN1::ObjectIdentifier identifier;- for (auto arc : StringView { text, static_cast<size_t>(length) }.split_view('.')) {- auto value = arc.to_number<u32>();- if (!value.has_value())- return Error::from_string_literal("Invalid object identifier");- TRY(identifier.try_append(*value));- }- return identifier;-}--static ErrorOr<AlgorithmIdentifier> algorithm_identifier(X509_ALGOR const* algorithm)-{- ASN1_OBJECT const* object = nullptr;- int parameters_type = 0;- void const* parameters = nullptr;- X509_ALGOR_get0(&object, ¶meters_type, ¶meters, algorithm);-- AlgorithmIdentifier result;- result.identifier = TRY(object_identifier(object));- if (parameters_type == V_ASN1_OBJECT)- result.ec_parameters = TRY(object_identifier(static_cast<ASN1_OBJECT const*>(parameters)));- return result;-}--static bool is_named_curve(AlgorithmIdentifier const& algorithm)-{- if (!algorithm.ec_parameters.has_value())- return false;- auto const& curve = *algorithm.ec_parameters;- return curve == ASN1::secp256r1_oid || curve == ASN1::secp384r1_oid || curve == ASN1::secp521r1_oid;-}--static bool is_ml_kem(ASN1::ObjectIdentifier const& identifier)-{- return identifier == ASN1::ml_kem_512_oid || identifier == ASN1::ml_kem_768_oid || identifier == ASN1::ml_kem_1024_oid;-}--// NB: The structure is in DER, so its SEQUENCE's length takes one byte, or one more than the count in that byte's low-// bits. Version 0 follows as 02 01 00.-static bool has_version_zero(ReadonlyBytes der)-{- static constexpr u8 version_zero[] { 0x02, 0x01, 0x00 };- if (der.size() < 2)- return false;- size_t header_size = 2 + ((der[1] & 0x80) ? (der[1] & 0x7f) : 0);- return der.size() >= header_size + sizeof(version_zero) && der.slice(header_size, sizeof(version_zero)) == ReadonlyBytes { version_zero, sizeof(version_zero) };-}--static bool encodes_as(ReadonlyBytes expected, u8 const* encoded, int encoded_size)-{- return encoded_size >= 0 && static_cast<size_t>(encoded_size) == expected.size() && expected == ReadonlyBytes { encoded, static_cast<size_t>(encoded_size) };-}--ErrorOr<SubjectPublicKeyInfo> parse_subject_public_key_info(ReadonlyBytes data, size_t& consumed)-{- auto const* cursor = data.data();- auto* public_key_info = d2i_X509_PUBKEY(nullptr, &cursor, data.size());- if (!public_key_info)- return Error::from_string_literal("Invalid SubjectPublicKeyInfo");- ScopeGuard const free_public_key_info = [&] { X509_PUBKEY_free(public_key_info); };- consumed = cursor - data.data();-- ASN1_OBJECT* object = nullptr;- u8 const* key_bits = nullptr;- int key_size = 0;- X509_ALGOR* algorithm = nullptr;- OPENSSL_TRY(X509_PUBKEY_get0_param(&object, &key_bits, &key_size, &algorithm, public_key_info));-- SubjectPublicKeyInfo result;- result.algorithm = TRY(algorithm_identifier(algorithm));- result.raw_key = TRY(ByteBuffer::copy(key_bits, key_size));-- // NB: OpenSSL runs the ML-KEM encapsulation key check when it decodes the key, but Web Crypto runs it at- // encapsulation. So an ML-KEM key is only checked to be in DER, without parameters.- if (is_ml_kem(result.algorithm.identifier)) {- int parameters_type = 0;- X509_ALGOR_get0(nullptr, ¶meters_type, nullptr, algorithm);- if (parameters_type != V_ASN1_UNDEF)- return Error::from_string_literal("The algorithm takes no parameters");-- u8* encoded = nullptr;- auto encoded_size = i2d_X509_PUBKEY(public_key_info, &encoded);- ScopeGuard const free_encoded = [&] { OPENSSL_free(encoded); };- // NB: The BIT STRING's contents end the encoding, and are its count of unused bits followed by the key.- if (!encodes_as(data.trim(consumed), encoded, encoded_size) || data[consumed - key_size - 1] != 0)- return Error::from_string_literal("SubjectPublicKeyInfo is not in DER");- return result;- }-- auto* key = X509_PUBKEY_get(public_key_info);- if (!key)- return Error::from_string_literal("Invalid or unsupported public key");- auto shared_key = OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(key)) };-- // NB: OpenSSL accepts BER, and parameters that an algorithm does not use. Its own encoding of the key is the DER- // encoding with the parameters that the algorithm takes, so any other input is not valid.- u8* encoded = nullptr;- auto encoded_size = i2d_PUBKEY(shared_key.ptr(), &encoded);- ScopeGuard const free_encoded = [&] { OPENSSL_free(encoded); };- if (!encodes_as(data.trim(consumed), encoded, encoded_size))- return Error::from_string_literal("SubjectPublicKeyInfo is not in DER");-- auto const& identifier = result.algorithm.identifier;- if (identifier == ASN1::rsa_encryption_oid) {- result.rsa = RSAPublicKey::from_openssl_key(move(shared_key));- } else if (identifier == ASN1::ec_public_key_encryption_oid) {- if (!is_named_curve(result.algorithm))- return Error::from_string_literal("Unsupported EC parameters");- result.ec = TRY(ECPublicKey::from_octets(result.raw_key));- }- return result;-}--ErrorOr<PrivateKeyInfo> parse_private_key_info(ReadonlyBytes data, size_t& consumed)-{- auto const* cursor = data.data();- auto* private_key_info = d2i_PKCS8_PRIV_KEY_INFO(nullptr, &cursor, data.size());- if (!private_key_info)- return Error::from_string_literal("Invalid PrivateKeyInfo");- ScopeGuard const free_private_key_info = [&] { PKCS8_PRIV_KEY_INFO_free(private_key_info); };- consumed = cursor - data.data();-- {- u8* encoded = nullptr;- auto encoded_size = i2d_PKCS8_PRIV_KEY_INFO(private_key_info, &encoded);- ScopeGuard const free_encoded = [&] { OPENSSL_clear_free(encoded, max(encoded_size, 0)); };- if (!encodes_as(data.trim(consumed), encoded, encoded_size))- return Error::from_string_literal("PrivateKeyInfo is not in DER");- }-- // NB: OpenSSL also takes the version 1 OneAsymmetricKey of RFC 5958.- if (!has_version_zero(data.trim(consumed)))- return Error::from_string_literal("Unsupported PrivateKeyInfo version");-- ASN1_OBJECT const* object = nullptr;- u8 const* private_key = nullptr;- int private_key_size = 0;- X509_ALGOR const* algorithm = nullptr;- OPENSSL_TRY(PKCS8_pkey_get0(&object, &private_key, &private_key_size, &algorithm, private_key_info));-- // NB: The private key is copied into the result only once it has been checked, since a copy left in a result that- // is given up would not be cleared.- ReadonlyBytes raw_key { private_key, static_cast<size_t>(private_key_size) };-- PrivateKeyInfo result;- result.algorithm = TRY(algorithm_identifier(algorithm));-- auto const& identifier = result.algorithm.identifier;-- // https://www.rfc-editor.org/rfc/rfc8410#section-9- // For all of the OIDs, the parameters MUST be absent.- // https://www.rfc-editor.org/rfc/rfc9881#section-2- // The contents of the parameters component for each algorithm MUST be absent.- // NB: ML-KEM's parameters are absent likewise, and the outer encoding check above keeps whatever parameters were given.- if (identifier != ASN1::rsa_encryption_oid && identifier != ASN1::ec_public_key_encryption_oid) {- int parameters_type = 0;- X509_ALGOR_get0(nullptr, ¶meters_type, nullptr, algorithm);- if (parameters_type != V_ASN1_UNDEF)- return Error::from_string_literal("The algorithm takes no parameters");- }-- // NB: The ML-DSA and ML-KEM privateKey choices are parsed here, since OpenSSL also takes forms that Web Crypto does- // not, and refuses an expandedKey that is not valid before Web Crypto can reject that form.- if (identifier == ASN1::ml_dsa_44_oid || identifier == ASN1::ml_dsa_65_oid || identifier == ASN1::ml_dsa_87_oid) {- auto size = identifier == ASN1::ml_dsa_44_oid ? MLDSA44 : identifier == ASN1::ml_dsa_65_oid ? MLDSA65- : MLDSA87;- result.mldsa = TRY(MLDSA::parse_mldsa_key(size, raw_key)).private_key;- result.raw_key = TRY(ByteBuffer::copy(raw_key));- return result;- }- if (is_ml_kem(identifier)) {- auto size = identifier == ASN1::ml_kem_512_oid ? MLKEMSize::MLKEM512 : identifier == ASN1::ml_kem_768_oid ? MLKEMSize::MLKEM768- : MLKEMSize::MLKEM1024;- result.mlkem = TRY(MLKEM::parse_mlkem_key(size, raw_key)).private_key;- result.raw_key = TRY(ByteBuffer::copy(raw_key));- return result;- }-- auto* key = EVP_PKCS82PKEY(private_key_info);- if (!key)- return Error::from_string_literal("Invalid or unsupported private key");- auto shared_key = OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(key)) };-- if (identifier == ASN1::rsa_encryption_oid) {- // https://www.rfc-editor.org/rfc/rfc3279#section-2.3.1- // The parameters field MUST have ASN.1 type NULL for this algorithm identifier.- int parameters_type = 0;- X509_ALGOR_get0(nullptr, ¶meters_type, nullptr, algorithm);- if (parameters_type != V_ASN1_NULL)- return Error::from_string_literal("RSA parameters must be NULL");-- // NB: OpenSSL accepts BER in the RSAPrivateKey, so it must be the key's own DER encoding.- u8* encoded = nullptr;- auto encoded_size = i2d_PrivateKey(shared_key.ptr(), &encoded);- ScopeGuard const free_encoded = [&] { OPENSSL_clear_free(encoded, max(encoded_size, 0)); };- if (!encodes_as(raw_key, encoded, encoded_size))- return Error::from_string_literal("RSAPrivateKey is not in DER");-- // NB: OpenSSL also takes other versions, and otherPrimeInfos even in version 0. Keys of more than two primes are- // not supported, as in JWK import.- if (!has_version_zero(raw_key))- return Error::from_string_literal("Unsupported RSAPrivateKey version");- BIGNUM* third_prime = nullptr;- bool has_third_prime = EVP_PKEY_get_bn_param(shared_key.ptr(), OSSL_PKEY_PARAM_RSA_FACTOR3, &third_prime) == 1;- BN_clear_free(third_prime);- if (has_third_prime)- return Error::from_string_literal("RSA keys of more than two primes are not supported");-- result.rsa = RSAPrivateKey::from_openssl_key(move(shared_key));- } else if (identifier == ASN1::ec_public_key_encryption_oid) {- if (!is_named_curve(result.algorithm))- return Error::from_string_literal("Unsupported EC parameters");- result.ec = TRY(ECPrivateKey::from_private_key_info(shared_key.ptr(), *result.algorithm.ec_parameters, raw_key));- }- result.raw_key = TRY(ByteBuffer::copy(raw_key));- return result;-}--ErrorOr<ReadonlyBytes> parse_octet_string(ReadonlyBytes data, size_t& consumed)-{- auto const* cursor = data.data();- auto* octet_string = d2i_ASN1_OCTET_STRING(nullptr, &cursor, data.size());- if (!octet_string)- return Error::from_string_literal("Invalid OCTET STRING");- // NB: The OCTET STRING holds an OKP private key, so it is cleared.- ScopeGuard const free_octet_string = [&] { ASN1_STRING_clear_free(octet_string); };- consumed = cursor - data.data();-- u8* encoded = nullptr;- auto encoded_size = i2d_ASN1_OCTET_STRING(octet_string, &encoded);- ScopeGuard const free_encoded = [&] { OPENSSL_clear_free(encoded, max(encoded_size, 0)); };- if (!encodes_as(data.trim(consumed), encoded, encoded_size))- return Error::from_string_literal("OCTET STRING is not in DER");-- // NB: In DER the contents are the last bytes of the encoding.- return data.slice(consumed - ASN1_STRING_length(octet_string), ASN1_STRING_length(octet_string));-}--}diff --git a/Libraries/LibCrypto/PK/KeyInfo.h b/Libraries/LibCrypto/PK/KeyInfo.hdeleted file mode 100644index cf770d46efb..00000000000--- a/Libraries/LibCrypto/PK/KeyInfo.h+++ /dev/null@@ -1,49 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Optional.h>-#include <LibCrypto/ASN1/DER.h>-#include <LibCrypto/PK/EC.h>-#include <LibCrypto/PK/MLDSA.h>-#include <LibCrypto/PK/MLKEM.h>-#include <LibCrypto/PK/RSA.h>--// NB: Each parser reads one DER structure from the start of its input, and gives the number of bytes it took in-// `consumed`. A structure that is not in DER, or whose key OpenSSL cannot decode, is an error.-namespace Crypto::PK {--struct AlgorithmIdentifier {- ASN1::ObjectIdentifier identifier;- // The parameters, when they are an object identifier, such as the named curve of an EC key.- Optional<ASN1::ObjectIdentifier> ec_parameters;-};--// https://www.rfc-editor.org/rfc/rfc5280#section-4.1-struct SubjectPublicKeyInfo {- AlgorithmIdentifier algorithm;- ByteBuffer raw_key;- RSAPublicKey rsa;- ECPublicKey ec;-};--// https://www.rfc-editor.org/rfc/rfc5208#section-5-struct PrivateKeyInfo {- AlgorithmIdentifier algorithm;- ByteBuffer raw_key;- RSAPrivateKey rsa;- ECPrivateKey ec;- MLDSAPrivateKey mldsa;- MLKEMPrivateKey mlkem;-};--ErrorOr<SubjectPublicKeyInfo> parse_subject_public_key_info(ReadonlyBytes, size_t& consumed);-ErrorOr<PrivateKeyInfo> parse_private_key_info(ReadonlyBytes, size_t& consumed);-ErrorOr<ReadonlyBytes> parse_octet_string(ReadonlyBytes, size_t& consumed);--}diff --git a/Libraries/LibCrypto/PK/MLDSA.cpp b/Libraries/LibCrypto/PK/MLDSA.cppdeleted file mode 100644index 58c81b3a983..00000000000--- a/Libraries/LibCrypto/PK/MLDSA.cpp+++ /dev/null@@ -1,224 +0,0 @@-/*- * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Array.h>-#include <AK/Memory.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>--namespace Crypto::PK {--static constexpr MLDSASize sizes[] { MLDSA44, MLDSA65, MLDSA87 };--static char const* openssl_name(MLDSASize size)-{- switch (size) {- case MLDSA44:- return "ML-DSA-44";- case MLDSA65:- return "ML-DSA-65";- case MLDSA87:- return "ML-DSA-87";- }- 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 expanded_key_size(MLDSASize size)-{- switch (size) {- case MLDSA44:- return 2560;- case MLDSA65:- return 4032;- case MLDSA87:- return 4896;- }- VERIFY_NOT_REACHED();-}--static ErrorOr<MLDSASize> size_for_length(ReadonlyBytes bytes, size_t (*size_of)(MLDSASize))-{- for (auto size : sizes) {- if (size_of(size) == bytes.size())- return size;- }- return Error::from_string_literal("Invalid ML-DSA key length");-}--static ErrorOr<OpenSSL_SharedPKEY> key_from_octets(MLDSASize 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<MLDSAPublicKey> MLDSAPublicKey::from_bytes(ReadonlyBytes bytes)-{- 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()));-- if (!seed.is_empty()) {- 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));- }-- 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 MLDSAPrivateKey { move(key), move(public_key), size };-}--MLDSAPrivateKey MLDSAPrivateKey::in_expanded_key_form(MLDSASize size)-{- MLDSAPrivateKey private_key;- private_key.m_size = size;- return private_key;-}--ErrorOr<ReadonlyBytes> MLDSAPrivateKey::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_DSA_SEED, buffer.data(), buffer.size(), &size));- return buffer.trim(size);-}--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);-}--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");-- ASN1::Encoder encoder;- TRY(encoder.write<ReadonlyBytes>(seed, ASN1::Class::Context, static_cast<ASN1::Kind>(0)));-- return encoder.finish();-}--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)));-- 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<MLDSA::KeyPairType> MLDSA::generate_key_pair(MLDSASize size, ReadonlyBytes seed)-{- 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) };-}--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;-}--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");-- 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(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(ctx.ptr(), result.data(), &sign_size, message.data(), message.size()));-- return result;-}--ErrorOr<bool> mldsa_verify(MLDSASize size, MLDSAPublicKey const& public_key, ReadonlyBytes context, ReadonlyBytes message, ReadonlyBytes signature)-{- if (public_key.size() != size)- return Error::from_string_literal("The key is for a different ML-DSA parameter set");-- 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.data()));-- auto ret = EVP_PKEY_verify(ctx.ptr(), signature.data(), signature.size(), message.data(), message.size());- if (ret == 1)- return true;- if (ret == 0)- return false;- OPENSSL_TRY(ret);- VERIFY_NOT_REACHED();-}--}diff --git a/Libraries/LibCrypto/PK/MLDSA.h b/Libraries/LibCrypto/PK/MLDSA.hdeleted file mode 100644index 5cae105348a..00000000000--- a/Libraries/LibCrypto/PK/MLDSA.h+++ /dev/null@@ -1,99 +0,0 @@-/*- * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Error.h>-#include <LibCrypto/OpenSSL.h>--namespace Crypto::PK {--enum MLDSASize {- MLDSA44,- MLDSA65,- MLDSA87,-};--class MLDSAPublicKey {-public:- 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() = default;-- // 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;-- 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; }- ErrorOr<ByteBuffer> expanded_key() const;-- ErrorOr<ByteBuffer> export_as_der() const;-- EVP_PKEY* openssl_key() const { return m_key.ptr(); }--private:- 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;- MLDSASize m_size { MLDSA44 };-};--struct MLDSAKeyPair {- MLDSAPublicKey public_key;- MLDSAPrivateKey private_key;-};--class MLDSA {-public:- using KeyPairType = MLDSAKeyPair;-- static ErrorOr<KeyPairType> parse_mldsa_key(MLDSASize, ReadonlyBytes der);- static ErrorOr<KeyPairType> generate_key_pair(MLDSASize, ReadonlyBytes seed = {});-};--ErrorOr<ByteBuffer> mldsa_sign(MLDSASize, MLDSAPrivateKey const&, ReadonlyBytes context, ReadonlyBytes message);-ErrorOr<bool> mldsa_verify(MLDSASize, MLDSAPublicKey const&, ReadonlyBytes context, ReadonlyBytes message, ReadonlyBytes signature);--}diff --git a/Libraries/LibCrypto/PK/MLKEM.cpp b/Libraries/LibCrypto/PK/MLKEM.cppdeleted file mode 100644index 9b7e8ab6f19..00000000000--- a/Libraries/LibCrypto/PK/MLKEM.cpp+++ /dev/null@@ -1,226 +0,0 @@-/*- * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Array.h>-#include <AK/Memory.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>--namespace Crypto::PK {--static constexpr MLKEMSize sizes[] { MLKEMSize::MLKEM512, MLKEMSize::MLKEM768, MLKEMSize::MLKEM1024 };--static char const* openssl_name(MLKEMSize size)-{- switch (size) {- case MLKEMSize::MLKEM512:- return "ML-KEM-512";- case MLKEMSize::MLKEM768:- return "ML-KEM-768";- case MLKEMSize::MLKEM1024:- return "ML-KEM-1024";- }- VERIFY_NOT_REACHED();-}--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:- return 1632;- case MLKEMSize::MLKEM768:- return 2400;- case MLKEMSize::MLKEM1024:- return 3168;- }- 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.- 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>(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, expanded_key_size(size)));-- if (encoded_key.seed.is_empty())- 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)-{- 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, key.openssl_key(), nullptr)));-- OPENSSL_TRY(EVP_PKEY_encapsulate_init(ctx.ptr(), nullptr));-- size_t shared_key_size;- size_t ciphertext_length;- OPENSSL_TRY(EVP_PKEY_encapsulate(ctx.ptr(), nullptr, &ciphertext_length, nullptr, &shared_key_size));-- auto shared_key = TRY(ByteBuffer::create_uninitialized(shared_key_size));- auto ciphertext = TRY(ByteBuffer::create_uninitialized(ciphertext_length));-- OPENSSL_TRY(EVP_PKEY_encapsulate(ctx.ptr(), ciphertext.data(), &ciphertext_length, shared_key.data(), &shared_key_size));-- return MLKEMEncapsulation { move(shared_key), move(ciphertext) };-}--ErrorOr<ByteBuffer> MLKEM::decapsulate(MLKEMSize size, MLKEMPrivateKey const& key, ReadonlyBytes ciphertext)-{- 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, key.openssl_key(), nullptr)));-- OPENSSL_TRY(EVP_PKEY_decapsulate_init(ctx.ptr(), nullptr));-- size_t shared_key_size;- OPENSSL_TRY(EVP_PKEY_decapsulate(ctx.ptr(), nullptr, &shared_key_size, ciphertext.data(), ciphertext.size()));-- auto shared_key = TRY(ByteBuffer::create_uninitialized(shared_key_size));- OPENSSL_TRY(EVP_PKEY_decapsulate(ctx.ptr(), shared_key.data(), &shared_key_size, ciphertext.data(), ciphertext.size()));-- return shared_key;-}--}diff --git a/Libraries/LibCrypto/PK/MLKEM.h b/Libraries/LibCrypto/PK/MLKEM.hdeleted file mode 100644index f57982b165f..00000000000--- a/Libraries/LibCrypto/PK/MLKEM.h+++ /dev/null@@ -1,102 +0,0 @@-/*- * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Error.h>-#include <AK/Optional.h>-#include <LibCrypto/OpenSSL.h>--namespace Crypto::PK {--enum class MLKEMSize {- MLKEM512,- MLKEM768,- MLKEM1024,-};--class MLKEMPublicKey {-public:- 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() = default;-- // An empty seed generates a new key.- static ErrorOr<MLKEMPrivateKey> generate(MLKEMSize, 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 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; }- ErrorOr<ByteBuffer> expanded_key() const;-- ErrorOr<ByteBuffer> export_as_der() const;-- EVP_PKEY* openssl_key() const { return m_key.ptr(); }--private:- 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;- MLKEMSize m_size { MLKEMSize::MLKEM512 };-};--struct MLKEMKeyPair {- MLKEMPublicKey public_key;- MLKEMPrivateKey private_key;-};--struct MLKEMEncapsulation {- ByteBuffer shared_key;- ByteBuffer ciphertext;-};--class MLKEM {-public:- 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, MLKEMPublicKey const&);- static ErrorOr<ByteBuffer> decapsulate(MLKEMSize, MLKEMPrivateKey const&, ReadonlyBytes ciphertext);-};--}diff --git a/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.cpp b/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.cppdeleted file mode 100644index 25374bc111c..00000000000--- a/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.cpp+++ /dev/null@@ -1,85 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Memory.h>-#include <AK/ScopeGuard.h>-#include <LibCrypto/ASN1/DER.h>-#include <LibCrypto/PK/ModuleLatticePrivateKey.h>--namespace Crypto::PK {--enum class Choice {- Seed,- ExpandedKey,- Both,-};--static ErrorOr<ByteBuffer> encode(Choice choice, ReadonlyBytes seed, ReadonlyBytes expanded_key)-{- ASN1::Encoder encoder;- switch (choice) {- case Choice::Seed:- TRY(encoder.write<ReadonlyBytes>(seed, ASN1::Class::Context, static_cast<ASN1::Kind>(0)));- break;- case Choice::ExpandedKey:- TRY(encoder.write<ReadonlyBytes>(expanded_key));- break;- case Choice::Both:- TRY(encoder.write_constructed(ASN1::Class::Universal, ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {- TRY(encoder.write<ReadonlyBytes>(seed));- TRY(encoder.write<ReadonlyBytes>(expanded_key));- return {};- }));- break;- }- return encoder.finish();-}--// https://datatracker.ietf.org/doc/html/draft-ietf-lamps-kyber-certificates-11#autoid-7-// https://www.rfc-editor.org/rfc/rfc9881.html#section-6-ErrorOr<ModuleLatticePrivateKey> parse_module_lattice_private_key(ReadonlyBytes der, size_t seed_size, size_t expanded_key_size)-{- // PrivateKey ::= CHOICE {- // seed [0] IMPLICIT OCTET STRING (SIZE (seed_size)),- // expandedKey OCTET STRING (SIZE (expanded_key_size)),- // both SEQUENCE {- // seed OCTET STRING (SIZE (seed_size)),- // expandedKey OCTET STRING (SIZE (expanded_key_size))- // }- // }- // NB: The sizes are fixed, so each choice has a single DER layout. The input is a choice when it is the DER encoding- // of the bytes at that choice's places.- auto zero_seed = TRY(ByteBuffer::create_zeroed(seed_size));- auto zero_expanded_key = TRY(ByteBuffer::create_zeroed(expanded_key_size));- auto expanded_key_header_size = TRY(encode(Choice::ExpandedKey, {}, zero_expanded_key)).size() - expanded_key_size;-- for (auto choice : { Choice::Seed, Choice::ExpandedKey, Choice::Both }) {- if (TRY(encode(choice, zero_seed, zero_expanded_key)).size() != der.size())- continue;-- ModuleLatticePrivateKey key;- switch (choice) {- case Choice::Seed:- key.seed = der.slice(der.size() - seed_size);- break;- case Choice::ExpandedKey:- key.expanded_key = der.slice(der.size() - expanded_key_size);- break;- case Choice::Both:- key.expanded_key = der.slice(der.size() - expanded_key_size);- key.seed = der.slice(der.size() - expanded_key_size - expanded_key_header_size - seed_size, seed_size);- break;- }-- auto encoded = TRY(encode(choice, key.seed, key.expanded_key));- ScopeGuard const clear_encoded = [&] { secure_zero(encoded.data(), encoded.size()); };- if (encoded == der)- return key;- }- return Error::from_string_literal("Invalid module-lattice private key");-}--}diff --git a/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.h b/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.hdeleted file mode 100644index 373f36844bb..00000000000--- a/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.h+++ /dev/null@@ -1,21 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Error.h>-#include <AK/Span.h>--namespace Crypto::PK {--struct ModuleLatticePrivateKey {- ReadonlyBytes seed;- ReadonlyBytes expanded_key;-};--ErrorOr<ModuleLatticePrivateKey> parse_module_lattice_private_key(ReadonlyBytes der, size_t seed_size, size_t expanded_key_size);--}diff --git a/Libraries/LibCrypto/PK/PK.cpp b/Libraries/LibCrypto/PK/PK.cppdeleted file mode 100644index da2c45f0328..00000000000--- a/Libraries/LibCrypto/PK/PK.cpp+++ /dev/null@@ -1,49 +0,0 @@-/*- * Copyright (c) 2020, Ali Mohammad Pur <[email protected]>- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/ASN1/DER.h>-#include <LibCrypto/PK/PK.h>--namespace Crypto::PK {--static ErrorOr<void> write_algorithm_identifier(ASN1::Encoder& encoder, Span<u32 const> algorithm, AlgorithmParameters const& parameters)-{- return encoder.write_constructed(ASN1::Class::Universal, ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {- TRY(encoder.write(algorithm));- TRY(parameters.visit(- [](Empty) -> ErrorOr<void> { return {}; },- [&](auto const& value) { return encoder.write(value); }));- return {};- });-}--ErrorOr<ByteBuffer> wrap_in_private_key_info(ReadonlyBytes private_key, Span<u32 const> algorithm, AlgorithmParameters parameters)-{- ASN1::Encoder encoder;- TRY(encoder.write_constructed(ASN1::Class::Universal, ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {- TRY(encoder.write(0x00u)); // version- TRY(write_algorithm_identifier(encoder, algorithm, parameters));- TRY(encoder.write(private_key));- return {};- }));-- return encoder.finish();-}--ErrorOr<ByteBuffer> wrap_in_subject_public_key_info(ReadonlyBytes public_key, Span<u32 const> algorithm, AlgorithmParameters parameters)-{- ASN1::Encoder encoder;- TRY(encoder.write_constructed(ASN1::Class::Universal, ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {- TRY(write_algorithm_identifier(encoder, algorithm, parameters));- TRY(encoder.write(ASN1::BitStringView(public_key, 0)));- return {};- }));-- return encoder.finish();-}--}diff --git a/Libraries/LibCrypto/PK/PK.h b/Libraries/LibCrypto/PK/PK.hdeleted file mode 100644index e3c76311627..00000000000--- a/Libraries/LibCrypto/PK/PK.h+++ /dev/null@@ -1,24 +0,0 @@-/*- * Copyright (c) 2020, Ali Mohammad Pur <[email protected]>- * Copyright (c) 2024, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/ByteBuffer.h>-#include <AK/Variant.h>--namespace Crypto::PK {--// The parameters of an AlgorithmIdentifier: absent, NULL, or a named curve.-using AlgorithmParameters = Variant<Empty, nullptr_t, Span<u32 const>>;--// https://www.rfc-editor.org/rfc/rfc5208#section-5-ErrorOr<ByteBuffer> wrap_in_private_key_info(ReadonlyBytes private_key, Span<u32 const> algorithm, AlgorithmParameters = {});--// https://www.rfc-editor.org/rfc/rfc5280#section-4.1-ErrorOr<ByteBuffer> wrap_in_subject_public_key_info(ReadonlyBytes public_key, Span<u32 const> algorithm, AlgorithmParameters = {});--}diff --git a/Libraries/LibCrypto/PK/RSA.cpp b/Libraries/LibCrypto/PK/RSA.cppindex c19445c625e..fe47b8a90bf 100644--- a/Libraries/LibCrypto/PK/RSA.cpp+++ b/Libraries/LibCrypto/PK/RSA.cpp@@ -7,8 +7,8 @@#include <AK/ByteBuffer.h>#include <AK/Memory.h>-#include <AK/NumericLimits.h>#include <AK/ScopeGuard.h>+#include <AK/Vector.h>#include <LibCrypto/OpenSSL.h>#include <LibCrypto/PK/RSA.h>@@ -16,22 +16,9 @@#include <openssl/core_names.h>#include <openssl/evp.h>#include <openssl/param_build.h>-#include <openssl/rsa.h>-#include <openssl/x509.h>namespace Crypto::PK {-static ErrorOr<ByteBuffer> integer_parameter(EVP_PKEY* key, char const* name)-{- BIGNUM* value = nullptr;- OPENSSL_TRY(EVP_PKEY_get_bn_param(key, name, &value));- ScopeGuard const free_value = [&] { BN_clear_free(value); };-- auto bytes = TRY(ByteBuffer::create_uninitialized(BN_num_bytes(value)));- BN_bn2bin(value, bytes.data());- return bytes;-}-// NB: The builder reads each BIGNUM when it builds the parameters, so the BIGNUMs must outlive the builder.class ParameterBuilder {AK_MAKE_NONCOPYABLE(ParameterBuilder);@@ -59,14 +46,6 @@ public:return {};}- ErrorOr<void> push_size(char const* name, size_t value)- {- if (!m_builder)- m_builder = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());- OPENSSL_TRY(OSSL_PARAM_BLD_push_size_t(m_builder, name, value));- return {};- }-OSSL_PARAM_BLD* ptr() { return m_builder; }private:@@ -103,16 +82,6 @@ static ErrorOr<bool> public_exponent_is_valid(EVP_PKEY* key)return BN_is_odd(e) && !BN_is_one(e) && BN_cmp(e, n) < 0;}-static ErrorOr<ByteBuffer> export_type_specific_der(EVP_PKEY* key, bool is_private)-{- u8* der = nullptr;- auto size = is_private ? i2d_PrivateKey(key, &der) : i2d_PublicKey(key, &der);- if (size <= 0)- return Error::from_string_literal("Failed to encode the RSA key");- ScopeGuard const free_der = [&] { OPENSSL_clear_free(der, size); };- return ByteBuffer::copy(der, size);-}-RSAPublicKey::RSAPublicKey(OpenSSL_SharedPKEY key): m_key(move(key)), m_length(EVP_PKEY_get_size(m_key.ptr()))@@ -127,21 +96,6 @@ ErrorOr<RSAPublicKey> RSAPublicKey::from_components(ReadonlyBytes modulus, Readoreturn RSAPublicKey { TRY(key_from_parameters(EVP_PKEY_PUBLIC_KEY, builder)) };}-size_t RSAPublicKey::modulus_bits() const-{- return EVP_PKEY_get_bits(m_key.ptr());-}--ErrorOr<ByteBuffer> RSAPublicKey::modulus() const-{- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_N);-}--ErrorOr<ByteBuffer> RSAPublicKey::public_exponent() const-{- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_E);-}-ErrorOr<bool> RSAPublicKey::is_valid() const{if (!TRY(public_exponent_is_valid(m_key.ptr())))@@ -151,220 +105,6 @@ ErrorOr<bool> RSAPublicKey::is_valid() constreturn EVP_PKEY_public_check(ctx.ptr()) == 1;}-// https://www.rfc-editor.org/rfc/rfc8017#appendix-A.1.1-ErrorOr<ByteBuffer> RSAPublicKey::export_as_der() const-{- return export_type_specific_der(m_key.ptr(), false);-}--RSAPrivateKey::RSAPrivateKey(OpenSSL_SharedPKEY key, bool has_crt_components)- : m_key(move(key))- , m_length(EVP_PKEY_get_size(m_key.ptr()))- , m_has_crt_components(has_crt_components)-{-}--ErrorOr<RSAPrivateKey> RSAPrivateKey::from_components(ReadonlyBytes modulus, ReadonlyBytes public_exponent, ReadonlyBytes private_exponent, Optional<RSACRTComponents> crt_components)-{- ParameterBuilder builder;- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_N, modulus, false));- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_E, public_exponent, false));- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_D, private_exponent, true));- if (crt_components.has_value()) {- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_FACTOR1, crt_components->prime1, true));- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_FACTOR2, crt_components->prime2, true));- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_EXPONENT1, crt_components->exponent1, true));- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_EXPONENT2, crt_components->exponent2, true));- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, crt_components->coefficient, true));- }- return RSAPrivateKey { TRY(key_from_parameters(EVP_PKEY_KEYPAIR, builder)), crt_components.has_value() };-}--RSAPrivateKey RSAPrivateKey::from_openssl_key(OpenSSL_SharedPKEY key)-{- BIGNUM* prime = nullptr;- bool has_crt_components = EVP_PKEY_get_bn_param(key.ptr(), OSSL_PKEY_PARAM_RSA_FACTOR1, &prime) == 1;- BN_clear_free(prime);- return RSAPrivateKey { move(key), has_crt_components };-}--size_t RSAPrivateKey::modulus_bits() const-{- return EVP_PKEY_get_bits(m_key.ptr());-}--ErrorOr<ByteBuffer> RSAPrivateKey::component(Component component) const-{- switch (component) {- case Component::Modulus:- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_N);- case Component::PublicExponent:- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_E);- case Component::PrivateExponent:- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_D);- default:- break;- }-- if (!m_has_crt_components)- return ByteBuffer {};-- switch (component) {- case Component::Prime1:- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_FACTOR1);- case Component::Prime2:- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_FACTOR2);- case Component::Exponent1:- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_EXPONENT1);- case Component::Exponent2:- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_EXPONENT2);- case Component::Coefficient:- return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_RSA_COEFFICIENT1);- default:- VERIFY_NOT_REACHED();- }-}--ErrorOr<RSAPublicKey> RSAPrivateKey::public_key() const-{- auto modulus = TRY(component(Component::Modulus));- auto public_exponent = TRY(component(Component::PublicExponent));- return RSAPublicKey::from_components(modulus, public_exponent);-}--ErrorOr<bool> RSAPrivateKey::is_valid() const-{- if (!TRY(public_exponent_is_valid(m_key.ptr())))- return false;-- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, m_key.ptr(), nullptr)));- if (EVP_PKEY_public_check(ctx.ptr()) != 1 || EVP_PKEY_private_check(ctx.ptr()) != 1)- return false;-- // NB: The pairwise check needs the prime factors, which a key of only n, e and d does not have.- if (!m_has_crt_components)- return true;- return EVP_PKEY_pairwise_check(ctx.ptr()) == 1;-}--// https://www.rfc-editor.org/rfc/rfc8017#appendix-A.1.2-ErrorOr<ByteBuffer> RSAPrivateKey::export_as_der() const-{- if (!m_has_crt_components)- return Error::from_string_literal("Cannot export private key without prime factors");- return export_type_specific_der(m_key.ptr(), true);-}--ErrorOr<void> RSA::validate_key_generation_parameters(size_t bits)-{- // OpenSSL refuses to generate keys with shorter moduli.- static constexpr size_t minimum_modulus_length = 512;-- if (bits < minimum_modulus_length)- return Error::from_string_literal("RSA modulus length must be at least 512 bits");-- if (bits > OPENSSL_RSA_MAX_MODULUS_BITS)- return Error::from_string_literal("RSA modulus length must be at most 16384 bits");-- return {};-}--ErrorOr<RSA::KeyPairType> RSA::generate_key_pair(size_t bits, ReadonlyBytes public_exponent)-{- TRY(validate_key_generation_parameters(bits));-- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr)));- OPENSSL_TRY(EVP_PKEY_keygen_init(ctx.ptr()));-- ParameterBuilder builder;- TRY(builder.push_size(OSSL_PKEY_PARAM_RSA_BITS, bits));- TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_E, public_exponent, false));-- auto* params = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_to_param(builder.ptr()));- ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };- OPENSSL_TRY(EVP_PKEY_CTX_set_params(ctx.ptr(), params));-- EVP_PKEY* key = nullptr;- OPENSSL_TRY(EVP_PKEY_generate(ctx.ptr(), &key));-- RSAPrivateKey private_key { OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(key)) }, true };- auto public_key = TRY(private_key.public_key());- return KeyPairType { move(public_key), move(private_key) };-}--ErrorOr<RSA::KeyPairType> RSA::generate_key_pair(size_t bits)-{- static constexpr u8 f4[] { 0x01, 0x00, 0x01 };- return generate_key_pair(bits, f4);-}--static ErrorOr<Array<OSSL_PARAM, 5>> oaep_parameters(Hash::HashKind hash_kind, ReadonlyBytes const& label)-{- auto* hash_name = const_cast<char*>(TRY(Hash::openssl_digest_name(hash_kind)));- Array<OSSL_PARAM, 5> params {- OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_PAD_MODE, const_cast<char*>(OSSL_PKEY_RSA_PAD_MODE_OAEP), 0),- OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, hash_name, 0),- OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST, hash_name, 0),- OSSL_PARAM_construct_end(),- OSSL_PARAM_construct_end(),- };- // NB: OpenSSL copies the label.- if (!label.is_empty())- params[3] = OSSL_PARAM_construct_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, const_cast<u8*>(label.data()), label.size());- return params;-}--ErrorOr<ByteBuffer> rsa_oaep_encrypt(RSAPublicKey const& public_key, Hash::HashKind hash_kind, ReadonlyBytes label, ReadonlyBytes plaintext)-{- auto* key = public_key.openssl_key();- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key, nullptr)));-- auto params = TRY(oaep_parameters(hash_kind, label));- OPENSSL_TRY(EVP_PKEY_encrypt_init_ex(ctx.ptr(), params.data()));-- size_t out_size = 0;- OPENSSL_TRY(EVP_PKEY_encrypt(ctx.ptr(), nullptr, &out_size, plaintext.data(), plaintext.size()));-- auto out = TRY(ByteBuffer::create_uninitialized(out_size));- OPENSSL_TRY(EVP_PKEY_encrypt(ctx.ptr(), out.data(), &out_size, plaintext.data(), plaintext.size()));- return out.slice(0, out_size);-}--ErrorOr<ByteBuffer> rsa_oaep_decrypt(RSAPrivateKey const& private_key, Hash::HashKind hash_kind, ReadonlyBytes label, ReadonlyBytes ciphertext)-{- if (ciphertext.size() != private_key.length())- return Error::from_string_literal("RSA ciphertext has an invalid length");-- auto* key = private_key.openssl_key();- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key, nullptr)));-- auto params = TRY(oaep_parameters(hash_kind, label));- OPENSSL_TRY(EVP_PKEY_decrypt_init_ex(ctx.ptr(), params.data()));-- size_t out_size = 0;- OPENSSL_TRY(EVP_PKEY_decrypt(ctx.ptr(), nullptr, &out_size, ciphertext.data(), ciphertext.size()));-- auto out = TRY(ByteBuffer::create_uninitialized(out_size));- ScopeGuard const clear_out = [&] { secure_zero(out.data(), out.size()); };- OPENSSL_TRY(EVP_PKEY_decrypt(ctx.ptr(), out.data(), &out_size, ciphertext.data(), ciphertext.size()));- return ByteBuffer::copy(out.bytes().trim(out_size));-}--static ErrorOr<ByteBuffer> sign(RSAPrivateKey const& private_key, Hash::HashKind hash_kind, OSSL_PARAM const* params, ReadonlyBytes message)-{- auto* key = private_key.openssl_key();- auto ctx = TRY(OpenSSL_MD_CTX::create());-- OPENSSL_TRY(EVP_DigestSignInit_ex(ctx.ptr(), nullptr, TRY(Hash::openssl_digest_name(hash_kind)), nullptr, nullptr, key, params));-- size_t signature_size = 0;- OPENSSL_TRY(EVP_DigestSign(ctx.ptr(), nullptr, &signature_size, message.data(), message.size()));-- auto signature = TRY(ByteBuffer::create_uninitialized(signature_size));- OPENSSL_TRY(EVP_DigestSign(ctx.ptr(), signature.data(), &signature_size, message.data(), message.size()));- return signature.slice(0, signature_size);-}-static ErrorOr<bool> verify(RSAPublicKey const& public_key, Hash::HashKind hash_kind, OSSL_PARAM const* params, ReadonlyBytes message, ReadonlyBytes signature){if (signature.size() != public_key.length())@@ -388,54 +128,11 @@ static ErrorOr<bool> verify(RSAPublicKey const& public_key, Hash::HashKind hash_VERIFY_NOT_REACHED();}-// NB: OpenSSL takes the salt length as an int and gives negative values special meanings, such as salt length-// auto-detection, so a length that does not fit in an int must never reach it. No RSA key is large enough-// for such a salt.-static bool salt_length_fits_in_int(u32 salt_length)-{- return salt_length <= static_cast<u32>(NumericLimits<int>::max());-}--static ErrorOr<Array<OSSL_PARAM, 4>> pss_parameters(Hash::HashKind hash_kind, int& salt_length)-{- return Array<OSSL_PARAM, 4> {- OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, const_cast<char*>(OSSL_PKEY_RSA_PAD_MODE_PSS), 0),- OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_MGF1_DIGEST, const_cast<char*>(TRY(Hash::openssl_digest_name(hash_kind))), 0),- OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_PSS_SALTLEN, &salt_length),- OSSL_PARAM_construct_end(),- };-}--ErrorOr<ByteBuffer> rsa_pss_sign(RSAPrivateKey const& private_key, Hash::HashKind hash_kind, u32 salt_length, ReadonlyBytes message)-{- if (!salt_length_fits_in_int(salt_length))- return Error::from_string_literal("Salt length is too large");-- auto salt_length_int = static_cast<int>(salt_length);- auto params = TRY(pss_parameters(hash_kind, salt_length_int));- return sign(private_key, hash_kind, params.data(), message);-}--ErrorOr<bool> rsa_pss_verify(RSAPublicKey const& public_key, Hash::HashKind hash_kind, u32 salt_length, ReadonlyBytes message, ReadonlyBytes signature)-{- if (!salt_length_fits_in_int(salt_length))- return false;-- auto salt_length_int = static_cast<int>(salt_length);- auto params = TRY(pss_parameters(hash_kind, salt_length_int));- return verify(public_key, hash_kind, params.data(), message, signature);-}-static OSSL_PARAM const pkcs1_parameters[] {OSSL_PARAM_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, const_cast<char*>(OSSL_PKEY_RSA_PAD_MODE_PKCSV15), sizeof(OSSL_PKEY_RSA_PAD_MODE_PKCSV15) - 1),OSSL_PARAM_END,};-ErrorOr<ByteBuffer> rsa_pkcs1_sign(RSAPrivateKey const& private_key, Hash::HashKind hash_kind, ReadonlyBytes message)-{- return sign(private_key, hash_kind, pkcs1_parameters, message);-}-ErrorOr<bool> rsa_pkcs1_verify(RSAPublicKey const& public_key, Hash::HashKind hash_kind, ReadonlyBytes message, ReadonlyBytes signature){return verify(public_key, hash_kind, pkcs1_parameters, message, signature);diff --git a/Libraries/LibCrypto/PK/RSA.h b/Libraries/LibCrypto/PK/RSA.hindex 46110ed9b83..fc39bb4b3af 100644--- a/Libraries/LibCrypto/PK/RSA.h+++ b/Libraries/LibCrypto/PK/RSA.h@@ -9,9 +9,6 @@#pragma once#include <AK/ByteBuffer.h>-#include <AK/Optional.h>-#include <AK/StringView.h>-#include <AK/Vector.h>#include <LibCrypto/Hash/Hash.h>#include <LibCrypto/OpenSSL.h>@@ -23,18 +20,11 @@ public:RSAPublicKey() = default;static ErrorOr<RSAPublicKey> from_components(ReadonlyBytes modulus, ReadonlyBytes public_exponent);- static RSAPublicKey from_openssl_key(OpenSSL_SharedPKEY key) { return RSAPublicKey { move(key) }; }size_t length() const { return m_length; }- size_t modulus_bits() const;-- ErrorOr<ByteBuffer> modulus() const;- ErrorOr<ByteBuffer> public_exponent() const;ErrorOr<bool> is_valid() const;- ErrorOr<ByteBuffer> export_as_der() const;-EVP_PKEY* openssl_key() const { return m_key.ptr(); }private:@@ -44,79 +34,6 @@ private:size_t m_length { 0 };};-struct RSACRTComponents {- ReadonlyBytes prime1;- ReadonlyBytes prime2;- ReadonlyBytes exponent1;- ReadonlyBytes exponent2;- ReadonlyBytes coefficient;-};--class RSAPrivateKey {-public:- // NB: The order matches libcrypto_rust's RsaJwkInteger.- enum class Component : u8 {- Modulus,- PublicExponent,- PrivateExponent,- Prime1,- Prime2,- Exponent1,- Exponent2,- Coefficient,- };-- RSAPrivateKey() = default;-- static ErrorOr<RSAPrivateKey> from_components(ReadonlyBytes modulus, ReadonlyBytes public_exponent, ReadonlyBytes private_exponent, Optional<RSACRTComponents>);- static RSAPrivateKey from_openssl_key(OpenSSL_SharedPKEY);-- size_t length() const { return m_length; }- size_t modulus_bits() const;- bool has_crt_components() const { return m_has_crt_components; }-- // A CRT component of a key without them is empty.- ErrorOr<ByteBuffer> component(Component) const;-- ErrorOr<RSAPublicKey> public_key() const;-- ErrorOr<bool> is_valid() const;-- ErrorOr<ByteBuffer> export_as_der() const;-- EVP_PKEY* openssl_key() const { return m_key.ptr(); }--private:- friend class RSA;-- RSAPrivateKey(OpenSSL_SharedPKEY key, bool has_crt_components);-- OpenSSL_SharedPKEY m_key;- size_t m_length { 0 };- bool m_has_crt_components { false };-};--struct RSAKeyPair {- RSAPublicKey public_key;- RSAPrivateKey private_key;-};--class RSA {-public:- using KeyPairType = RSAKeyPair;-- static ErrorOr<void> validate_key_generation_parameters(size_t bits);- static ErrorOr<KeyPairType> generate_key_pair(size_t bits, ReadonlyBytes public_exponent);- static ErrorOr<KeyPairType> generate_key_pair(size_t bits);-};--ErrorOr<ByteBuffer> rsa_oaep_encrypt(RSAPublicKey const&, Hash::HashKind, ReadonlyBytes label, ReadonlyBytes plaintext);-ErrorOr<ByteBuffer> rsa_oaep_decrypt(RSAPrivateKey const&, Hash::HashKind, ReadonlyBytes label, ReadonlyBytes ciphertext);--ErrorOr<ByteBuffer> rsa_pss_sign(RSAPrivateKey const&, Hash::HashKind, u32 salt_length, ReadonlyBytes message);-ErrorOr<bool> rsa_pss_verify(RSAPublicKey const&, Hash::HashKind, u32 salt_length, ReadonlyBytes message, ReadonlyBytes signature);--ErrorOr<ByteBuffer> rsa_pkcs1_sign(RSAPrivateKey const&, Hash::HashKind, ReadonlyBytes message);ErrorOr<bool> rsa_pkcs1_verify(RSAPublicKey const&, Hash::HashKind, ReadonlyBytes message, ReadonlyBytes signature);}diff --git a/Libraries/LibCrypto/RustBindings.cpp b/Libraries/LibCrypto/RustBindings.cppdeleted file mode 100644index db298e0bd81..00000000000--- a/Libraries/LibCrypto/RustBindings.cpp+++ /dev/null@@ -1,1112 +0,0 @@-/*- * 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/AnyOf.h>-#include <AK/Array.h>-#include <AK/Memory.h>-#include <AK/Random.h>-#include <AK/ScopeGuard.h>-#include <AK/Utf16String.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/Cipher/AES.h>-#include <LibCrypto/Cipher/ChaCha.h>-#include <LibCrypto/Curves/EdwardsCurve.h>-#include <LibCrypto/Hash/Argon2.h>-#include <LibCrypto/Hash/HKDF.h>-#include <LibCrypto/Hash/Hash.h>-#include <LibCrypto/Hash/PBKDF2.h>-#include <LibCrypto/Hash/SHAKE.h>-#include <LibCrypto/KeyHandle.h>-#include <LibCrypto/PK/EC.h>-#include <LibCrypto/PK/KeyInfo.h>-#include <LibCrypto/PK/MLDSA.h>-#include <LibCrypto/PK/MLKEM.h>-#include <LibCrypto/PK/PK.h>-#include <LibCrypto/PK/RSA.h>--namespace Crypto {--template<typename T>-struct Asn1Storage final {- AK_ALLOC_WITH_KMALLOC;-- T value;-};--using SubjectPublicKeyStorage = Asn1Storage<PK::SubjectPublicKeyInfo>;-using PrivateKeyStorage = Asn1Storage<PK::PrivateKeyInfo>;-using OctetStringStorage = Asn1Storage<ReadonlyBytes>;--extern "C" {-using ReceiveEncodedBytes = void (*)(void*, ReadonlyBytes);-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;-}--FlatPtr crypto_decode_asn1_structure(ReadonlyBytes data, Asn1Structure structure, void* out, bool* all_consumed)-{- size_t consumed = 0;- switch (structure) {- case Asn1Structure::SubjectPublicKeyInfo: {- auto subject_public_key = ::Crypto::PK::parse_subject_public_key_info(data, consumed);- 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::PK::parse_private_key_info(data, consumed);- 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 = ::Crypto::PK::parse_octet_string(data, consumed);- 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 = consumed == data.size();- 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_modulus_length(u32);-bool crypto_rsa_generate_key_pair(u32, ReadonlyBytes, KeyHandle**, KeyHandle**);-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);- auto* storage = static_cast<PrivateKeyStorage*>(key_info);- secure_zero(storage->value.raw_key.data(), storage->value.raw_key.size());- delete storage;-}--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_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, 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;-}--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_bits();- return public_key.public_exponent();- },- [&](::Crypto::PK::RSAPrivateKey const& private_key) {- *modulus_length = private_key.modulus_bits();- return private_key.component(::Crypto::PK::RSAPrivateKey::Component::PublicExponent);- },- [](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 key = [&]() -> ErrorOr<KeyHandle> {- if (!is_private)- return TRY(::Crypto::PK::RSAPublicKey::from_components(components[0], components[1]));-- // NB: A JWK of a key without CRT components may carry them empty.- auto has_crt_components = components.size() == 8 && any_of(components.slice(3), [](auto const& component) { return !component.is_empty(); });- Optional<::Crypto::PK::RSACRTComponents> crt_components;- if (has_crt_components)- crt_components = ::Crypto::PK::RSACRTComponents { components[3], components[4], components[5], components[6], components[7] };- return TRY(::Crypto::PK::RSAPrivateKey::from_components(components[0], components[1], components[2], crt_components));- }();- if (key.is_error())- return nullptr;- return new KeyHandle(key.release_value());-}--bool crypto_rsa_export_der(KeyHandle const* key, bool is_public, void* state, ReceiveEncodedBytes receive)-{- auto result = [&]() -> ErrorOr<ByteBuffer> {- if (is_public) {- auto public_key = TRY(key->get<::Crypto::PK::RSAPublicKey>().export_as_der());- return ::Crypto::PK::wrap_in_subject_public_key_info(public_key, ::Crypto::ASN1::rsa_encryption_oid, nullptr);- }- auto private_key = TRY(key->get<::Crypto::PK::RSAPrivateKey>().export_as_der());- ScopeGuard const clear_private_key = [&] { secure_zero(private_key.data(), private_key.size()); };- return ::Crypto::PK::wrap_in_private_key_info(private_key, ::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 integer = key->visit(- [&](::Crypto::PK::RSAPublicKey const& public_key) {- VERIFY(component < 2);- return component == 0 ? public_key.modulus() : public_key.public_exponent();- },- [&](::Crypto::PK::RSAPrivateKey const& private_key) {- VERIFY(component <= to_underlying(::Crypto::PK::RSAPrivateKey::Component::Coefficient));- return private_key.component(static_cast<::Crypto::PK::RSAPrivateKey::Component>(component));- },- [](auto const&) -> ErrorOr<ByteBuffer> { VERIFY_NOT_REACHED(); });- if (integer.is_error())- return false;- receive(state, integer.value());- secure_zero(integer.value().data(), integer.value().size());- 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 = encrypt- ? ::Crypto::PK::rsa_oaep_encrypt(key->get<::Crypto::PK::RSAPublicKey>(), hash_kind, label, input)- : ::Crypto::PK::rsa_oaep_decrypt(key->get<::Crypto::PK::RSAPrivateKey>(), hash_kind, label, input);- if (result.is_error())- return false;- receive(state, result.value());- if (!encrypt)- secure_zero(result.value().data(), result.value().size());- return true;-}--bool crypto_rsa_pss_sign(::Crypto::Hash::HashKind hash_kind, KeyHandle const* key, u32 salt_length, ReadonlyBytes message, void* state, ReceiveEncodedBytes receive)-{- auto result = ::Crypto::PK::rsa_pss_sign(key->get<::Crypto::PK::RSAPrivateKey>(), hash_kind, salt_length, 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)-{- auto result = ::Crypto::PK::rsa_pss_verify(key->get<::Crypto::PK::RSAPublicKey>(), hash_kind, salt_length, 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)-{- auto result = ::Crypto::PK::rsa_pkcs1_sign(key->get<::Crypto::PK::RSAPrivateKey>(), hash_kind, 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)-{- auto result = ::Crypto::PK::rsa_pkcs1_verify(key->get<::Crypto::PK::RSAPublicKey>(), hash_kind, 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())- 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) == 2);-static_assert(to_underlying(::Crypto::Hash::HashKind::SHA256) == 3);-static_assert(to_underlying(::Crypto::Hash::HashKind::SHA384) == 4);-static_assert(to_underlying(::Crypto::Hash::HashKind::SHA512) == 5);-static_assert(to_underlying(::Crypto::Hash::HashKind::SHA3_256) == 6);-static_assert(to_underlying(::Crypto::Hash::HashKind::SHA3_384) == 7);-static_assert(to_underlying(::Crypto::Hash::HashKind::SHA3_512) == 8);--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)-{- auto digest = ::Crypto::Hash::digest(hash_kind, data);- receive(state, digest.bytes());- return true;-}--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 size_t ec_scalar_size(EcCurve curve)-{- switch (curve) {- case EcCurve::P256:- return 32;- case EcCurve::P384:- return 48;- case EcCurve::P521:- return 66;- }- 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**);-FlatPtr crypto_ec_sign(EcCurve, KeyHandle const*, ReadonlyBytes, void*, void*, ReceiveEncodedBytes);-FlatPtr crypto_ec_verify(EcCurve, KeyHandle const*, ReadonlyBytes, ReadonlyBytes, ReadonlyBytes, bool*);-size_t crypto_ec_public_key_scalar_size(KeyHandle const*);-FlatPtr crypto_ec_compute_coordinate(EcCurve, KeyHandle const*, KeyHandle const*, 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, 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(KeyHandle const*, void*, void*, ReceiveEncodedBytes);-bool crypto_ec_export_private_scalar(KeyHandle const*, void*, ReceiveEncodedBytes);-}--bool crypto_ec_generate_key_pair(EcCurve curve, KeyHandle** out_public_key, KeyHandle** out_private_key)-{- auto private_key = ::Crypto::PK::ECPrivateKey::generate(ec_scalar_size(curve));- if (private_key.is_error())- return false;- *out_public_key = new KeyHandle(*private_key.value().public_key());- *out_private_key = new KeyHandle(private_key.release_value());- return true;-}--FlatPtr crypto_ec_sign(EcCurve curve, KeyHandle const* key, ReadonlyBytes digest, void* r, void* s, ReceiveEncodedBytes receive)-{- auto const& private_key = key->get<::Crypto::PK::ECPrivateKey>();- if (private_key.scalar_size() != ec_scalar_size(curve))- return Utf16String::from_utf8("The key is on a different curve"sv).into_raw();- auto signature = ::Crypto::PK::ecdsa_sign(private_key, digest);- if (signature.is_error())- return Utf16String::formatted("{}", signature.error()).into_raw();- receive(r, signature.value().r);- receive(s, signature.value().s);- return 0;-}--FlatPtr crypto_ec_verify(EcCurve curve, KeyHandle const* key, ReadonlyBytes digest, ReadonlyBytes r, ReadonlyBytes s, bool* verified)-{- auto const& public_key = key->get<::Crypto::PK::ECPublicKey>();- if (public_key.scalar_size() != ec_scalar_size(curve)) {- *verified = false;- return 0;- }- auto result = ::Crypto::PK::ecdsa_verify(public_key, digest, r, s);- 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();-}--FlatPtr crypto_ec_compute_coordinate(EcCurve curve, KeyHandle const* key, KeyHandle const* public_key, void* state, ReceiveEncodedBytes receive)-{- auto const& private_key = key->get<::Crypto::PK::ECPrivateKey>();- if (private_key.scalar_size() != ec_scalar_size(curve))- return Utf16String::from_utf8("The key is on a different curve"sv).into_raw();- auto secret = ::Crypto::PK::ecdh_derive(private_key, public_key->get<::Crypto::PK::ECPublicKey>());- if (secret.is_error())- return Utf16String::formatted("{}", secret.error()).into_raw();- receive(state, secret.value());- secure_zero(secret.value().data(), secret.value().size());- return 0;-}--static ::Crypto::PK::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, OptionalBytes d)-{- auto public_key = ::Crypto::PK::ECPublicKey::from_coordinates(x, y);- if (public_key.is_error())- return nullptr;- if (!d.has_value)- return new KeyHandle(public_key.release_value());- auto private_key = ::Crypto::PK::ECPrivateKey::from_scalar(d.bytes, {}, public_key.release_value());- if (private_key.is_error())- return nullptr;- return new KeyHandle(private_key.release_value());-}--KeyHandle* crypto_ec_parse_raw_public_key(ReadonlyBytes data)-{- auto public_key = ::Crypto::PK::ECPublicKey::from_octets(data);- if (public_key.is_error())- return nullptr;- return new KeyHandle(public_key.release_value());-}--// NB: Every EC key is a valid key for its own curve, since building it checks that.-bool crypto_ec_key_is_valid(EcCurve curve, KeyHandle const* key, bool* valid)-{- auto scalar_size = key->visit(- [](::Crypto::PK::ECPublicKey const& public_key) { return public_key.scalar_size(); },- [](::Crypto::PK::ECPrivateKey const& private_key) { return private_key.scalar_size(); },- [](auto const&) -> size_t { VERIFY_NOT_REACHED(); });- *valid = scalar_size == ec_scalar_size(curve);- 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);- }- auto private_key = TRY(key->get<::Crypto::PK::ECPrivateKey>().export_as_der());- ScopeGuard const clear_private_key = [&] { secure_zero(private_key.data(), private_key.size()); };- return ::Crypto::PK::wrap_in_private_key_info(private_key, ::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(KeyHandle const* key, void* x, void* y, ReceiveEncodedBytes receive)-{- auto result = [&]() -> ErrorOr<void> {- auto public_key = TRY(key->visit(- [](::Crypto::PK::ECPublicKey const& public_key) -> ErrorOr<::Crypto::PK::ECPublicKey> { return public_key; },- [](::Crypto::PK::ECPrivateKey const& private_key) { return private_key.derive_public_key(); },- [](auto const&) -> ErrorOr<::Crypto::PK::ECPublicKey> { VERIFY_NOT_REACHED(); }));- 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 {};- }();- 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();- if (result.is_error())- return false;- receive(state, result.value());- secure_zero(result.value().data(), result.value().size());- return true;-}--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;-}--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(key, oid);- ::Crypto::ASN1::Encoder encoder;- TRY(encoder.write(key));- auto private_key = encoder.finish();- ScopeGuard const clear_private_key = [&] { secure_zero(private_key.data(), private_key.size()); };- return ::Crypto::PK::wrap_in_private_key_info(private_key, oid);- }();- return receive_byte_result(result, state, receive);-}--extern "C" {-bool crypto_hmac_sign(::Crypto::Hash::HashKind, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);-}--bool crypto_hmac_sign(::Crypto::Hash::HashKind hash_kind, ReadonlyBytes key, ReadonlyBytes message, void* state, ReceiveEncodedBytes receive)-{- auto mac = ::Crypto::Authentication::hmac(hash_kind, key, message);- if (mac.is_error())- return false;- receive(state, mac.value().bytes());- return true;-}--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(::Crypto::PK::MLDSASize, ReadonlyBytes);-void crypto_mldsa_public_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);-}--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)-{- auto result = ::Crypto::PK::mldsa_sign(size, key->get<::Crypto::PK::MLDSAPrivateKey>(), context, 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)-{- auto result = ::Crypto::PK::mldsa_verify(size, key->get<::Crypto::PK::MLDSAPublicKey>(), context, 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, 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(::Crypto::PK::MLDSASize size, ReadonlyBytes bytes)-{- auto public_key = ::Crypto::PK::MLDSAPublicKey::from_bytes(bytes);- if (public_key.is_error() || public_key.value().size() != size)- return nullptr;- return new KeyHandle(public_key.release_value());-}--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(); });-}--bool crypto_mldsa_seed_bytes(KeyHandle const* key, void* state, ReceiveEncodedBytes receive)-{- 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)-{- auto result = [&]() -> ErrorOr<ByteBuffer> {- if (is_public)- return ::Crypto::PK::wrap_in_subject_public_key_info(key->get<::Crypto::PK::MLDSAPublicKey>().public_key(), oid);- auto private_key = TRY(key->get<::Crypto::PK::MLDSAPrivateKey>().export_as_der());- ScopeGuard const clear_private_key = [&] { secure_zero(private_key.data(), private_key.size()); };- return ::Crypto::PK::wrap_in_private_key_info(private_key, 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);-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);-}--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, 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)-{- 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)-{- receive(state, key->get<::Crypto::PK::MLKEMPublicKey>().public_key());-}--bool crypto_mlkem_seed_bytes(KeyHandle const* key, void* state, ReceiveEncodedBytes receive)-{- 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)-{- auto result = [&]() -> ErrorOr<ByteBuffer> {- if (is_public)- return ::Crypto::PK::wrap_in_subject_public_key_info(key->get<::Crypto::PK::MLKEMPublicKey>().public_key(), oid);- auto private_key = TRY(key->get<::Crypto::PK::MLKEMPrivateKey>().export_as_der());- ScopeGuard const clear_private_key = [&] { secure_zero(private_key.data(), private_key.size()); };- return ::Crypto::PK::wrap_in_private_key_info(private_key, 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);- 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>(), 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;-}--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::digest_size(hash_kind);-}--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);-extern "C" FlatPtr crypto_cshake_digest(::Crypto::Hash::SHAKEKind, ReadonlyBytes, u32, OptionalBytes, OptionalBytes, void*, ReceiveEncodedBytes);--FlatPtr crypto_cshake_validate_parameters(u32 output_length)-{- auto result = ::Crypto::Hash::SHAKE::validate_parameters(output_length);- 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);--KeyHandle* crypto_public_key_for_private_key(KeyHandle const* key, FlatPtr raw_name)-{- auto result = key->visit(- [](::Crypto::PK::RSAPrivateKey const& private_key) -> ErrorOr<KeyHandle> {- return TRY(private_key.public_key());- },- [](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<KeyHandle> {- if (private_key.public_key().has_value())- return *private_key.public_key();- return TRY(private_key.derive_public_key());- },- [](::Crypto::PK::MLDSAPrivateKey const& private_key) -> ErrorOr<KeyHandle> {- return TRY(::Crypto::PK::MLDSAPublicKey::from_bytes(private_key.public_key()));- },- [](::Crypto::PK::MLKEMPrivateKey const& private_key) -> ErrorOr<KeyHandle> {- return TRY(::Crypto::PK::MLKEMPublicKey::from_bytes(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());-}--}diff --git a/Tests/LibCrypto/CMakeLists.txt b/Tests/LibCrypto/CMakeLists.txtindex 169bc02f5f4..dece03e8fc5 100644--- a/Tests/LibCrypto/CMakeLists.txt+++ b/Tests/LibCrypto/CMakeLists.txt@@ -1,20 +1,11 @@ladybird_test_suite(LibCrypto)set(TEST_SOURCES- TestAES.cpp- TestArgon2.cpp- TestASN1.cppTestCurves.cppTestEd25519.cppTestEd448.cppTestHash.cpp- TestHKDF.cppTestHMAC.cpp- TestMLDSA.cpp- TestMLKEM.cpp- TestOAEP.cpp- TestPBKDF2.cpp- TestPSS.cppTestRSA.cpp)diff --git a/Tests/LibCrypto/TestAES.cpp b/Tests/LibCrypto/TestAES.cppdeleted file mode 100644index 089718cf9e2..00000000000--- a/Tests/LibCrypto/TestAES.cpp+++ /dev/null@@ -1,288 +0,0 @@-/*- * Copyright (c) 2021, Peter Bocan <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Cipher/AES.h>-#include <LibTest/TestCase.h>-#include <cstring>--static ReadonlyBytes operator""_b(char const* string, size_t length)-{- return ReadonlyBytes(string, length);-}--static auto test_aes_cbc_encrypt = [](auto& cipher, auto& result) {- auto in = "This is a test! This is another test!"_b;- auto out = TRY_OR_FAIL(cipher.encrypt(in, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"_b));- EXPECT_EQ(out.size(), sizeof(result));- EXPECT(memcmp(out.data(), result, out.size()) == 0);-};--TEST_CASE(test_AES_CBC_encrypt_with_128bit_key)-{- u8 result[] {- 0xb8, 0x06, 0x7c, 0xf2, 0xa9, 0x56, 0x63, 0x58, 0x2d, 0x5c, 0xa1, 0x4b, 0xc5, 0xe3, 0x08,- 0xcf, 0xb5, 0x93, 0xfb, 0x67, 0xb6, 0xf7, 0xaf, 0x45, 0x34, 0x64, 0x70, 0x9e, 0xc9, 0x1a,- 0x8b, 0xd3, 0x70, 0x45, 0xf0, 0x79, 0x65, 0xca, 0xb9, 0x03, 0x88, 0x72, 0x1c, 0xdd, 0xab,- 0x45, 0x6b, 0x1c- };- Crypto::Cipher::AESCBCCipher cipher("WellHelloFriends"_b);- test_aes_cbc_encrypt(cipher, result);-}--TEST_CASE(test_AES_CBC_encrypt_with_unsigned_256bit_key)-{- u8 result[] {- 0x18, 0x71, 0x80, 0x4c, 0x28, 0x07, 0x55, 0x3c, 0x05, 0x33, 0x36, 0x3f, 0x19, 0x38, 0x5c,- 0xbe, 0xf8, 0xb8, 0x0e, 0x0e, 0x66, 0x67, 0x63, 0x9c, 0xbf, 0x73, 0xcd, 0x82, 0xf9, 0xcb,- 0x9d, 0x81, 0x56, 0xc6, 0x75, 0x14, 0x8b, 0x79, 0x60, 0xb0, 0xdf, 0xaa, 0x2c, 0x2b, 0xd4,- 0xd6, 0xa0, 0x46- };- u8 key[] { 0x0a, 0x8c, 0x5b, 0x0d, 0x8a, 0x68, 0x43, 0xf7, 0xaf, 0xc0, 0xe3, 0x4e, 0x4b, 0x43, 0xaa, 0x28, 0x69, 0x9b, 0x6f, 0xe7, 0x24, 0x82, 0x1c, 0x71, 0x86, 0xf6, 0x2b, 0x87, 0xd6, 0x8b, 0x8f, 0xf1 };- Crypto::Cipher::AESCBCCipher cipher(ReadonlyBytes { key, sizeof(key) });- test_aes_cbc_encrypt(cipher, result);-}--static auto test_aes_cbc_decrypt = [](auto& cipher, auto& result, auto result_len) {- auto true_value = "This is a test! This is another test!";- auto in = MUST(ByteBuffer::copy(result, result_len));- auto out = TRY_OR_FAIL(cipher.decrypt(in, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"_b));- EXPECT_EQ(out.size(), strlen(true_value));- EXPECT(memcmp(out.data(), true_value, strlen(true_value)) == 0);-};--TEST_CASE(test_AES_CBC_128bit_key_decrypt)-{- u8 result[] {- 0xb8, 0x06, 0x7c, 0xf2, 0xa9, 0x56, 0x63, 0x58, 0x2d, 0x5c, 0xa1, 0x4b, 0xc5, 0xe3, 0x08,- 0xcf, 0xb5, 0x93, 0xfb, 0x67, 0xb6, 0xf7, 0xaf, 0x45, 0x34, 0x64, 0x70, 0x9e, 0xc9, 0x1a,- 0x8b, 0xd3, 0x70, 0x45, 0xf0, 0x79, 0x65, 0xca, 0xb9, 0x03, 0x88, 0x72, 0x1c, 0xdd, 0xab,- 0x45, 0x6b, 0x1c- };- Crypto::Cipher::AESCBCCipher cipher("WellHelloFriends"_b);- test_aes_cbc_decrypt(cipher, result, 48);-}--static void do_roundtrip_cbc_128_nopad(ReadonlyBytes key, ReadonlyBytes iv, ReadonlyBytes expected_plaintext, ReadonlyBytes expected_ciphertext)-{- Crypto::Cipher::AESCBCCipher cipher(key, true);- {- auto actual_ciphertext = TRY_OR_FAIL(cipher.encrypt(expected_plaintext, iv));- EXPECT_EQ(actual_ciphertext, expected_ciphertext);- }- {- auto actual_plaintext = TRY_OR_FAIL(cipher.decrypt(expected_ciphertext, iv));- EXPECT_EQ(actual_plaintext, expected_plaintext);- }-}--TEST_CASE(test_AES_CBC_128bit_key_encrypt_rfc3602_case1)-{- // Test vector taken from https://www.rfc-editor.org/rfc/rfc3602#section-4- u8 key_raw[16] {- 0x06, 0xa9, 0x21, 0x40, 0x36, 0xb8, 0xa1, 0x5b, 0x51, 0x2e, 0x03, 0xd5, 0x34, 0x12, 0x00, 0x06- };- ReadonlyBytes key(key_raw, sizeof(key_raw));- u8 iv_raw[16] {- 0x3d, 0xaf, 0xba, 0x42, 0x9d, 0x9e, 0xb4, 0x30, 0xb4, 0x22, 0xda, 0x80, 0x2c, 0x9f, 0xac, 0x41- };- ReadonlyBytes iv(iv_raw, sizeof(iv_raw));- ReadonlyBytes plaintext = "Single block msg"_b;- u8 ciphertext_raw[16] {- 0xe3, 0x53, 0x77, 0x9c, 0x10, 0x79, 0xae, 0xb8, 0x27, 0x08, 0x94, 0x2d, 0xbe, 0x77, 0x18, 0x1a- };- ReadonlyBytes ciphertext(ciphertext_raw, sizeof(ciphertext_raw));-- do_roundtrip_cbc_128_nopad(key, iv, plaintext, ciphertext);-}--static void do_roundtrip_cbc_128_cms(ReadonlyBytes key, ReadonlyBytes iv, ReadonlyBytes expected_plaintext, ReadonlyBytes expected_ciphertext)-{- Crypto::Cipher::AESCBCCipher cipher(key);- {- auto actual_ciphertext = TRY_OR_FAIL(cipher.encrypt(expected_plaintext, iv));- EXPECT_EQ(actual_ciphertext, expected_ciphertext);- }- {- auto actual_plaintext = TRY_OR_FAIL(cipher.decrypt(expected_ciphertext, iv));- EXPECT_EQ(actual_plaintext, expected_plaintext);- }-}--TEST_CASE(test_AES_CBC_128bit_key_encrypt_CMS_aligned)-{- // Test vector taken from https://www.rfc-editor.org/rfc/rfc3602#section-4- u8 key_raw[16] {- 0x06, 0xa9, 0x21, 0x40, 0x36, 0xb8, 0xa1, 0x5b, 0x51, 0x2e, 0x03, 0xd5, 0x34, 0x12, 0x00, 0x06- };- ReadonlyBytes key(key_raw, sizeof(key_raw));- u8 iv_raw[16] {- 0x3d, 0xaf, 0xba, 0x42, 0x9d, 0x9e, 0xb4, 0x30, 0xb4, 0x22, 0xda, 0x80, 0x2c, 0x9f, 0xac, 0x41- };- ReadonlyBytes iv(iv_raw, sizeof(iv_raw));- ReadonlyBytes plaintext = "Single block msg"_b;- u8 ciphertext_raw[32] {- 0xe3, 0x53, 0x77, 0x9c, 0x10, 0x79, 0xae, 0xb8, 0x27, 0x08, 0x94, 0x2d, 0xbe, 0x77, 0x18, 0x1a,- // This additional block just encodes the padding "0x1010101010101010".- 0xb9, 0x7c, 0x82, 0x5e, 0x1c, 0x78, 0x51, 0x46, 0x54, 0x2d, 0x39, 0x69, 0x41, 0xbc, 0xe5, 0x5d- };- ReadonlyBytes ciphertext(ciphertext_raw, sizeof(ciphertext_raw));-- do_roundtrip_cbc_128_cms(key, iv, plaintext, ciphertext);-}--#define AS_BB(x) (ReadonlyBytes { (x), sizeof((x)) / sizeof((x)[0]) })--static auto test_aes_ctr_encrypt = [](auto key, auto ivec, auto in, auto out_expected) {- Crypto::Cipher::AESCTRCipher cipher(key);- auto out_actual = TRY_OR_FAIL(cipher.encrypt(in, ivec));- EXPECT_EQ(out_expected.size(), out_actual.size());- EXPECT(memcmp(out_expected.data(), out_actual.data(), out_expected.size()) == 0);-};--TEST_CASE(test_AES_CTR_128bit_key_encrypt_16bytes)-{- u8 key[] {- 0xae, 0x68, 0x52, 0xf8, 0x12, 0x10, 0x67, 0xcc, 0x4b, 0xf7, 0xa5, 0x76, 0x55, 0x77, 0xf3, 0x9e- };- u8 ivec[] {- 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + 1 // See CTR.h- };- u8 in[] {- 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x6d, 0x73, 0x67- };- u8 out[] {- 0xe4, 0x09, 0x5d, 0x4f, 0xb7, 0xa7, 0xb3, 0x79, 0x2d, 0x61, 0x75, 0xa3, 0x26, 0x13, 0x11, 0xb8- };- test_aes_ctr_encrypt(AS_BB(key), AS_BB(ivec), AS_BB(in), AS_BB(out));-}--TEST_CASE(test_AES_CTR_256bit_encrypt_36bytes_with_high_counter)-{- // This test checks whether counter overflow crashes.- u8 key[] {- 0xff, 0x7a, 0x61, 0x7c, 0xe6, 0x91, 0x48, 0xe4, 0xf1, 0x72, 0x6e, 0x2f, 0x43, 0x58, 0x1d, 0xe2, 0xaa, 0x62, 0xd9, 0xf8, 0x05, 0x53, 0x2e, 0xdf, 0xf1, 0xee, 0xd6, 0x87, 0xfb, 0x54, 0x15, 0x3d- };- u8 ivec[] {- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff- };- u8 in[] {- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23- };- u8 out[] {- // Pasted from the output. The actual success condition is- // not crashing when incrementing the counter.- 0x6e, 0x8c, 0xfc, 0x59, 0x08, 0xa8, 0xc0, 0xf1, 0xe6, 0x85, 0x96, 0xe9, 0xc5, 0x40, 0xb6, 0x8b, 0xfe, 0x28, 0x72, 0xe2, 0x24, 0x11, 0x7e, 0x59, 0xef, 0xac, 0x5c, 0xe1, 0x06, 0x89, 0x09, 0xab, 0xf8, 0x90, 0x1c, 0x66- };- test_aes_ctr_encrypt(AS_BB(key), AS_BB(ivec), AS_BB(in), AS_BB(out));-}--static auto test_aes_ctr_decrypt = [](auto key, auto ivec, auto in, auto out_expected) {- Crypto::Cipher::AESCTRCipher cipher(key);- auto out_actual = TRY_OR_FAIL(cipher.decrypt(in, ivec));- EXPECT_EQ(out_expected.size(), out_actual.size());- EXPECT(memcmp(out_expected.data(), out_actual.data(), out_expected.size()) == 0);-};--// From RFC 3686, Section 6-TEST_CASE(test_AES_CTR_128bit_decrypt_16bytes)-{- // This test checks whether counter overflow crashes.- u8 key[] {- 0xae, 0x68, 0x52, 0xf8, 0x12, 0x10, 0x67, 0xcc, 0x4b, 0xf7, 0xa5, 0x76, 0x55, 0x77, 0xf3, 0x9e- };- u8 ivec[] {- 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + 1 // See CTR.h- };- u8 out[] {- 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x6d, 0x73, 0x67- };- u8 in[] {- 0xe4, 0x09, 0x5d, 0x4f, 0xb7, 0xa7, 0xb3, 0x79, 0x2d, 0x61, 0x75, 0xa3, 0x26, 0x13, 0x11, 0xb8- };- test_aes_ctr_decrypt(AS_BB(key), AS_BB(ivec), AS_BB(in), AS_BB(out));- // If encryption works, then decryption works, too.-}--TEST_CASE(test_AES_GCM_128bit_encrypt_empty)-{- Crypto::Cipher::AESGCMCipher cipher("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"_b);- u8 result_tag[] { 0x58, 0xe2, 0xfc, 0xce, 0xfa, 0x7e, 0x30, 0x61, 0x36, 0x7f, 0x1d, 0x57, 0xa4, 0xe7, 0x45, 0x5a };- auto [ciphertext, tag] = TRY_OR_FAIL(cipher.encrypt({}, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"_b, {}, 16));- EXPECT(memcmp(result_tag, tag.data(), tag.size()) == 0);-}--TEST_CASE(test_AES_GCM_128bit_encrypt_with_aad)-{- Crypto::Cipher::AESGCMCipher cipher("\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08"_b);- u8 result_tag[] { 0x4d, 0x5c, 0x2a, 0xf3, 0x27, 0xcd, 0x64, 0xa6, 0x2c, 0xf3, 0x5a, 0xbd, 0x2b, 0xa6, 0xfa, 0xb4 };- u8 result_ct[] { 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c, 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, 0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e, 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, 0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, 0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85 };- auto [ciphertext, tag] = TRY_OR_FAIL(cipher.encrypt(- "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39\x1a\xaf\xd2\x55"_b,- "\xca\xfe\xba\xbe\xfa\xce\xdb\xad\xde\xca\xf8\x88"_b,- {}, 16));- EXPECT(memcmp(result_ct, ciphertext.data(), ciphertext.size()) == 0);- EXPECT(memcmp(result_tag, tag.data(), tag.size()) == 0);-}--TEST_CASE(test_AES_GCM_128bit_encrypt_decrypt_round_trip_with_non_standard_iv)-{- Crypto::Cipher::AESGCMCipher cipher("\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08"_b);- auto plaintext = "The quick brown fox jumps over the lazy dog!"_b;- // 16-byte IV (non-standard; default is 12) to exercise EVP_CTRL_GCM_SET_IVLEN.- auto iv = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"_b;- auto aad = "\xde\xad\xbe\xef"_b;-- auto [ciphertext, tag] = TRY_OR_FAIL(cipher.encrypt(plaintext, iv, aad, 16));- EXPECT_NE(ciphertext.size(), 0u);-- auto decrypted = TRY_OR_FAIL(cipher.decrypt(ciphertext, iv, aad, tag));- EXPECT_EQ(decrypted.size(), plaintext.size());- EXPECT(memcmp(plaintext.data(), decrypted.data(), plaintext.size()) == 0);-}--TEST_CASE(test_AES_GCM_128bit_decrypt_empty)-{- Crypto::Cipher::AESGCMCipher cipher("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"_b);- u8 input_tag[] { 0x58, 0xe2, 0xfc, 0xce, 0xfa, 0x7e, 0x30, 0x61, 0x36, 0x7f, 0x1d, 0x57, 0xa4, 0xe7, 0x45, 0x5a };- auto out = TRY_OR_FAIL(cipher.decrypt({}, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"_b, {}, { input_tag, 16 }));- EXPECT_EQ(out.size(), 0u);-}--TEST_CASE(test_AES_GCM_128bit_decrypt_multiple_blocks_with_aad)-{- Crypto::Cipher::AESGCMCipher cipher("\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08"_b);- u8 input_tag[] { 0x93, 0xae, 0x16, 0x97, 0x49, 0xa3, 0xbf, 0x39, 0x4f, 0x61, 0xb7, 0xc1, 0xb1, 0x2, 0x4f, 0x60 };- u8 input_ct[] { 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c, 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, 0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e, 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, 0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, 0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85 };- u8 result_pt[] { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 };- auto out = TRY_OR_FAIL(cipher.decrypt(- { input_ct, 64 },- "\xca\xfe\xba\xbe\xfa\xce\xdb\xad\xde\xca\xf8\x88"_b,- "\xde\xad\xbe\xef\xfa\xaf\x11\xcc"_b,- { input_tag, 16 }));- EXPECT(memcmp(result_pt, out.data(), out.size()) == 0);-}--TEST_CASE(test_AES_KW_encrypt_128bits_with_128bit_key)-{- Crypto::Cipher::AESKWCipher cipher("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"_b);-- auto wrap_result = "\x1F\xA6\x8B\x0A\x81\x12\xB4\x47\xAE\xF3\x4B\xD8\xFB\x5A\x7B\x82\x9D\x3E\x86\x23\x71\xD2\xCF\xE5"_b;- auto in = "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"_b;-- auto wrapped = TRY_OR_FAIL(cipher.wrap(in));- EXPECT(memcmp(wrapped.data(), wrap_result.data(), wrapped.size()) == 0);-}--TEST_CASE(test_AES_KW_decrypt_128bits_with_128bit_key)-{- Crypto::Cipher::AESKWCipher cipher("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"_b);-- auto unwrap_result = "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"_b;- auto in = "\x1F\xA6\x8B\x0A\x81\x12\xB4\x47\xAE\xF3\x4B\xD8\xFB\x5A\x7B\x82\x9D\x3E\x86\x23\x71\xD2\xCF\xE5"_b;-- auto unwrapped = TRY_OR_FAIL(cipher.unwrap(in));- EXPECT(memcmp(unwrapped.data(), unwrap_result.data(), unwrap_result.size()) == 0);-}diff --git a/Tests/LibCrypto/TestASN1.cpp b/Tests/LibCrypto/TestASN1.cppdeleted file mode 100644index ea5ce8403eb..00000000000--- a/Tests/LibCrypto/TestASN1.cpp+++ /dev/null@@ -1,79 +0,0 @@-/*- * Copyright (c) 2022, Ben Wiederhake <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/ASN1/DER.h>-#include <LibTest/TestCase.h>--template<typename Write>-static ByteBuffer encode(Write write)-{- Crypto::ASN1::Encoder encoder;- MUST(write(encoder));- return encoder.finish();-}--static void expect_encoding(ByteBuffer const& encoded, Vector<u8> const& expected)-{- EXPECT_EQ(encoded.bytes(), expected.span());-}--TEST_CASE(test_encoder_integers)-{- expect_encoding(encode([](auto& encoder) { return encoder.write(0u); }), { 0x02, 0x01, 0x00 });- expect_encoding(encode([](auto& encoder) { return encoder.write(1u); }), { 0x02, 0x01, 0x01 });- expect_encoding(encode([](auto& encoder) { return encoder.write(0x1234u); }), { 0x02, 0x02, 0x12, 0x34 });-- // A leading zero keeps an integer whose top bit is set positive.- expect_encoding(encode([](auto& encoder) { return encoder.write(0x80u); }), { 0x02, 0x02, 0x00, 0x80 });-}--TEST_CASE(test_encoder_object_identifiers)-{- expect_encoding(encode([](auto& encoder) { return encoder.write(Crypto::ASN1::ObjectIdentifier { 1, 2, 840, 113549, 1, 1, 1 }); }),- { 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 });-- // The widest subidentifier the encoder can write.- expect_encoding(encode([](auto& encoder) { return encoder.write(Crypto::ASN1::ObjectIdentifier { 1, 2, 0xfffffff }); }),- { 0x06, 0x05, 0x2a, 0xff, 0xff, 0xff, 0x7f });-}--TEST_CASE(test_encoder_null_and_strings)-{- expect_encoding(encode([](auto& encoder) { return encoder.write(nullptr); }), { 0x05, 0x00 });-- u8 const bytes[] { 0x00, 0x01, 0x02, 0x03 };- expect_encoding(encode([&](auto& encoder) { return encoder.write(Crypto::ASN1::BitStringView { bytes, 0 }); }),- { 0x03, 0x05, 0x00, 0x00, 0x01, 0x02, 0x03 });- expect_encoding(encode([&](auto& encoder) { return encoder.template write<ReadonlyBytes>(bytes); }),- { 0x04, 0x04, 0x00, 0x01, 0x02, 0x03 });- expect_encoding(encode([&](auto& encoder) { return encoder.template write<ReadonlyBytes>(bytes, Crypto::ASN1::Class::Context, static_cast<Crypto::ASN1::Kind>(0)); }),- { 0x80, 0x04, 0x00, 0x01, 0x02, 0x03 });-}--TEST_CASE(test_encoder_lengths_in_the_fewest_bytes_possible)-{- auto header_of_octet_string = [](size_t length) {- auto contents = MUST(ByteBuffer::create_zeroed(length));- auto encoded = encode([&](auto& encoder) { return encoder.template write<ReadonlyBytes>(contents); });- return MUST(ByteBuffer::copy(encoded.bytes().trim(encoded.size() - length)));- };-- expect_encoding(header_of_octet_string(127), { 0x04, 0x7f });- expect_encoding(header_of_octet_string(128), { 0x04, 0x81, 0x80 });- expect_encoding(header_of_octet_string(256), { 0x04, 0x82, 0x01, 0x00 });-}--TEST_CASE(test_encoder_constructed)-{- auto encoded = encode([](auto& encoder) {- return encoder.write_constructed(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {- TRY(encoder.write(0u));- TRY(encoder.write(0x1234u));- return {};- });- });- expect_encoding(encoded, { 0x30, 0x07, 0x02, 0x01, 0x00, 0x02, 0x02, 0x12, 0x34 });-}diff --git a/Tests/LibCrypto/TestArgon2.cpp b/Tests/LibCrypto/TestArgon2.cppdeleted file mode 100644index 029258da419..00000000000--- a/Tests/LibCrypto/TestArgon2.cpp+++ /dev/null@@ -1,57 +0,0 @@-/*- * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Hash/Argon2.h>-#include <LibTest/TestCase.h>--TEST_CASE(ARGON2id)-{- Crypto::Hash::Argon2 argon2(Crypto::Hash::Argon2Type::Argon2id);-- u8 const message[32] = {- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01- };-- u8 const nonce[16] = {- 0x02, 0x02, 0x02, 0x02,- 0x02, 0x02, 0x02, 0x02,- 0x02, 0x02, 0x02, 0x02,- 0x02, 0x02, 0x02, 0x02- };-- u8 const secret_value[8] = {- 0x03, 0x03, 0x03, 0x03,- 0x03, 0x03, 0x03, 0x03- };-- u8 const associated_data[12] = {- 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,- 0x04, 0x04, 0x04, 0x04, 0x04, 0x04- };-- auto const result = TRY_OR_FAIL(argon2.derive_key(- message,- nonce,- 4,- 32,- 3,- 0x13,- TRY_OR_FAIL(ByteBuffer::copy(secret_value, sizeof(secret_value))).span(),- TRY_OR_FAIL(ByteBuffer::copy(associated_data, sizeof(associated_data))).span(),- 256 / 8));-- u8 const expected_output_key[] = {- 0x0d, 0x64, 0x0d, 0xf5, 0x8d, 0x78, 0x76, 0x6c,- 0x08, 0xc0, 0x37, 0xa3, 0x4a, 0x8b, 0x53, 0xc9,- 0xd0, 0x1e, 0xf0, 0x45, 0x2d, 0x75, 0xb6, 0x5e,- 0xb5, 0x25, 0x20, 0xe9, 0x6b, 0x01, 0xe6, 0x59- };-- EXPECT_EQ(result.bytes(), ReadonlyBytes(expected_output_key));-}diff --git a/Tests/LibCrypto/TestCurves.cpp b/Tests/LibCrypto/TestCurves.cppindex 65288cd2a1c..bd910cc2cc4 100644--- a/Tests/LibCrypto/TestCurves.cpp+++ b/Tests/LibCrypto/TestCurves.cpp@@ -9,22 +9,6 @@#include <LibCrypto/PK/EC.h>#include <LibTest/TestCase.h>-TEST_CASE(test_secp256r1_rejects_wrong_signature_width)-{- Array<u8, 32> hash {};- Array<u8, 32> d {};- d[31] = 1;-- auto private_key = TRY_OR_FAIL(Crypto::PK::ECPrivateKey::from_scalar(d, {}, {}));- auto public_key = TRY_OR_FAIL(private_key.derive_public_key());- auto signature = TRY_OR_FAIL(Crypto::PK::ecdsa_sign(private_key, hash));- EXPECT(TRY_OR_FAIL(Crypto::PK::ecdsa_verify(public_key, hash, signature.r, signature.s)));-- auto wide_r = TRY_OR_FAIL(ByteBuffer::create_zeroed(1));- TRY_OR_FAIL(wide_r.try_append(signature.r));- EXPECT(!TRY_OR_FAIL(Crypto::PK::ecdsa_verify(public_key, hash, wide_r, signature.s)));-}-TEST_CASE(test_x25519){// https://datatracker.ietf.org/doc/html/rfc7748#section-6.1@@ -162,97 +146,6 @@ TEST_CASE(test_x448)EXPECT_EQ(shared_alice, shared_bob);}-TEST_CASE(test_secp256r1)-{- // clang-format off- u8 alice_private_key_data[32] {- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,- };-- u8 alice_public_key_data[65] {- 0x04,- 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2,- 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96,- 0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16,- 0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5,- };-- u8 bob_private_key_data[32] {- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,- };-- u8 bob_public_key_data[65] {- 0x04,- 0x7C, 0xF2, 0x7B, 0x18, 0x8D, 0x03, 0x4F, 0x7E, 0x8A, 0x52, 0x38, 0x03, 0x04, 0xB5, 0x1A, 0xC3,- 0xC0, 0x89, 0x69, 0xE2, 0x77, 0xF2, 0x1B, 0x35, 0xA6, 0x0B, 0x48, 0xFC, 0x47, 0x66, 0x99, 0x78,- 0x07, 0x77, 0x55, 0x10, 0xDB, 0x8E, 0xD0, 0x40, 0x29, 0x3D, 0x9A, 0xC6, 0x9F, 0x74, 0x30, 0xDB,- 0xBA, 0x7D, 0xAD, 0xE6, 0x3C, 0xE9, 0x82, 0x29, 0x9E, 0x04, 0xB7, 0x9D, 0x22, 0x78, 0x73, 0xD1,- };-- u8 shared_secret_data[65] {- 0x04,- 0x7c, 0xf2, 0x7b, 0x18, 0x8d, 0x03, 0x4f, 0x7e, 0x8a, 0x52, 0x38, 0x03, 0x04, 0xb5, 0x1a, 0xc3,- 0xc0, 0x89, 0x69, 0xe2, 0x77, 0xf2, 0x1b, 0x35, 0xa6, 0x0b, 0x48, 0xfc, 0x47, 0x66, 0x99, 0x78,- 0x07, 0x77, 0x55, 0x10, 0xdb, 0x8e, 0xd0, 0x40, 0x29, 0x3d, 0x9a, 0xc6, 0x9f, 0x74, 0x30, 0xdb,- 0xba, 0x7d, 0xad, 0xe6, 0x3c, 0xe9, 0x82, 0x29, 0x9e, 0x04, 0xb7, 0x9d, 0x22, 0x78, 0x73, 0xd1,- };-- u8 private_key_data[32] {- 0x01, 0xff, 0xf8, 0x1f, 0xc0, 0x00, 0x00, 0x00, 0x00, 0xff, 0x80, 0x1f, 0xff, 0xc0, 0xf8, 0x1f,- 0x01, 0xff, 0xf8, 0x00, 0x1f, 0xc0, 0x05, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0xff, 0xff, 0xfc,- };-- u8 expected_public_key_data[65] {- 0x04,- 0x34, 0xdf, 0xbc, 0x09, 0x40, 0x4c, 0x21, 0xe2, 0x50, 0xa9, 0xb4, 0x0f, 0xa8, 0x77, 0x28, 0x97,- 0xac, 0x63, 0xa0, 0x94, 0x87, 0x7d, 0xb6, 0x58, 0x62, 0xb6, 0x1b, 0xd1, 0x50, 0x7b, 0x34, 0xf3,- 0xcf, 0x6f, 0x8a, 0x87, 0x6c, 0x6f, 0x99, 0xce, 0xae, 0xc8, 0x71, 0x48, 0xf1, 0x8c, 0x7e, 0x1e,- 0x0d, 0xa6, 0xe1, 0x65, 0xff, 0xc8, 0xed, 0x82, 0xab, 0xb6, 0x59, 0x55, 0x21, 0x5f, 0x77, 0xd3,- };- // clang-format on-- auto alice_private_key = TRY_OR_FAIL(Crypto::PK::ECPrivateKey::from_scalar(alice_private_key_data, {}, {}));- auto alice_public_key = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(alice_public_key_data));- auto bob_private_key = TRY_OR_FAIL(Crypto::PK::ECPrivateKey::from_scalar(bob_private_key_data, {}, {}));- auto bob_public_key = TRY_OR_FAIL(Crypto::PK::ECPublicKey::from_octets(bob_public_key_data));- auto private_key = TRY_OR_FAIL(Crypto::PK::ECPrivateKey::from_scalar(private_key_data, {}, {}));-- auto expect_public_key = [](Crypto::PK::ECPrivateKey const& private_key, ReadonlyBytes expected) {- auto public_key = TRY_OR_FAIL(TRY_OR_FAIL(private_key.derive_public_key()).to_uncompressed());- EXPECT_EQ(public_key.bytes(), expected);- };- expect_public_key(alice_private_key, alice_public_key_data);- expect_public_key(bob_private_key, bob_public_key_data);- expect_public_key(private_key, expected_public_key_data);-- // ECDH gives the x-coordinate of the shared point.- auto shared_secret_x = ReadonlyBytes { shared_secret_data }.slice(1, 32);- auto shared_alice = TRY_OR_FAIL(Crypto::PK::ecdh_derive(alice_private_key, bob_public_key));- EXPECT_EQ(shared_alice.bytes(), shared_secret_x);- auto shared_bob = TRY_OR_FAIL(Crypto::PK::ecdh_derive(bob_private_key, alice_public_key));- EXPECT_EQ(shared_bob.bytes(), shared_secret_x);-}--TEST_CASE(test_secp256r1_rejects_out_of_range_private_keys)-{- Array<u8, 32> zero {};- EXPECT(Crypto::PK::ECPrivateKey::from_scalar(zero, {}, {}).is_error());-- // n, the order of P-256's base point.- u8 const order[32] {- 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,- 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51- };- EXPECT(Crypto::PK::ECPrivateKey::from_scalar(order, {}, {}).is_error());-- // A scalar that is not as wide as P-256's coordinates.- Array<u8, 31> narrow {};- narrow[30] = 1;- EXPECT(Crypto::PK::ECPrivateKey::from_scalar(narrow, {}, {}).is_error());-}-// Test vectors from WebCryptoAPI WPT ec_importKey.https.any.jsTEST_CASE(test_ec_compressed_point_p256){diff --git a/Tests/LibCrypto/TestHKDF.cpp b/Tests/LibCrypto/TestHKDF.cppdeleted file mode 100644index 1ada852cbc5..00000000000--- a/Tests/LibCrypto/TestHKDF.cpp+++ /dev/null@@ -1,72 +0,0 @@-/*- * Copyright (c) 2023, stelar7 <[email protected]>- * Copyright (c) 2024, Ben Wiederhake- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Hash/HKDF.h>-#include <LibTest/TestCase.h>--TEST_CASE(test_error_extreme_output_key_length)-{- Crypto::Hash::HKDF hkdf(Crypto::Hash::HashKind::SHA1);- auto result = hkdf.derive_key(Optional<ReadonlyBytes>(), ReadonlyBytes(), ReadonlyBytes(), 999999);- EXPECT(result.is_error());-}--// https://www.rfc-editor.org/rfc/rfc5869#appendix-A.1-TEST_CASE(test_vector_A_1)-{- // IKM = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b (22 octets)- u8 const ikm[] {- 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,- 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b- };- static_assert(sizeof(ikm) == 22);- // salt = 0x000102030405060708090a0b0c (13 octets)- u8 const salt[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c };- static_assert(sizeof(salt) == 13);- // info = 0xf0f1f2f3f4f5f6f7f8f9 (10 octets)- u8 const info[] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 };- static_assert(sizeof(info) == 10);- // L = 42- size_t const output_key_length = 42;-- Crypto::Hash::HKDF hkdf(Crypto::Hash::HashKind::SHA256);- auto result = TRY_OR_FAIL(hkdf.derive_key(Optional<ReadonlyBytes>(salt), ikm, info, output_key_length));- // Intermediate value 'PRK' isn't checked explicitly. However, any bit error would have- // an avalanche effect on the output, so if the output is correct then PRK can be presumed correct, too.- u8 const expected_output_key[] = {- 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a,- 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf,- 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65- };- static_assert(sizeof(expected_output_key) == output_key_length);- EXPECT_EQ(result.bytes(), ReadonlyBytes(expected_output_key));-}--// https://www.rfc-editor.org/rfc/rfc5869#appendix-A.3-TEST_CASE(test_vector_A_3)-{- u8 const ikm[] {- 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,- 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b- };- static_assert(sizeof(ikm) == 22);- size_t const output_key_length = 42;-- Crypto::Hash::HKDF hkdf(Crypto::Hash::HashKind::SHA256);-- // Note: This creates a salt of zero bytes.- auto result = TRY_OR_FAIL(hkdf.derive_key(Optional<ReadonlyBytes>(ReadonlyBytes()), ikm, ReadonlyBytes(), output_key_length));- // Intermediate value 'PRK' isn't checked explicitly. However, any bit error would have- // an avalanche effect on the output, so if the output is correct then PRK can be presumed correct, too.- u8 const expected_output_key[] = {- 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 0x80, 0x2a, 0x06, 0x3c, 0x5a, 0x31,- 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73, 0x8d, 0x2d,- 0x9d, 0x20, 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8- };- static_assert(sizeof(expected_output_key) == output_key_length);- EXPECT_EQ(result.bytes(), ReadonlyBytes(expected_output_key));-}diff --git a/Tests/LibCrypto/TestHash.cpp b/Tests/LibCrypto/TestHash.cppindex 7667ef96782..411c74e0c7a 100644--- a/Tests/LibCrypto/TestHash.cpp+++ b/Tests/LibCrypto/TestHash.cpp@@ -5,7 +5,6 @@*/#include <LibCrypto/Hash/Hash.h>-#include <LibCrypto/Hash/SHAKE.h>#include <LibTest/TestCase.h>#include <cstring>@@ -58,49 +57,3 @@ TEST_CASE(test_SHA3_256_hash_split_into_blocks)auto digest = Crypto::Hash::digest(Crypto::Hash::HashKind::SHA3_256, "0123456789012345678901234567890123456789012345678901234567890123abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcd"sv.bytes());EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });}--TEST_CASE(test_cSHAKE128_without_function_name_or_customization)-{- u8 result[] {- 0x58, 0x81, 0x09, 0x2d, 0xd8, 0x18, 0xbf, 0x5c, 0xf8, 0xa3, 0xdd, 0xb7, 0x93, 0xfb, 0xcb, 0xa7,- 0x40, 0x97, 0xd5, 0xc5, 0x26, 0xa6, 0xd3, 0x5f, 0x97, 0xb8, 0x33, 0x51, 0x94, 0x0f, 0x2c, 0xc8- };- auto digest = TRY_OR_FAIL(Crypto::Hash::SHAKE(Crypto::Hash::SHAKEKind::CSHAKE128).digest("abc"sv.bytes(), 256, {}, {}));- EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });-}--// NIST SP 800-185 cSHAKE sample #1-TEST_CASE(test_cSHAKE128_with_customization)-{- u8 const data[] { 0x00, 0x01, 0x02, 0x03 };- u8 result[] {- 0xc1, 0xc3, 0x69, 0x25, 0xb6, 0x40, 0x9a, 0x04, 0xf1, 0xb5, 0x04, 0xfc, 0xbc, 0xa9, 0xd8, 0x2b,- 0x40, 0x17, 0x27, 0x7c, 0xb5, 0xed, 0x2b, 0x20, 0x65, 0xfc, 0x1d, 0x38, 0x14, 0xd5, 0xaa, 0xf5- };- auto digest = TRY_OR_FAIL(Crypto::Hash::SHAKE(Crypto::Hash::SHAKEKind::CSHAKE128).digest(data, 256, "Email Signature"sv.bytes(), {}));- EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });-}--// NIST SP 800-185 cSHAKE sample #3-TEST_CASE(test_cSHAKE256_with_customization)-{- u8 const data[] { 0x00, 0x01, 0x02, 0x03 };- u8 result[] {- 0xd0, 0x08, 0x82, 0x8e, 0x2b, 0x80, 0xac, 0x9d, 0x22, 0x18, 0xff, 0xee, 0x1d, 0x07, 0x0c, 0x48,- 0xb8, 0xe4, 0xc8, 0x7b, 0xff, 0x32, 0xc9, 0x69, 0x9d, 0x5b, 0x68, 0x96, 0xee, 0xe0, 0xed, 0xd1,- 0x64, 0x02, 0x0e, 0x2b, 0xe0, 0x56, 0x08, 0x58, 0xd9, 0xc0, 0x0c, 0x03, 0x7e, 0x34, 0xa9, 0x69,- 0x37, 0xc5, 0x61, 0xa7, 0x4c, 0x41, 0x2b, 0xb4, 0xc7, 0x46, 0x46, 0x95, 0x27, 0x28, 0x1c, 0x8c- };- auto digest = TRY_OR_FAIL(Crypto::Hash::SHAKE(Crypto::Hash::SHAKEKind::CSHAKE256).digest(data, 512, "Email Signature"sv.bytes(), {}));- EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });-}--TEST_CASE(test_cSHAKE128_with_function_name)-{- u8 result[] {- 0xd8, 0x02, 0x43, 0xb8, 0x42, 0x23, 0x2b, 0xe0, 0xbd, 0x24, 0x26, 0x7d, 0x41, 0x81, 0xc2, 0x5d,- 0x69, 0xb2, 0x86, 0xf4, 0x3a, 0x85, 0xe1, 0xc6, 0xf3, 0x24, 0xdb, 0x04, 0x86, 0xae, 0x19, 0x26- };- auto digest = TRY_OR_FAIL(Crypto::Hash::SHAKE(Crypto::Hash::SHAKEKind::CSHAKE128).digest("hello"sv.bytes(), 256, {}, "KMAC"sv.bytes()));- EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });-}diff --git a/Tests/LibCrypto/TestMLDSA.cpp b/Tests/LibCrypto/TestMLDSA.cppdeleted file mode 100644index 44e1042b2da..00000000000--- a/Tests/LibCrypto/TestMLDSA.cpp+++ /dev/null@@ -1,122 +0,0 @@-/*- * Copyright (c) 2025, Miguel Sacristán Izcue <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/ASN1/DER.h>-#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 [public_key, private_key] = TRY_OR_FAIL(Crypto::PK::MLDSA::generate_key_pair(Crypto::PK::MLDSA65));-- auto size = Crypto::PK::MLDSA65;-- auto const signed_message = TRY_OR_FAIL(Crypto::PK::mldsa_sign(size, private_key, {}, message));- EXPECT(signed_message.size() == 3309);- EXPECT(TRY_OR_FAIL(Crypto::PK::mldsa_verify(size, public_key, {}, message, signed_message)));-- auto const signed_message_with_context = TRY_OR_FAIL(Crypto::PK::mldsa_sign(size, private_key, message, message));- EXPECT(signed_message_with_context.size() == 3309);- EXPECT_NE(signed_message, signed_message_with_context);- EXPECT(TRY_OR_FAIL(Crypto::PK::mldsa_verify(size, public_key, message, message, signed_message_with_context)));-}--static Crypto::PK::MLDSA::KeyPairType generate_key_pair_from_seed(u8 first_seed_byte)-{- auto seed = MUST(ByteBuffer::create_zeroed(32));- for (size_t i = 0; i < seed.size(); ++i)- seed[i] = first_seed_byte + i;- return MUST(Crypto::PK::MLDSA::generate_key_pair(Crypto::PK::MLDSA44, seed));-}--static ByteBuffer encode_both(ReadonlyBytes seed, ReadonlyBytes expanded_key)-{- Crypto::ASN1::Encoder encoder;- MUST(encoder.write_constructed(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::Sequence, [&] -> ErrorOr<void> {- TRY(encoder.write<ReadonlyBytes>(seed, Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::OctetString));- TRY(encoder.write<ReadonlyBytes>(expanded_key, Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::OctetString));- return {};- }));- return encoder.finish();-}--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>(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.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>(expanded_key, Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::OctetString);- }));- auto der = encoder.finish();-- EXPECT(Crypto::PK::MLDSA::parse_mldsa_key(Crypto::PK::MLDSA44, der).is_error());-}--TEST_CASE(seed_and_expanded_key)-{- auto key_pair = generate_key_pair_from_seed(0);- 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(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 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());-}--TEST_CASE(seed_without_its_tag)-{- auto seed = MUST(ByteBuffer::create_zeroed(32));- EXPECT(Crypto::PK::MLDSA::parse_mldsa_key(Crypto::PK::MLDSA44, seed).is_error());-}--TEST_CASE(expanded_key_that_is_not_a_valid_key)-{- // The expandedKey form is checked only for its encoding, since Web Crypto rejects it before validating the key.- auto der = MUST(ByteBuffer::create_zeroed(4 + 2560));- 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.has_seed());-}diff --git a/Tests/LibCrypto/TestMLKEM.cpp b/Tests/LibCrypto/TestMLKEM.cppdeleted file mode 100644index bc0c71a8160..00000000000--- a/Tests/LibCrypto/TestMLKEM.cpp+++ /dev/null@@ -1,130 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/ASN1/DER.h>-#include <LibCrypto/PK/MLKEM.h>-#include <LibTest/TestCase.h>--using Crypto::ASN1::Class;-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));- for (size_t i = 0; i < seed.size(); ++i)- seed[i] = first_seed_byte + i;- return MUST(MLKEM::generate_key_pair(MLKEMSize::MLKEM512, seed));-}--static ByteBuffer encode_both(ReadonlyBytes seed, ReadonlyBytes expanded_key)-{- Crypto::ASN1::Encoder encoder;- MUST(encoder.write_constructed(Class::Universal, Kind::Sequence, [&] -> ErrorOr<void> {- TRY(encoder.write<ReadonlyBytes>(seed, Class::Universal, Kind::OctetString));- TRY(encoder.write<ReadonlyBytes>(expanded_key, Class::Universal, Kind::OctetString));- return {};- }));- return encoder.finish();-}--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>(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.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>(expanded_key, Class::Universal, Kind::OctetString);- }));-- auto der = encoder.finish();- EXPECT(MLKEM::parse_mlkem_key(MLKEMSize::MLKEM512, der).is_error());-}--TEST_CASE(seed_and_expanded_key)-{- auto key_pair = generate_key_pair(0);- 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(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 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());-}--TEST_CASE(seed_without_its_tag)-{- auto seed = MUST(ByteBuffer::create_zeroed(64));- EXPECT(MLKEM::parse_mlkem_key(MLKEMSize::MLKEM512, seed).is_error());-}--TEST_CASE(expanded_key_that_is_not_a_valid_key)-{- // The expandedKey form is checked only for its encoding, since Web Crypto rejects it before validating the key.- auto der = MUST(ByteBuffer::create_zeroed(4 + 1632));- 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.has_seed());-}--TEST_CASE(encodings_that_are_not_der)-{- auto key_pair = generate_key_pair(0);- 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());- header.extend(trailer);- return header;- };-- EXPECT(!parse(encode({ 0x80, 0x40 }, seed)).is_error());- EXPECT(parse(encode({ 0x80, 0x40 }, seed, { 0x00 })).is_error());- EXPECT(parse(encode({ 0x80, 0x81, 0x40 }, seed)).is_error());- EXPECT(parse(encode({ 0x81, 0x40 }, seed)).is_error());-- 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/LibCrypto/TestOAEP.cpp b/Tests/LibCrypto/TestOAEP.cppdeleted file mode 100644index d8906c5b4ae..00000000000--- a/Tests/LibCrypto/TestOAEP.cpp+++ /dev/null@@ -1,23 +0,0 @@-/*- * Copyright (c) 2024, stelar7 <[email protected]>- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/ByteBuffer.h>-#include <LibCrypto/PK/RSA.h>-#include <LibTest/TestCase.h>--// https://www.inf.pucrs.br/~calazans/graduate/TPVLSI_I/RSA-oaep_spec.pdf-TEST_CASE(test_oaep)-{- auto msg = "WellHelloFriendsWellHelloFriendsWellHelloFriendsWellHelloFriends"sv.bytes();-- auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::generate_key_pair(1024));- auto label = "LABEL"sv.bytes();-- auto enc = TRY_OR_FAIL(Crypto::PK::rsa_oaep_encrypt(keypair.public_key, Crypto::Hash::HashKind::SHA1, label, msg));- auto dec = TRY_OR_FAIL(Crypto::PK::rsa_oaep_decrypt(keypair.private_key, Crypto::Hash::HashKind::SHA1, label, enc));- EXPECT_EQ(msg, dec);-}diff --git a/Tests/LibCrypto/TestPBKDF2.cpp b/Tests/LibCrypto/TestPBKDF2.cppdeleted file mode 100644index 361c9ac27c4..00000000000--- a/Tests/LibCrypto/TestPBKDF2.cpp+++ /dev/null@@ -1,53 +0,0 @@-/*- * Copyright (c) 2023, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Hash/PBKDF2.h>-#include <LibTest/TestCase.h>--// https://www.rfc-editor.org/rfc/rfc6070#section-2-TEST_CASE(test_vector_1_sha1)-{- Array<u8, 8> const password {- 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64- };- Array<u8, 4> const salt {- 0x73, 0x61, 0x6c, 0x74- };- Array<u8, 20> const expected {- 0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71,- 0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06,- 0x2f, 0xe0, 0x37, 0xa6- };- u32 iterations = 1;- u32 derived_key_length_bytes = 20;-- Crypto::Hash::PBKDF2 pbkdf2(Crypto::Hash::HashKind::SHA1);- auto result = MUST(pbkdf2.derive_key(password, salt, iterations, derived_key_length_bytes));-- EXPECT_EQ(result, expected.span());-}--TEST_CASE(test_vector_1_sha256)-{- Array<u8, 8> const password {- 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64- };- Array<u8, 4> const salt {- 0x73, 0x61, 0x6c, 0x74- };- Array<u8, 20> const expected {- 0x12, 0x0f, 0xb6, 0xcf, 0xfc, 0xf8, 0xb3, 0x2c,- 0x43, 0xe7, 0x22, 0x52, 0x56, 0xc4, 0xf8, 0x37,- 0xa8, 0x65, 0x48, 0xc9- };- u32 iterations = 1;- u32 derived_key_length_bytes = 20;-- Crypto::Hash::PBKDF2 pbkdf2(Crypto::Hash::HashKind::SHA256);- auto result = MUST(pbkdf2.derive_key(password, salt, iterations, derived_key_length_bytes));-- EXPECT_EQ(result, expected.span());-}diff --git a/Tests/LibCrypto/TestPSS.cpp b/Tests/LibCrypto/TestPSS.cppdeleted file mode 100644index ff6f0490845..00000000000--- a/Tests/LibCrypto/TestPSS.cpp+++ /dev/null@@ -1,47 +0,0 @@-/*- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/ByteBuffer.h>-#include <LibCrypto/PK/RSA.h>-#include <LibTest/TestCase.h>--TEST_CASE(test_pss)-{- auto msg = "WellHelloFriendsWellHelloFriendsWellHelloFriendsWellHelloFriends"sv.bytes();-- auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::generate_key_pair(1024));-- auto sig = TRY_OR_FAIL(Crypto::PK::rsa_pss_sign(keypair.private_key, Crypto::Hash::HashKind::SHA1, 48, msg));- auto ok = TRY_OR_FAIL(Crypto::PK::rsa_pss_verify(keypair.public_key, Crypto::Hash::HashKind::SHA1, 48, msg, sig));- EXPECT(ok);-}--TEST_CASE(test_pss_tampered_message)-{- auto msg = "WellHelloFriendsWellHelloFriendsWellHelloFriendsWellHelloFriends"sv.bytes();- auto msg_tampered = "WellHell0FriendsWellHelloFriendsWellHelloFriendsWellHelloFriends"sv.bytes();-- auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::generate_key_pair(1024));-- auto sig = TRY_OR_FAIL(Crypto::PK::rsa_pss_sign(keypair.private_key, Crypto::Hash::HashKind::SHA1, 48, msg));- auto ok = TRY_OR_FAIL(Crypto::PK::rsa_pss_verify(keypair.public_key, Crypto::Hash::HashKind::SHA1, 48, msg_tampered, sig));- EXPECT(!ok);-}--TEST_CASE(test_pss_tampered_signature)-{- auto msg = "WellHelloFriendsWellHelloFriendsWellHelloFriendsWellHelloFriends"sv.bytes();-- auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::generate_key_pair(1024));-- auto sig = TRY_OR_FAIL(Crypto::PK::rsa_pss_sign(keypair.private_key, Crypto::Hash::HashKind::SHA1, 48, msg));-- // Tamper with the signature- sig[8]++;-- auto ok = TRY_OR_FAIL(Crypto::PK::rsa_pss_verify(keypair.public_key, Crypto::Hash::HashKind::SHA1, 48, msg, sig));- EXPECT(!ok);-}diff --git a/Tests/LibCrypto/TestRSA.cpp b/Tests/LibCrypto/TestRSA.cppindex 64435d1ac06..b1594bbb48b 100644--- a/Tests/LibCrypto/TestRSA.cpp+++ b/Tests/LibCrypto/TestRSA.cpp@@ -5,26 +5,10 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Base64.h>-#include <AK/Hex.h>-#include <LibCrypto/ASN1/Constants.h>+#include <AK/Array.h>#include <LibCrypto/Hash/Hash.h>-#include <LibCrypto/PK/KeyInfo.h>-#include <LibCrypto/PK/PK.h>#include <LibCrypto/PK/RSA.h>#include <LibTest/TestCase.h>-#include <cstring>--// An RSA component in hex, as the big-endian bytes that RSAPrivateKey::component() gives.-static ByteBuffer integer(StringView hex)-{- return MUST(decode_hex(hex));-}--static ByteBuffer operator""_b(char const* string, size_t length)-{- return ByteBuffer::copy(string, length).release_value();-}TEST_CASE(test_RSA_rejects_invalid_public_key){@@ -50,143 +34,3 @@ TEST_CASE(test_RSA_rejects_invalid_public_key)auto invalid_key = TRY_OR_FAIL(Crypto::PK::RSAPublicKey::from_components(modulus, exponent_one));EXPECT(!TRY_OR_FAIL(Crypto::PK::rsa_pkcs1_verify(invalid_key, Crypto::Hash::HashKind::SHA256, message, encoded_message)));}--// RSA PKCS #1 1.5-// RSA | ASN1 PKCS1 DER encoded Key import-TEST_CASE(test_RSA_ASN1_PKCS1_DER_parse)-{- auto der = TRY_OR_FAIL(decode_base64(- "MIIBOgIBAAJBAJsrIYHxs1YL9tpfodaWs1lJoMdF4kgFisUFSj6nvBhJUlmBh607AlgTaX0EDGPYycXYGZ2n6rqmms5lpDXBpUcC"- "AwEAAQJAUNpPkmtEHDENxsoQBUXvXDYeXdePSiIBJhpUjoNOYoR5R9z5oX2cpcyykQ58FC2vKKg+x8N6xczG7qO95tw5UQIhAN35"- "4CP/FA+uTeJ6KJ+izCBCl58CjNCzO0s5HTc56el5AiEAsvPKXo5/9gS/S4UzDRP6abq7GreixTfjR8LXidk3FL8CIQCTjYI861Y+"- "hjMnlORkGSdvWlTHUj6gjEOh4TlWeJzQoQIgAxMZOQKtxCZUuxFwzRq4xLRGnrDlBQpuxz7bwSyQO7UCIHrYMnDohgNbwtA5ZpW3"- "H1cKKQQvueWm6sxW9P5sUrZ3"sv));-- // NB: Private keys are imported inside a PrivateKeyInfo.- auto private_key_info = TRY_OR_FAIL(Crypto::PK::wrap_in_private_key_info(der, Crypto::ASN1::rsa_encryption_oid, nullptr));- size_t consumed = 0;- auto private_key = TRY_OR_FAIL(Crypto::PK::parse_private_key_info(private_key_info, consumed)).rsa;- if (TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PublicExponent)) != integer("010001"sv)) {- FAIL("Invalid public exponent");- }- if (TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PrivateExponent)) != integer("50da4f926b441c310dc6ca100545ef5c361e5dd78f4a2201261a548e834e62847947dcf9a17d9ca5ccb2910e7c142daf28a83ec7c37ac5ccc6eea3bde6dc3951"sv)) {- FAIL("Invalid private exponent");- }-}--// RSA | ASN1 PKCS8 DER encoded Key import-TEST_CASE(test_RSA_ASN1_PKCS8_DER_parse)-{- auto der = TRY_OR_FAIL(decode_base64(- "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7ZBYaG9+CcJP7WVFJRI/uw3hljc7WpzeYs8MN82/g9CG1gnEF"- "3P3ZSBdWVr8gnbh05EsSGHKghIceCB7DNrM5Ab0ru04CuODdPx56xCj+4MmzTc/aq79ntmOt131NGHgq9yVwfJqnSpylOoVw7j/W"- "g4ciwPDQaeLmD1BsE/W9UsF1km7DWasBpW5br82DpudKgJq2Ixf52+rYTCkMgyWcetx4MfXll4y5ZVtJXCnHJfkCS64EaCqXmClP"- "4ovOuHH4khJ3rW9j4yuLe5ck3PSXOrtOTR43HZkCXzseCkbW7qKSmk/9ZreImOzOgu8vvw7ewLAQR9qYVS6XPXY8IilDAgMBAAEC"- "ggEBAIV3ld5mt90Z/exqA2Fh+fofMyNxyz5Lv2d9sZHAL5FTkKbND18TtaIKnMSb6Gl8rKJk76slyo7Vlb8oHXEBBsm1mV0KfVen"- "AlHS4QyjpmdTB5Yz97VR2nQuDfUFpHNC2GQRv5LMzQIWPFfaxKxYpRNOfvOb5Gks4bTmd2tjFAYRMCbHgPw1liKA9dYKk4NB0301"- "EY05e4Zz8RjqYHkkmOPD7DnjFbHqcFUjVKK5E3vDWjxNXUbiSudCCN7WLEOyeHZNd+l6kSAVxZuCAp0G3Da5ndXgIStcy4hYi/fL"- "3XQQbNpxjfhsjlD3tdHNr3NNYDAqxcxpsyO1NCpCIW3ZVrECgYEA7l6gTZ3e9AiSNlMd2O2vNnbQ6UZfsEfu2y7HmpCuNJkFkAnM"- "/1h72Krejnn31rRuR6uCFn4YgQUN9Eq0E1PJCtTay2ucZw5rqtkewT9QzXvVD9eiGM+MF89UzSCC+dOW0/odkD+xP2evnPvGPbXz"- "tnuERC1pi0YWLj1YcsfsEX0CgYEAyUA2UtYjnvCcteIy+rURT0aoZ9tDMrG+Es42EURVv1sduVdUst5R+bXx1aDzpCkcdni3Tyxe"- "osvTGAZngI3O8ghh1GV7NPZRnkiPXjMnhL0Zf+X9gCA6TFANfPuWhMSGijYsCd46diKGDReGYUnmcN9XopeG1h6i3JiOuVPAIb8C"- "gYBmIcUtfGb6yHFdNV+kgrJ/84ivaqe1MBz3bKO5ZiQ+BRKNFKXxAkiOHSgeg8PdCpH1w1aJrJ1zKmdANIHThiKtsWXNot3wig03"- "tq+mvSox4Mz5bLrXRpYP3ZXIDhYQVMhbKt9f3upi8FoeOQJHjp5Nob6aN5rxQaZfSYmMJHzRQQKBgQCOALwUGTtLNBYvlKtKEadk"- "G8RKfAFfbOFkXZLy/hfPDRjdJY0DJTIMk+BPT+F6rPODeMxHllQ0ZMPPiP1RTT5/s4BsISsdhMy0dhiLbGbvF4s9nugPly3rmPTb"- "gp6DkjQoo+7RC7iOkO+rnzTXwxBSBpXMiUTAIx/hrdfPVxQT+wKBgCh7N3OLIOH6EWcW1fifUoENh8rkt/kzm89G1JLwBhuBIBPX"- "UEZt2dS/xSUempqVqFGONpP87gvqxkMTtgCA73KXn/cxHWM2kmXyHA3kQlOYw6WHjpldQAxLE+TRHXO2JUtZ09Mu4rVXX7lmwbTm"- "l3vmuDEF3/Bo1C1HTg0xRV/l"sv));-- size_t consumed = 0;- auto private_key = TRY_OR_FAIL(Crypto::PK::parse_private_key_info(der, consumed)).rsa;- if (TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PublicExponent)) != integer("010001"sv)) {- FAIL("Invalid public exponent");- }-- if (TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PrivateExponent)) != integer("857795de66b7dd19fdec6a036161f9fa1f332371cb3e4bbf677db191c02f915390a6cd0f5f13b5a20a9cc49be8697caca264efab25ca8ed595bf281d710106c9b5995d0a7d57a70251d2e10ca3a66753079633f7b551da742e0df505a47342d86411bf92cccd02163c57dac4ac58a5134e7ef39be4692ce1b4e6776b631406113026c780fc35962280f5d60a938341d37d35118d397b8673f118ea60792498e3c3ec39e315b1ea70552354a2b9137bc35a3c4d5d46e24ae74208ded62c43b278764d77e97a912015c59b82029d06dc36b99dd5e0212b5ccb88588bf7cbdd74106cda718df86c8e50f7b5d1cdaf734d60302ac5cc69b323b5342a42216dd956b1"sv)) {- FAIL("Invalid private exponent");- }-}--TEST_CASE(test_RSA_keygen_enc)-{- auto der = TRY_OR_FAIL(decode_base64(- "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA5HMXMnY+RhEcYXsaOyB/YkcrO1nxIeyDCMqwg5MDrSXO8vPXSEb9"- "AZUNMF1jKiFWPoHxZ+foRxrLv4d9sV/ETwIDAQABAkBpC37UJkjWQRHyxP83xuasExuO6/mT5sQN692kcppTJ9wHNWoD9ZcREk4G"- "Giklu4qx48/fYt8Cv6z6JuQ0ZQExAiEA9XRZVUnCJ2xOcCFCbyIF+d3F9Kht5rR77F9KsRlgUbkCIQDuQ7YzLpQ8V8BJwKbDeXw1"- "vQvcPEnyKnTOoALpF6bqRwIhAIDSm8Ajgf7m3RQEoLVrCe/l8WtCqsuWliOsr6rbQq4hAiEAx8R16wvOtZlNW4jvSU1+WwAaBZl2"- "1lfKf8OhLRXrmNkCIG9IRdcSiNR/Ut8QfD3N9Bb1HsUm+Bvzc8yGzl89pYST"sv));- size_t consumed = 0;- auto priv_key_info = MUST(Crypto::PK::parse_private_key_info(der, consumed));- auto public_key = TRY_OR_FAIL(priv_key_info.rsa.public_key());- auto wrapped_priv_der = MUST(Crypto::PK::wrap_in_private_key_info(priv_key_info.raw_key, Crypto::ASN1::rsa_encryption_oid, nullptr));-- EXPECT_EQ(der.bytes(), wrapped_priv_der.bytes());-- auto enc = TRY_OR_FAIL(Crypto::PK::rsa_oaep_encrypt(public_key, Crypto::Hash::HashKind::SHA1, {}, "WellHelloFriends"sv.bytes()));- auto dec = TRY_OR_FAIL(Crypto::PK::rsa_oaep_decrypt(priv_key_info.rsa, Crypto::Hash::HashKind::SHA1, {}, enc));-- EXPECT_EQ(StringView { dec }, "WellHelloFriends"sv);-}--TEST_CASE(test_RSA_OAEP_rejects_short_ciphertext)-{- auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::generate_key_pair(1024));- auto hash_kind = Crypto::Hash::HashKind::SHA256;- u8 message = 42;-- for (size_t i = 0; i < 4096; ++i) {- auto encrypted = TRY_OR_FAIL(Crypto::PK::rsa_oaep_encrypt(keypair.public_key, hash_kind, {}, { &message, 1 }));- if (encrypted[0] != 0)- continue;-- auto decrypted = TRY_OR_FAIL(Crypto::PK::rsa_oaep_decrypt(keypair.private_key, hash_kind, {}, encrypted));- EXPECT_EQ(decrypted.size(), 1u);- EXPECT_EQ(decrypted[0], message);- EXPECT(Crypto::PK::rsa_oaep_decrypt(keypair.private_key, hash_kind, {}, encrypted.bytes().slice(1)).is_error());- return;- }-- FAIL("Could not generate an RSA ciphertext with a leading zero");-}--TEST_CASE(test_RSA_PSS_rejects_short_signature)-{- auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::generate_key_pair(1024));- auto hash_kind = Crypto::Hash::HashKind::SHA256;- ByteBuffer message { "message"_b };-- for (size_t i = 0; i < 4096; ++i) {- auto signature = TRY_OR_FAIL(Crypto::PK::rsa_pss_sign(keypair.private_key, hash_kind, 32, message));- if (signature[0] != 0)- continue;-- EXPECT(TRY_OR_FAIL(Crypto::PK::rsa_pss_verify(keypair.public_key, hash_kind, 32, message, signature)));- EXPECT(!TRY_OR_FAIL(Crypto::PK::rsa_pss_verify(keypair.public_key, hash_kind, 32, message, signature.bytes().slice(1))));- return;- }-- FAIL("Could not generate an RSA signature with a leading zero");-}--TEST_CASE(test_RSA_rejects_exponent_one)-{- auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::generate_key_pair(1024));- u8 const exponent_one[] { 1 };- auto modulus = TRY_OR_FAIL(keypair.public_key.modulus());- auto public_key = TRY_OR_FAIL(Crypto::PK::RSAPublicKey::from_components(modulus, exponent_one));-- // With e = 1, the EMSA-PKCS1-v1_5 encoding of the message is its own signature.- ByteBuffer message { "message"_b };- auto digest = Crypto::Hash::digest(Crypto::Hash::HashKind::SHA256, message);- static constexpr Array<u8, 19> sha256_digest_info { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 };-- auto encoded = TRY_OR_FAIL(ByteBuffer::create_zeroed(public_key.length()));- auto padding_end = encoded.size() - sha256_digest_info.size() - digest.bytes().size() - 1;- encoded[1] = 0x01;- for (size_t i = 2; i < padding_end; ++i)- encoded[i] = 0xff;- encoded.overwrite(padding_end + 1, sha256_digest_info.data(), sha256_digest_info.size());- encoded.overwrite(padding_end + 1 + sha256_digest_info.size(), digest.bytes().data(), digest.bytes().size());-- EXPECT(!TRY_OR_FAIL(Crypto::PK::rsa_pkcs1_verify(public_key, Crypto::Hash::HashKind::SHA256, message, encoded)));-}diff --git a/Tests/LibTLS/CMakeLists.txt b/Tests/LibTLS/CMakeLists.txtindex e3c19e8c05a..3a8fa3002f6 100644--- a/Tests/LibTLS/CMakeLists.txt+++ b/Tests/LibTLS/CMakeLists.txt@@ -1,7 +1,6 @@ladybird_test_suite(LibTLS)set(TEST_SOURCES- TestTLSCertificateParser.cppTestTLSHandshake.cppTestTLSHostname.cpp)diff --git a/Tests/LibTLS/TestTLSCertificateParser.cpp b/Tests/LibTLS/TestTLSCertificateParser.cppdeleted file mode 100644index 2bf38a62900..00000000000--- a/Tests/LibTLS/TestTLSCertificateParser.cpp+++ /dev/null@@ -1,118 +0,0 @@-/*- * Copyright (c) 2023, Tim Ledbetter <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Base64.h>-#include <LibCrypto/ASN1/Constants.h>-#include <LibCrypto/PK/KeyInfo.h>-#include <LibTest/TestCase.h>--TEST_CASE(test_ed25519_private_key_length)-{- constexpr Array<u8, 16> invalid_key_der {- 0x30, 0x0e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,- 0x03, 0x2b, 0x65, 0x70, 0x04, 0x02, 0x04, 0x00- };- size_t consumed = 0;- EXPECT(Crypto::PK::parse_private_key_info(invalid_key_der, consumed).is_error());-- constexpr Array<u8, 48> valid_key_der {- 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,- 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00- };- EXPECT(!Crypto::PK::parse_private_key_info(valid_key_der, consumed).is_error());-}--TEST_CASE(test_private_key_info_decode)-{- constexpr auto keyder = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA5HMXMnY+RhEcYXsa"- "OyB/YkcrO1nxIeyDCMqwg5MDrSXO8vPXSEb9AZUNMF1jKiFWPoHxZ+foRxrLv4d9"- "sV/ETwIDAQABAkBpC37UJkjWQRHyxP83xuasExuO6/mT5sQN692kcppTJ9wHNWoD"- "9ZcREk4GGiklu4qx48/fYt8Cv6z6JuQ0ZQExAiEA9XRZVUnCJ2xOcCFCbyIF+d3F"- "9Kht5rR77F9KsRlgUbkCIQDuQ7YzLpQ8V8BJwKbDeXw1vQvcPEnyKnTOoALpF6bq"- "RwIhAIDSm8Ajgf7m3RQEoLVrCe/l8WtCqsuWliOsr6rbQq4hAiEAx8R16wvOtZlN"- "W4jvSU1+WwAaBZl21lfKf8OhLRXrmNkCIG9IRdcSiNR/Ut8QfD3N9Bb1HsUm+Bvz"- "c8yGzl89pYST"sv;-- static_assert(keyder.length() == 460u, "keyder length is not 340");-- auto decoded_keyder = TRY_OR_FAIL(decode_base64(keyder));-- size_t consumed = 0;- auto private_key_info = TRY_OR_FAIL(Crypto::PK::parse_private_key_info(decoded_keyder, consumed));-- EXPECT_EQ(private_key_info.algorithm.identifier, Crypto::ASN1::rsa_encryption_oid);- auto& key = private_key_info.rsa;- using Component = Crypto::PK::RSAPrivateKey::Component;- // NB: A component has no leading zero bytes, which `openssl rsa -text` prints before a top bit that is set.- auto expect_component = [&](Component component, ReadonlyBytes expected) {- auto bytes = MUST(key.component(component));- while (!expected.is_empty() && expected[0] == 0)- expected = expected.slice(1);- EXPECT_EQ(bytes.bytes(), expected);- };-- u8 const public_exponent[] = { 0x01, 0x00, 0x01 };- expect_component(Component::PublicExponent, public_exponent);-- // $ openssl rsa -in testcase.pem -text-- u8 const modulus[] = {- 0x00, 0xe4, 0x73, 0x17, 0x32, 0x76, 0x3e, 0x46, 0x11, 0x1c, 0x61, 0x7b, 0x1a, 0x3b, 0x20,- 0x7f, 0x62, 0x47, 0x2b, 0x3b, 0x59, 0xf1, 0x21, 0xec, 0x83, 0x08, 0xca, 0xb0, 0x83, 0x93,- 0x03, 0xad, 0x25, 0xce, 0xf2, 0xf3, 0xd7, 0x48, 0x46, 0xfd, 0x01, 0x95, 0x0d, 0x30, 0x5d,- 0x63, 0x2a, 0x21, 0x56, 0x3e, 0x81, 0xf1, 0x67, 0xe7, 0xe8, 0x47, 0x1a, 0xcb, 0xbf, 0x87,- 0x7d, 0xb1, 0x5f, 0xc4, 0x4f- };- expect_component(Component::Modulus, modulus);-- u8 const private_exponent[] = {- 0x69, 0x0b, 0x7e, 0xd4, 0x26, 0x48, 0xd6, 0x41, 0x11, 0xf2, 0xc4, 0xff, 0x37, 0xc6, 0xe6,- 0xac, 0x13, 0x1b, 0x8e, 0xeb, 0xf9, 0x93, 0xe6, 0xc4, 0x0d, 0xeb, 0xdd, 0xa4, 0x72, 0x9a,- 0x53, 0x27, 0xdc, 0x07, 0x35, 0x6a, 0x03, 0xf5, 0x97, 0x11, 0x12, 0x4e, 0x06, 0x1a, 0x29,- 0x25, 0xbb, 0x8a, 0xb1, 0xe3, 0xcf, 0xdf, 0x62, 0xdf, 0x02, 0xbf, 0xac, 0xfa, 0x26, 0xe4,- 0x34, 0x65, 0x01, 0x31- };- expect_component(Component::PrivateExponent, private_exponent);-- u8 const prime1[] = {- 0x00, 0xf5, 0x74, 0x59, 0x55, 0x49, 0xc2, 0x27, 0x6c, 0x4e, 0x70, 0x21, 0x42, 0x6f, 0x22,- 0x05, 0xf9, 0xdd, 0xc5, 0xf4, 0xa8, 0x6d, 0xe6, 0xb4, 0x7b, 0xec, 0x5f, 0x4a, 0xb1, 0x19,- 0x60, 0x51, 0xb9- };- expect_component(Component::Prime1, prime1);-- u8 const prime2[] = {- 0x00, 0xee, 0x43, 0xb6, 0x33, 0x2e, 0x94, 0x3c, 0x57, 0xc0, 0x49, 0xc0, 0xa6, 0xc3, 0x79,- 0x7c, 0x35, 0xbd, 0x0b, 0xdc, 0x3c, 0x49, 0xf2, 0x2a, 0x74, 0xce, 0xa0, 0x02, 0xe9, 0x17,- 0xa6, 0xea, 0x47- };- expect_component(Component::Prime2, prime2);-- u8 const exponent1[] = {- 0x00, 0x80, 0xd2, 0x9b, 0xc0, 0x23, 0x81, 0xfe, 0xe6, 0xdd, 0x14, 0x04, 0xa0, 0xb5, 0x6b,- 0x09, 0xef, 0xe5, 0xf1, 0x6b, 0x42, 0xaa, 0xcb, 0x96, 0x96, 0x23, 0xac, 0xaf, 0xaa, 0xdb,- 0x42, 0xae, 0x21- };- expect_component(Component::Exponent1, exponent1);-- u8 const exponent2[] = {- 0x00, 0xc7, 0xc4, 0x75, 0xeb, 0x0b, 0xce, 0xb5, 0x99, 0x4d, 0x5b, 0x88, 0xef, 0x49, 0x4d,- 0x7e, 0x5b, 0x00, 0x1a, 0x05, 0x99, 0x76, 0xd6, 0x57, 0xca, 0x7f, 0xc3, 0xa1, 0x2d, 0x15,- 0xeb, 0x98, 0xd9- };- expect_component(Component::Exponent2, exponent2);-- u8 const coefficient[] = {- 0x6f, 0x48, 0x45, 0xd7, 0x12, 0x88, 0xd4, 0x7f, 0x52, 0xdf, 0x10, 0x7c, 0x3d, 0xcd, 0xf4,- 0x16, 0xf5, 0x1e, 0xc5, 0x26, 0xf8, 0x1b, 0xf3, 0x73, 0xcc, 0x86, 0xce, 0x5f, 0x3d, 0xa5,- 0x84, 0x93- };- expect_component(Component::Coefficient, coefficient);-}