Truly independent web browser
LibCrypto: Parse SPKI and PKCS#8 with OpenSSL
Shannon Boothb03c196ba83c
diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txtindex 32dc6c4d025..1fe31cfb04a 100644--- a/Libraries/LibCrypto/CMakeLists.txt+++ b/Libraries/LibCrypto/CMakeLists.txt@@ -9,7 +9,6 @@ set(SOURCESAuthentication/HMAC.cppAuthentication/KMAC.cppBigInt/UnsignedBigInteger.cpp- Certificate/Certificate.cppCipher/AES.cppCipher/ChaCha.cppCurves/EdwardsCurve.cpp@@ -19,6 +18,7 @@ set(SOURCESHash/HKDF.cppHash/PBKDF2.cppPK/EC.cpp+ PK/KeyInfo.cppPK/MLDSA.cppPK/MLKEM.cppPK/ModuleLatticePrivateKey.cppdiff --git a/Libraries/LibCrypto/Certificate/Certificate.cpp b/Libraries/LibCrypto/Certificate/Certificate.cppdeleted file mode 100644index 0e6510f428b..00000000000--- a/Libraries/LibCrypto/Certificate/Certificate.cpp+++ /dev/null@@ -1,387 +0,0 @@-/*- * Copyright (c) 2020, Ali Mohammad Pur <[email protected]>- * Copyright (c) 2023, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/ByteBuffer.h>-#include <LibCrypto/ASN1/ASN1.h>-#include <LibCrypto/ASN1/Constants.h>-#include <LibCrypto/ASN1/DER.h>-#include <LibCrypto/Certificate/Certificate.h>-#include <LibCrypto/PK/EC.h>--namespace Crypto::Certificate {--ErrorOr<ASN1::ObjectIdentifier> parse_ec_parameters(ASN1::Decoder& decoder, Vector<StringView> current_scope)-{- // ECParameters ::= CHOICE {- // namedCurve OBJECT IDENTIFIER- // }- PUSH_SCOPE("ECParameters"sv);- READ_OBJECT(ObjectIdentifier, ASN1::ObjectIdentifier, named_curve);- POP_SCOPE();-- constexpr static Array<Span<u32 const>, 3> known_curve_identifiers {- ASN1::secp256r1_oid,- ASN1::secp384r1_oid,- ASN1::secp521r1_oid- };-- bool is_known_curve = false;- for (auto const& curves : known_curve_identifiers) {- if (curves == named_curve.span()) {- is_known_curve = true;- break;- }- }-- if (!is_known_curve) {- ERROR_WITH_SCOPE(TRY(String::formatted("Unknown named curve {}", named_curve)));- }-- return named_curve;-}--static ErrorOr<AlgorithmIdentifier> parse_algorithm_identifier(ASN1::Decoder& decoder, Vector<StringView> current_scope)-{- // AlgorithmIdentifier{ALGORITHM:SupportedAlgorithms} ::= SEQUENCE {- // algorithm ALGORITHM.&id({SupportedAlgorithms}),- // parameters ALGORITHM.&Type({SupportedAlgorithms}{@algorithm}) OPTIONAL,- // ... }- ENTER_TYPED_SCOPE(Sequence, "AlgorithmIdentifier");- PUSH_SCOPE("algorithm"sv);- READ_OBJECT(ObjectIdentifier, ASN1::ObjectIdentifier, algorithm);- POP_SCOPE();-- constexpr static Array<Span<u32 const>, 12> known_algorithm_identifiers {- ASN1::rsa_encryption_oid,- ASN1::ec_public_key_encryption_oid,- ASN1::x25519_oid,- ASN1::ed25519_oid,- ASN1::x448_oid,- ASN1::ed448_oid,- ASN1::ml_dsa_44_oid,- ASN1::ml_dsa_65_oid,- ASN1::ml_dsa_87_oid,- ASN1::ml_kem_512_oid,- ASN1::ml_kem_768_oid,- ASN1::ml_kem_1024_oid- };-- bool is_known_algorithm = false;- for (auto const& inner : known_algorithm_identifiers) {- if (inner == algorithm.span()) {- is_known_algorithm = true;- break;- }- }-- if (!is_known_algorithm) {- ERROR_WITH_SCOPE(TRY(String::formatted("Unknown algorithm {}", algorithm)));- }-- // -- When rsaEncryption is used in an AlgorithmIdentifier,- // -- the parameters MUST be present and MUST be NULL.- // rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 }- if (algorithm.span() == ASN1::rsa_encryption_oid.span()) {- PUSH_SCOPE("RSA null parameter"sv);- READ_OBJECT(Null, void*, forced_null);- (void)forced_null;- POP_SCOPE();-- EXIT_SCOPE();- return AlgorithmIdentifier(algorithm);- }-- // https://datatracker.ietf.org/doc/html/rfc8410#section-9- // For all of the OIDs, the parameters MUST be absent.-- // https://datatracker.ietf.org/doc/html/rfc9881/#section-2- // The contents of the parameters component for each algorithm MUST be absent.-- // https://datatracker.ietf.org/doc/html/rfc8410#section-9- // For all of the OIDs, the parameters MUST be absent.- constexpr static Array<Span<u32 const>, 10> no_parameter_algorithms = {- ASN1::x25519_oid,- ASN1::x448_oid,- ASN1::ed25519_oid,- ASN1::ed448_oid,- ASN1::ml_dsa_44_oid,- ASN1::ml_dsa_65_oid,- ASN1::ml_dsa_87_oid,- ASN1::ml_kem_512_oid,- ASN1::ml_kem_768_oid,- ASN1::ml_kem_1024_oid- };-- bool is_no_parameter_algorithm = false;- for (auto const& inner : no_parameter_algorithms) {- if (inner == algorithm.span()) {- is_no_parameter_algorithm = true;- }- }-- if (is_no_parameter_algorithm) {- EXIT_SCOPE();-- return AlgorithmIdentifier(algorithm);- }-- if (algorithm.span() == ASN1::ec_public_key_encryption_oid.span()) {- // The parameters associated with id-ecPublicKey SHOULD be absent or ECParameters,- // and NULL is allowed to support legacy implementations.- if (decoder.eof()) {- EXIT_SCOPE();-- return AlgorithmIdentifier(algorithm);- }-- auto tag = TRY(decoder.peek());- if (tag.kind == Crypto::ASN1::Kind::Null) {- PUSH_SCOPE("ecPublicKey null parameter"sv);- READ_OBJECT(Null, void*, forced_null);- (void)forced_null;- POP_SCOPE();-- EXIT_SCOPE();- return AlgorithmIdentifier(algorithm);- }-- auto algorithm_identifier = AlgorithmIdentifier(algorithm);- algorithm_identifier.ec_parameters = TRY(parse_ec_parameters(decoder, current_scope));-- EXIT_SCOPE();- return algorithm_identifier;- }-- ERROR_WITH_SCOPE(TRY(String::formatted("Unhandled parameters for algorithm {}", algorithm)));-}--// https://datatracker.ietf.org/doc/html/rfc5280#section-4.1-ErrorOr<SubjectPublicKey> parse_subject_public_key_info(ASN1::Decoder& decoder, Vector<StringView> current_scope)-{- // SubjectPublicKeyInfo ::= Sequence {- // algorithm AlgorithmIdentifier,- // subject_public_key BitString- // }-- SubjectPublicKey public_key;- ENTER_TYPED_SCOPE(Sequence, "SubjectPublicKeyInfo");-- public_key.algorithm = TRY(parse_algorithm_identifier(decoder, current_scope));-- PUSH_SCOPE("subjectPublicKey"sv);- READ_OBJECT(BitString, Crypto::ASN1::BitStringView, value);- POP_SCOPE();-- public_key.raw_key = TRY(ByteBuffer::copy(TRY(value.raw_bytes())));-- if (public_key.algorithm.identifier.span() == ASN1::rsa_encryption_oid.span()) {- auto maybe_key = Crypto::PK::RSA::parse_rsa_key(public_key.raw_key, false, current_scope);- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- public_key.rsa = move(maybe_key.release_value().public_key);-- EXIT_SCOPE();- return public_key;- }- if (public_key.algorithm.identifier.span() == ASN1::ec_public_key_encryption_oid.span()) {- auto maybe_key = Crypto::PK::EC::parse_ec_key(public_key.raw_key, false, current_scope);- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- public_key.ec = move(maybe_key.release_value().public_key);-- EXIT_SCOPE();- return public_key;- }-- // https://datatracker.ietf.org/doc/html/rfc8410#section-9- // For all of the OIDs, the parameters MUST be absent.-- // https://datatracker.ietf.org/doc/html/rfc9881/#section-2- // The contents of the parameters component for each algorithm MUST be absent.-- // https://datatracker.ietf.org/doc/html/draft-ietf-lamps-kyber-certificates-07#section-3-6- // The parameters field of the AlgorithmIdentifier for the ML-KEM public key MUST be absent.- constexpr static Array<Span<u32 const>, 11> no_parameter_algorithms = {- ASN1::ec_public_key_encryption_oid,- ASN1::x25519_oid,- ASN1::x448_oid,- ASN1::ed25519_oid,- ASN1::ed448_oid,- ASN1::ml_dsa_44_oid,- ASN1::ml_dsa_65_oid,- ASN1::ml_dsa_87_oid,- ASN1::ml_kem_512_oid,- ASN1::ml_kem_768_oid,- ASN1::ml_kem_1024_oid- };-- for (auto const& inner : no_parameter_algorithms) {- if (public_key.algorithm.identifier.span() == inner) {- // Note: Raw key is already stored, so we can just exit out at this point.- EXIT_SCOPE();- return public_key;- }- }-- String algo_oid = TRY(String::join("."sv, public_key.algorithm.identifier));- ERROR_WITH_SCOPE(TRY(String::formatted("Unhandled algorithm {}", algo_oid)));-}--// https://www.rfc-editor.org/rfc/rfc5208#section-5-ErrorOr<PrivateKey> parse_private_key_info(ASN1::Decoder& decoder, Vector<StringView> current_scope)-{- // PrivateKeyInfo ::= SEQUENCE {- // version Version,- // privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,- // privateKey PrivateKey,- // attributes [0] IMPLICIT Attributes OPTIONAL- // }-- PrivateKey private_key;- ENTER_TYPED_SCOPE(Sequence, "PrivateKeyInfo");-- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, version);- if (version != 0) {- ERROR_WITH_SCOPE(TRY(String::formatted("Invalid version value at {}", current_scope)));- }- private_key.algorithm = TRY(parse_algorithm_identifier(decoder, current_scope));-- PUSH_SCOPE("privateKey"sv);- READ_OBJECT(OctetString, StringView, value);- POP_SCOPE();-- private_key.raw_key = TRY(ByteBuffer::copy(value.bytes()));-- if (private_key.algorithm.identifier.span() == ASN1::rsa_encryption_oid.span()) {- auto maybe_key = Crypto::PK::RSA::parse_rsa_key(value.bytes(), true, current_scope);- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- private_key.rsa = move(maybe_key.release_value().private_key);-- EXIT_SCOPE();- return private_key;- }- if (private_key.algorithm.identifier.span() == ASN1::ec_public_key_encryption_oid.span()) {- auto maybe_key = Crypto::PK::EC::parse_ec_key(value.bytes(), true, current_scope);- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- private_key.ec = move(maybe_key.release_value().private_key);-- EXIT_SCOPE();- return private_key;- }- if (private_key.algorithm.identifier.span() == ASN1::ml_dsa_44_oid.span()) {- auto maybe_key = Crypto::PK::MLDSA::parse_mldsa_key(PK::MLDSA44, value.bytes());- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- private_key.mldsa = move(maybe_key.release_value().private_key);- EXIT_SCOPE();- return private_key;- }- if (private_key.algorithm.identifier.span() == ASN1::ml_dsa_65_oid.span()) {- auto maybe_key = Crypto::PK::MLDSA::parse_mldsa_key(PK::MLDSA65, value.bytes());- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- private_key.mldsa = move(maybe_key.release_value().private_key);- EXIT_SCOPE();- return private_key;- }- if (private_key.algorithm.identifier.span() == ASN1::ml_dsa_87_oid.span()) {- auto maybe_key = Crypto::PK::MLDSA::parse_mldsa_key(PK::MLDSA87, value.bytes());- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- private_key.mldsa = move(maybe_key.release_value().private_key);- EXIT_SCOPE();- return private_key;- }- if (private_key.algorithm.identifier.span() == ASN1::ml_kem_512_oid.span()) {- auto maybe_key = Crypto::PK::MLKEM::parse_mlkem_key(PK::MLKEMSize::MLKEM512, value.bytes());- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- private_key.mlkem = move(maybe_key.release_value().private_key);- EXIT_SCOPE();- return private_key;- }- if (private_key.algorithm.identifier.span() == ASN1::ml_kem_768_oid.span()) {- auto maybe_key = Crypto::PK::MLKEM::parse_mlkem_key(PK::MLKEMSize::MLKEM768, value.bytes());- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- private_key.mlkem = move(maybe_key.release_value().private_key);- EXIT_SCOPE();- return private_key;- }- if (private_key.algorithm.identifier.span() == ASN1::ml_kem_1024_oid.span()) {- auto maybe_key = Crypto::PK::MLKEM::parse_mlkem_key(PK::MLKEMSize::MLKEM1024, value.bytes());- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());- }-- private_key.mlkem = move(maybe_key.release_value().private_key);- EXIT_SCOPE();- return private_key;- }-- if (private_key.algorithm.identifier.span() == ASN1::ed25519_oid.span()) {- ASN1::Decoder private_key_decoder(value.bytes());- auto curve_private_key = TRY(private_key_decoder.read<StringView>(ASN1::Class::Universal, ASN1::Kind::OctetString));- if (!private_key_decoder.eof() || curve_private_key.length() != 32)- ERROR_WITH_SCOPE(TRY(String::formatted("Invalid Ed25519 private key at {}", current_scope)));- }-- // https://datatracker.ietf.org/doc/html/rfc8410#section-9- // For all of the OIDs, the parameters MUST be absent.-- // https://datatracker.ietf.org/doc/html/rfc9881/#section-2- // The contents of the parameters component for each algorithm MUST be absent.-- // https://datatracker.ietf.org/doc/html/draft-ietf-lamps-kyber-certificates-07#section-3-6- // The parameters field of the AlgorithmIdentifier for the ML-KEM public key MUST be absent.- constexpr static Array<Span<u32 const>, 11> no_parameter_algorithms = {- ASN1::ec_public_key_encryption_oid,- ASN1::x25519_oid,- ASN1::x448_oid,- ASN1::ed25519_oid,- ASN1::ed448_oid,- ASN1::ml_dsa_44_oid,- ASN1::ml_dsa_65_oid,- ASN1::ml_dsa_87_oid,- ASN1::ml_kem_512_oid,- ASN1::ml_kem_768_oid,- ASN1::ml_kem_1024_oid- };-- for (auto const& inner : no_parameter_algorithms) {- if (private_key.algorithm.identifier.span() == inner) {- // Note: Raw key is already stored, so we can just exit out at this point.- EXIT_SCOPE();- return private_key;- }- }-- String algo_oid = TRY(String::join("."sv, private_key.algorithm.identifier));- ERROR_WITH_SCOPE(TRY(String::formatted("Unhandled algorithm {}", algo_oid)));-}--}diff --git a/Libraries/LibCrypto/Certificate/Certificate.h b/Libraries/LibCrypto/Certificate/Certificate.hdeleted file mode 100644index f6993e4e16c..00000000000--- a/Libraries/LibCrypto/Certificate/Certificate.h+++ /dev/null@@ -1,59 +0,0 @@-/*- * Copyright (c) 2020-2023, the SerenityOS developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#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>--namespace Crypto::Certificate {--struct AlgorithmIdentifier {- AlgorithmIdentifier()- {- }-- explicit AlgorithmIdentifier(ASN1::ObjectIdentifier const& identifier)- : identifier(identifier)- {- }-- ASN1::ObjectIdentifier identifier;- Optional<ASN1::ObjectIdentifier> ec_parameters {};-};--ErrorOr<ASN1::ObjectIdentifier> parse_ec_parameters(ASN1::Decoder& decoder, Vector<StringView> current_scope = {});--// https://datatracker.ietf.org/doc/html/rfc5280#section-4.1-class SubjectPublicKey {-public:- PK::RSAPublicKey rsa;- PK::ECPublicKey ec;-- AlgorithmIdentifier algorithm;- ByteBuffer raw_key;-};-ErrorOr<SubjectPublicKey> parse_subject_public_key_info(ASN1::Decoder& decoder, Vector<StringView> current_scope = {});--// https://www.rfc-editor.org/rfc/rfc5208#section-5-class PrivateKey {-public:- PK::RSAPrivateKey rsa;- PK::ECPrivateKey ec;- PK::MLDSAPrivateKey mldsa;- PK::MLKEMPrivateKey mlkem;-- AlgorithmIdentifier algorithm;- ByteBuffer raw_key;-- // FIXME: attributes [0] IMPLICIT Attributes OPTIONAL-};-ErrorOr<PrivateKey> parse_private_key_info(ASN1::Decoder& decoder, Vector<StringView> current_scope = {});--}diff --git a/Libraries/LibCrypto/PK/EC.cpp b/Libraries/LibCrypto/PK/EC.cppindex df9bf20fafc..e127e4bc1f5 100644--- a/Libraries/LibCrypto/PK/EC.cpp+++ b/Libraries/LibCrypto/PK/EC.cpp@@ -9,7 +9,6 @@#include <AK/ScopeGuard.h>#include <AK/StringView.h>#include <LibCrypto/ASN1/DER.h>-#include <LibCrypto/Certificate/Certificate.h>#include <LibCrypto/OpenSSL.h>#include <LibCrypto/PK/EC.h>@@ -167,40 +166,24 @@ ErrorOr<ECPrivateKey> ECPrivateKey::from_scalar(ReadonlyBytes d_bytes, Optional<return ECPrivateKey { move(key), d_bytes.size(), move(parameters), move(public_key) };}-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+// 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-- auto d = TRY(d_bytes());- ScopeGuard const clear_d = [&] { secure_zero(d.data(), d.size()); };TRY(encoder.write<ReadonlyBytes>(d));- if (m_parameters.has_value()) {+ if (parameters.has_value()) {TRY(encoder.write_constructed(ASN1::Class::Context, static_cast<ASN1::Kind>(0), [&]() -> ErrorOr<void> {- TRY(encoder.write<ASN1::ObjectIdentifier>(*m_parameters, {}, ASN1::Kind::ObjectIdentifier));+ TRY(encoder.write<ASN1::ObjectIdentifier>(*parameters, {}, ASN1::Kind::ObjectIdentifier));return {};}));}- if (m_public_key.has_value()) {+ if (public_point.has_value()) {TRY(encoder.write_constructed(ASN1::Class::Context, static_cast<ASN1::Kind>(1), [&]() -> ErrorOr<void> {- auto public_key_bytes = TRY(m_public_key->to_uncompressed());- TRY(encoder.write(ASN1::BitStringView(public_key_bytes, 0)));-+ TRY(encoder.write(ASN1::BitStringView(*public_point, 0)));return {};}));}@@ -211,85 +194,58 @@ ErrorOr<ByteBuffer> ECPrivateKey::export_as_der() constreturn encoder.finish();}-// https://www.rfc-editor.org/rfc/rfc5915#section-3-ErrorOr<EC::KeyPairType> EC::parse_ec_key(ReadonlyBytes der, bool is_private, Vector<StringView> current_scope)+ErrorOr<ECPrivateKey> ECPrivateKey::from_private_key_info(EVP_PKEY* key, ASN1::ObjectIdentifier const& curve, ReadonlyBytes encoded){- KeyPairType keypair;-- if (!is_private) {- // NB: A raw public key is the SEC 1 point itself.- auto maybe_key = ECPublicKey::from_octets(der);- if (maybe_key.is_error()) {- ERROR_WITH_SCOPE(maybe_key.release_error());+ 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));}-- keypair.public_key = maybe_key.release_value();- return keypair;}+ return Error::from_string_literal("Invalid ECPrivateKey");+}- ASN1::Decoder decoder(der);-- // ECPrivateKey ::= SEQUENCE {- // version INTEGER { ecPrivkeyVer1(1) }(ecPrivkeyVer1),- // privateKey OCTET STRING,- // parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,- // publicKey [1] BIT STRING OPTIONAL- // }-- ENTER_TYPED_SCOPE(Sequence, "ECPrivateKey");-- PUSH_SCOPE("version");- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, version);- POP_SCOPE();-- if (version != 1) {- ERROR_WITH_SCOPE("Invalid version");- }-- PUSH_SCOPE("privateKey");- READ_OBJECT(OctetString, StringView, private_key_bytes);- POP_SCOPE();-- Optional<ASN1::ObjectIdentifier> parameters;- if (!decoder.eof()) {- auto tag = TRY(decoder.peek());- if (static_cast<u8>(tag.kind) == 0) {- REWRITE_TAG(Sequence);- ENTER_TYPED_SCOPE(Sequence, "parameters");- parameters = TRY(Crypto::Certificate::parse_ec_parameters(decoder, {}));- EXIT_SCOPE();- }- }-- Optional<ECPublicKey> public_key;- if (!decoder.eof()) {- auto tag = TRY(decoder.peek());- if (static_cast<u8>(tag.kind) == 1) {- REWRITE_TAG(Sequence);- ENTER_TYPED_SCOPE(Sequence, "publicKey");- READ_OBJECT(BitString, Crypto::ASN1::BitStringView, public_key_bits);-- auto public_key_bytes = TRY(public_key_bits.raw_bytes());- auto maybe_public_key = ECPublicKey::from_octets(public_key_bytes);- if (maybe_public_key.is_error()) {- ERROR_WITH_SCOPE(maybe_public_key.release_error());- }-- keypair.public_key = maybe_public_key.release_value();- public_key = keypair.public_key;-- EXIT_SCOPE();- }- }+ErrorOr<ByteBuffer> ECPrivateKey::d_bytes() const+{+ return integer_parameter(m_key.ptr(), OSSL_PKEY_PARAM_PRIV_KEY, m_scalar_size);+}- auto private_key = ECPrivateKey::from_scalar(private_key_bytes.bytes(), move(parameters), move(public_key));- if (private_key.is_error()) {- ERROR_WITH_SCOPE(private_key.release_error());- }- keypair.private_key = private_key.release_value();+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);+}- EXIT_SCOPE();- return keypair;+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)diff --git a/Libraries/LibCrypto/PK/EC.h b/Libraries/LibCrypto/PK/EC.hindex fbab5e171df..a89a06280af 100644--- a/Libraries/LibCrypto/PK/EC.h+++ b/Libraries/LibCrypto/PK/EC.h@@ -50,6 +50,9 @@ public: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;@@ -77,18 +80,6 @@ private:Optional<ECPublicKey> m_public_key;};-struct ECKeyPair {- ECPublicKey public_key;- ECPrivateKey private_key;-};--class EC {-public:- using KeyPairType = ECKeyPair;-- static ErrorOr<KeyPairType> parse_ec_key(ReadonlyBytes der, bool is_private, Vector<StringView> current_scope);-};-struct ECDSASignature {ByteBuffer r;ByteBuffer s;diff --git a/Libraries/LibCrypto/PK/KeyInfo.cpp b/Libraries/LibCrypto/PK/KeyInfo.cppnew file mode 100644index 00000000000..8764a10da9c--- /dev/null+++ b/Libraries/LibCrypto/PK/KeyInfo.cpp@@ -0,0 +1,267 @@+/*+ * 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.hnew file mode 100644index 00000000000..cf770d46efb--- /dev/null+++ b/Libraries/LibCrypto/PK/KeyInfo.h@@ -0,0 +1,49 @@+/*+ * 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/ModuleLatticePrivateKey.cpp b/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.cppindex 4e7d14ca2ff..25374bc111c 100644--- a/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.cpp+++ b/Libraries/LibCrypto/PK/ModuleLatticePrivateKey.cpp@@ -4,26 +4,38 @@* 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 {-static ErrorOr<void> expect_tag(ASN1::Decoder& decoder, ASN1::Class class_, ASN1::Kind kind, ASN1::Type type)-{- auto tag = TRY(decoder.peek());- if (tag.class_ != class_ || tag.kind != kind || tag.type != type)- return Error::from_string_literal("Unexpected tag in private key");- return {};-}+enum class Choice {+ Seed,+ ExpandedKey,+ Both,+};-static ErrorOr<ReadonlyBytes> read_octet_string(ASN1::Decoder& decoder, ASN1::Class class_, ASN1::Kind kind, size_t size)+static ErrorOr<ByteBuffer> encode(Choice choice, ReadonlyBytes seed, ReadonlyBytes expanded_key){- TRY(expect_tag(decoder, class_, kind, ASN1::Type::Primitive));- auto contents = TRY(decoder.read<StringView>(ASN1::Class::Universal, ASN1::Kind::OctetString));- if (contents.length() != size)- return Error::from_string_literal("Unexpected size of an OCTET STRING in private key");- return contents.bytes();+ 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@@ -38,27 +50,36 @@ ErrorOr<ModuleLatticePrivateKey> parse_module_lattice_private_key(ReadonlyBytes// expandedKey OCTET STRING (SIZE (expanded_key_size))// }// }- ASN1::Decoder decoder { der };- ModuleLatticePrivateKey key;+ // 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;- auto tag = TRY(decoder.peek());- if (tag.class_ == ASN1::Class::Context) {- key.seed = TRY(read_octet_string(decoder, ASN1::Class::Context, static_cast<ASN1::Kind>(0), seed_size));- } else if (tag.kind == ASN1::Kind::OctetString) {- key.expanded_key = TRY(read_octet_string(decoder, ASN1::Class::Universal, ASN1::Kind::OctetString, expanded_key_size));- } else {- TRY(expect_tag(decoder, ASN1::Class::Universal, ASN1::Kind::Sequence, ASN1::Type::Constructed));- TRY(decoder.enter());- key.seed = TRY(read_octet_string(decoder, ASN1::Class::Universal, ASN1::Kind::OctetString, seed_size));- key.expanded_key = TRY(read_octet_string(decoder, ASN1::Class::Universal, ASN1::Kind::OctetString, expanded_key_size));- if (!decoder.eof())- return Error::from_string_literal("Trailing data in private key");- TRY(decoder.leave());- }+ 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;+ }- if (!decoder.eof())- return Error::from_string_literal("Trailing data after private key");- return key;+ 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/RSA.cpp b/Libraries/LibCrypto/PK/RSA.cppindex a558db443d7..c19445c625e 100644--- a/Libraries/LibCrypto/PK/RSA.cpp+++ b/Libraries/LibCrypto/PK/RSA.cpp@@ -9,8 +9,6 @@#include <AK/Memory.h>#include <AK/NumericLimits.h>#include <AK/ScopeGuard.h>-#include <LibCrypto/ASN1/DER.h>-#include <LibCrypto/Certificate/Certificate.h>#include <LibCrypto/OpenSSL.h>#include <LibCrypto/PK/RSA.h>@@ -23,14 +21,6 @@namespace Crypto::PK {-static ErrorOr<ByteBuffer> integer_bytes(UnsignedBigInteger const& integer)-{- auto bytes = TRY(ByteBuffer::create_uninitialized(integer.byte_length()));- auto written = integer.export_data(bytes.span());- VERIFY(written.size() == bytes.size());- return bytes;-}-static ErrorOr<ByteBuffer> integer_parameter(EVP_PKEY* key, char const* name){BIGNUM* value = nullptr;@@ -190,6 +180,14 @@ ErrorOr<RSAPrivateKey> RSAPrivateKey::from_components(ReadonlyBytes modulus, Reareturn 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());@@ -257,91 +255,6 @@ ErrorOr<ByteBuffer> RSAPrivateKey::export_as_der() constreturn export_type_specific_der(m_key.ptr(), true);}-ErrorOr<RSA::KeyPairType> RSA::parse_rsa_key(ReadonlyBytes der, bool is_private, Vector<StringView> current_scope)-{- KeyPairType keypair;-- ASN1::Decoder decoder(der);-- if (is_private) {- // RSAPrivateKey ::= SEQUENCE {- // version Version,- // modulus INTEGER,- // publicExponent INTEGER,- // privateExponent INTEGER,- // prime1 INTEGER,- // prime2 INTEGER,- // exponent1 INTEGER,- // exponent2 INTEGER,- // coefficient INTEGER,- // otherPrimeInfos OtherPrimeInfos OPTIONAL- // }-- ENTER_TYPED_SCOPE(Sequence, "RSAPrivateKey");-- PUSH_SCOPE("version");- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, version);- POP_SCOPE();- if (version != 0) {- ERROR_WITH_SCOPE(TRY(String::formatted("Invalid version value at {}", current_scope)));- }-- Array<ByteBuffer, 8> components;- ScopeGuard const clear_components = [&] {- for (auto& component : components)- secure_zero(component.data(), component.size());- };- for (auto& component : components) {- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, value);- component = TRY(integer_bytes(value));- }-- // NB: An RSAPrivateKey always has the second representation of RFC 8017, section 3.2, whose p, q, dP, dQ and- // qInv are positive, so a zero one makes the key invalid.- for (size_t i = 3; i < components.size(); ++i) {- if (components[i].is_empty())- ERROR_WITH_SCOPE("RSAPrivateKey has a zero prime factor or CRT value");- }-- RSACRTComponents crt_components { components[3], components[4], components[5], components[6], components[7] };- auto private_key = RSAPrivateKey::from_components(components[0], components[1], components[2], crt_components);- if (private_key.is_error()) {- ERROR_WITH_SCOPE(private_key.release_error());- }- keypair.private_key = private_key.release_value();- keypair.public_key = TRY(keypair.private_key.public_key());-- EXIT_SCOPE();- return keypair;- }-- // RSAPublicKey ::= SEQUENCE {- // modulus INTEGER,- // publicExponent INTEGER- // }-- ENTER_TYPED_SCOPE(Sequence, "RSAPublicKey");-- PUSH_SCOPE("modulus");- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, modulus);- POP_SCOPE();-- PUSH_SCOPE("publicExponent");- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, public_exponent);- POP_SCOPE();-- auto modulus_bytes = TRY(integer_bytes(modulus));- auto public_exponent_bytes = TRY(integer_bytes(public_exponent));- auto public_key = RSAPublicKey::from_components(modulus_bytes, public_exponent_bytes);- if (public_key.is_error()) {- ERROR_WITH_SCOPE(public_key.release_error());- }- keypair.public_key = public_key.release_value();-- EXIT_SCOPE();- return keypair;-}-ErrorOr<void> RSA::validate_key_generation_parameters(size_t bits){// OpenSSL refuses to generate keys with shorter moduli.diff --git a/Libraries/LibCrypto/PK/RSA.h b/Libraries/LibCrypto/PK/RSA.hindex 8cf9fea13b8..46110ed9b83 100644--- a/Libraries/LibCrypto/PK/RSA.h+++ b/Libraries/LibCrypto/PK/RSA.h@@ -23,6 +23,7 @@ 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;@@ -68,6 +69,7 @@ public: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;@@ -103,7 +105,6 @@ class RSA {public:using KeyPairType = RSAKeyPair;- static ErrorOr<KeyPairType> parse_rsa_key(ReadonlyBytes der, bool is_private, Vector<StringView> current_scope);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);diff --git a/Libraries/LibCrypto/RustBindings.cpp b/Libraries/LibCrypto/RustBindings.cppindex 8dccd6a4dc9..aa9f07ea0ae 100644--- a/Libraries/LibCrypto/RustBindings.cpp+++ b/Libraries/LibCrypto/RustBindings.cpp@@ -17,7 +17,6 @@#include <LibCrypto/ASN1/DER.h>#include <LibCrypto/Authentication/HMAC.h>#include <LibCrypto/Authentication/KMAC.h>-#include <LibCrypto/Certificate/Certificate.h>#include <LibCrypto/Cipher/AES.h>#include <LibCrypto/Cipher/ChaCha.h>#include <LibCrypto/Curves/EdwardsCurve.h>@@ -28,6 +27,7 @@#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>@@ -42,9 +42,9 @@ struct Asn1Storage final {T value;};-using SubjectPublicKeyStorage = Asn1Storage<Certificate::SubjectPublicKey>;-using PrivateKeyStorage = Asn1Storage<Certificate::PrivateKey>;-using OctetStringStorage = Asn1Storage<StringView>;+using SubjectPublicKeyStorage = Asn1Storage<PK::SubjectPublicKeyInfo>;+using PrivateKeyStorage = Asn1Storage<PK::PrivateKeyInfo>;+using OctetStringStorage = Asn1Storage<ReadonlyBytes>;extern "C" {using ReceiveEncodedBytes = void (*)(void*, ReadonlyBytes);@@ -66,31 +66,31 @@ static bool receive_byte_result(ErrorOr<ByteBuffer> const& result, void* state,FlatPtr crypto_decode_asn1_structure(ReadonlyBytes data, Asn1Structure structure, void* out, bool* all_consumed){- ::Crypto::ASN1::Decoder decoder(data);+ size_t consumed = 0;switch (structure) {case Asn1Structure::SubjectPublicKeyInfo: {- auto subject_public_key = ::Crypto::Certificate::parse_subject_public_key_info(decoder);+ 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::Certificate::parse_private_key_info(decoder);+ 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 = decoder.read<StringView>(::Crypto::ASN1::Class::Universal, ::Crypto::ASN1::Kind::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 = decoder.eof();+ *all_consumed = consumed == data.size();return 0;}@@ -504,7 +504,7 @@ FlatPtr crypto_ec_compute_coordinate(EcCurve curve, KeyHandle const* key, KeyHanreturn 0;}-static ::Crypto::Certificate::AlgorithmIdentifier const& key_info_algorithm(Asn1Structure structure, void const* key_info)+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;@@ -728,7 +728,7 @@ void crypto_asn1_key_info_raw_key(Asn1Structure structure, void const* key_info,void crypto_asn1_octet_string_bytes(OctetStringStorage const* string, ReadonlyBytes* bytes){- *bytes = string->value.bytes();+ *bytes = string->value;}bool crypto_okp_export_der(OkpCurve curve, bool is_public, ReadonlyBytes key, void* state, ReceiveEncodedBytes receive)diff --git a/Meta/Fuzzers/FuzzRSAKeyParsing.cpp b/Meta/Fuzzers/FuzzRSAKeyParsing.cppdeleted file mode 100644index 2360cbbfca9..00000000000--- a/Meta/Fuzzers/FuzzRSAKeyParsing.cpp+++ /dev/null@@ -1,17 +0,0 @@-/*- * Copyright (c) 2021, the SerenityOS developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/PK/RSA.h>-#include <stddef.h>-#include <stdint.h>--extern "C" int LLVMFuzzerTestOneInput(uint8_t const* data, size_t size)-{- AK::set_debug_enabled(false);- (void)Crypto::PK::RSA::parse_rsa_key({ data, size }, true, {});- (void)Crypto::PK::RSA::parse_rsa_key({ data, size }, false, {});- return 0;-}diff --git a/Meta/Fuzzers/fuzzers.cmake b/Meta/Fuzzers/fuzzers.cmakeindex c12b962c532..6bcc3dbdb84 100644--- a/Meta/Fuzzers/fuzzers.cmake+++ b/Meta/Fuzzers/fuzzers.cmake@@ -9,7 +9,6 @@ set(FUZZER_TARGETSMatroskaReaderPNGLoaderRegexECMA262- RSAKeyParsingTextDecoderURLWasmParser@@ -30,7 +29,6 @@ set(FUZZER_DEPENDENCIES_Js LibJSStandalone LibGC)set(FUZZER_DEPENDENCIES_MatroskaReader LibMedia)set(FUZZER_DEPENDENCIES_PNGLoader LibGfx LibImageDecoders)set(FUZZER_DEPENDENCIES_RegexECMA262 LibRegex)-set(FUZZER_DEPENDENCIES_RSAKeyParsing LibCrypto)set(FUZZER_DEPENDENCIES_TextDecoder LibTextCodec)set(FUZZER_DEPENDENCIES_URL LibURL)set(FUZZER_DEPENDENCIES_WasmParser LibWasm)diff --git a/Tests/LibCrypto/TestRSA.cpp b/Tests/LibCrypto/TestRSA.cppindex f581a826f8c..0a6627c3778 100644--- a/Tests/LibCrypto/TestRSA.cpp+++ b/Tests/LibCrypto/TestRSA.cpp@@ -6,8 +6,9 @@*/#include <AK/Base64.h>-#include <LibCrypto/Certificate/Certificate.h>+#include <LibCrypto/ASN1/Constants.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>@@ -59,11 +60,14 @@ TEST_CASE(test_RSA_ASN1_PKCS1_DER_parse)"hjMnlORkGSdvWlTHUj6gjEOh4TlWeJzQoQIgAxMZOQKtxCZUuxFwzRq4xLRGnrDlBQpuxz7bwSyQO7UCIHrYMnDohgNbwtA5ZpW3""H1cKKQQvueWm6sxW9P5sUrZ3"sv));- auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::parse_rsa_key(der, true, {}));- if (to_integer(TRY_OR_FAIL(keypair.public_key.public_exponent())) != 65537) {+ // 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 (to_integer(TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PublicExponent))) != 65537) {FAIL("Invalid public exponent");}- if (to_integer(TRY_OR_FAIL(keypair.private_key.component(Crypto::PK::RSAPrivateKey::Component::PrivateExponent))) != "4234603516465654167360850580101327813936403862038934287300450163438938741499875303761385527882335478349599685406941909381269804396099893549838642251053393"_bigint) {+ if (to_integer(TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PrivateExponent))) != "4234603516465654167360850580101327813936403862038934287300450163438938741499875303761385527882335478349599685406941909381269804396099893549838642251053393"_bigint) {FAIL("Invalid private exponent");}}@@ -90,8 +94,8 @@ TEST_CASE(test_RSA_ASN1_PKCS8_DER_parse)"UEZt2dS/xSUempqVqFGONpP87gvqxkMTtgCA73KXn/cxHWM2kmXyHA3kQlOYw6WHjpldQAxLE+TRHXO2JUtZ09Mu4rVXX7lmwbTm""l3vmuDEF3/Bo1C1HTg0xRV/l"sv));- auto decoder = Crypto::ASN1::Decoder { der };- auto private_key = TRY_OR_FAIL(Crypto::Certificate::parse_private_key_info(decoder, {})).rsa;+ size_t consumed = 0;+ auto private_key = TRY_OR_FAIL(Crypto::PK::parse_private_key_info(der, consumed)).rsa;if (to_integer(TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PublicExponent))) != 65537) {FAIL("Invalid public exponent");}@@ -109,15 +113,14 @@ TEST_CASE(test_RSA_keygen_enc)"Giklu4qx48/fYt8Cv6z6JuQ0ZQExAiEA9XRZVUnCJ2xOcCFCbyIF+d3F9Kht5rR77F9KsRlgUbkCIQDuQ7YzLpQ8V8BJwKbDeXw1""vQvcPEnyKnTOoALpF6bqRwIhAIDSm8Ajgf7m3RQEoLVrCe/l8WtCqsuWliOsr6rbQq4hAiEAx8R16wvOtZlNW4jvSU1+WwAaBZl2""1lfKf8OhLRXrmNkCIG9IRdcSiNR/Ut8QfD3N9Bb1HsUm+Bvzc8yGzl89pYST"sv));- auto decoder = Crypto::ASN1::Decoder { der };- auto priv_key_info = MUST(Crypto::Certificate::parse_private_key_info(decoder, {}));- auto keypair = MUST(Crypto::PK::RSA::parse_rsa_key(priv_key_info.raw_key, true, {}));- auto rsa_encryption_oid = Array<u32, 7> { 1, 2, 840, 113549, 1, 1, 1 };- auto wrapped_priv_der = MUST(Crypto::PK::wrap_in_private_key_info(priv_key_info.raw_key, rsa_encryption_oid, nullptr));+ 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(keypair.public_key, Crypto::Hash::HashKind::SHA1, {}, "WellHelloFriends"sv.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);diff --git a/Tests/LibTLS/TestTLSCertificateParser.cpp b/Tests/LibTLS/TestTLSCertificateParser.cppindex 3527dc9629d..43027594909 100644--- a/Tests/LibTLS/TestTLSCertificateParser.cpp+++ b/Tests/LibTLS/TestTLSCertificateParser.cpp@@ -6,7 +6,7 @@#include <AK/Base64.h>#include <LibCrypto/ASN1/Constants.h>-#include <LibCrypto/Certificate/Certificate.h>+#include <LibCrypto/PK/KeyInfo.h>#include <LibTest/TestCase.h>TEST_CASE(test_ed25519_private_key_length)@@ -15,8 +15,8 @@ TEST_CASE(test_ed25519_private_key_length)0x30, 0x0e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,0x03, 0x2b, 0x65, 0x70, 0x04, 0x02, 0x04, 0x00};- Crypto::ASN1::Decoder invalid_key_decoder(invalid_key_der);- EXPECT(Crypto::Certificate::parse_private_key_info(invalid_key_decoder).is_error());+ 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,@@ -26,8 +26,7 @@ TEST_CASE(test_ed25519_private_key_length)0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};- Crypto::ASN1::Decoder valid_key_decoder(valid_key_der);- EXPECT(!Crypto::Certificate::parse_private_key_info(valid_key_decoder).is_error());+ EXPECT(!Crypto::PK::parse_private_key_info(valid_key_der, consumed).is_error());}TEST_CASE(test_private_key_info_decode)@@ -45,8 +44,8 @@ TEST_CASE(test_private_key_info_decode)auto decoded_keyder = TRY_OR_FAIL(decode_base64(keyder));- Crypto::ASN1::Decoder decoder(decoded_keyder);- auto private_key_info = TRY_OR_FAIL(Crypto::Certificate::parse_private_key_info(decoder));+ 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;diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-pkcs8-compressed-public-key.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-pkcs8-compressed-public-key.txtnew file mode 100644index 00000000000..dbd8db7f6b2--- /dev/null+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-EC-pkcs8-compressed-public-key.txt@@ -0,0 +1,2 @@+compressed: imported, y T-NC4v4af5uO5-tKfA-eFivOM1drMV7Oy7ZAaDe_UfU+compressed with the wrong parity: DataErrordiff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.txtindex f96d98c6f95..d9e0b3d3be3 100644--- a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.txt+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.txt@@ -1,3 +1,5 @@a valid key: imported, encapsulated800 bytes of 0xff: imported, encapsulate OperationError799 bytes: imported, encapsulate OperationError+a valid key in SPKI: imported, encapsulated+800 bytes of 0xff in SPKI: imported, encapsulate OperationErrordiff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-pkcs8-three-primes.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-pkcs8-three-primes.txtnew file mode 100644index 00000000000..a3a68b80081--- /dev/null+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-pkcs8-three-primes.txt@@ -0,0 +1 @@+DataErrordiff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-ec-bad-import-key.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-ec-bad-import-key.txtindex 5d0c6646885..9fd275790d1 100644--- a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-ec-bad-import-key.txt+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-ec-bad-import-key.txt@@ -1,30 +1,30 @@ECDSA P-256 PUB - jwk OK: DataError: Invalid key-ECDSA P-256 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public key+ECDSA P-256 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: Invalid or unsupported public keyECDSA P-256 PRIV - jwk OK: DataError: Invalid key-ECDSA P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key-ECDSA P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public key+ECDSA P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid ECPrivateKey+ECDSA P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid or unsupported private keyECDSA P-384 PUB - jwk OK: DataError: Invalid key-ECDSA P-384 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public key+ECDSA P-384 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: Invalid or unsupported public keyECDSA P-384 PRIV - jwk OK: DataError: Invalid key-ECDSA P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key-ECDSA P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public key+ECDSA P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid ECPrivateKey+ECDSA P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid or unsupported private keyECDSA P-521 PUB - jwk OK: DataError: Invalid key-ECDSA P-521 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public key+ECDSA P-521 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: Invalid or unsupported public keyECDSA P-521 PRIV - jwk OK: DataError: Invalid key-ECDSA P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key-ECDSA P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public key+ECDSA P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid ECPrivateKey+ECDSA P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid or unsupported private keyECDH P-256 PUB - jwk OK: DataError: Invalid key-ECDH P-256 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public key+ECDH P-256 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: Invalid or unsupported public keyECDH P-256 PRIV - jwk OK: DataError: Invalid key-ECDH P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key-ECDH P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public key+ECDH P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid ECPrivateKey+ECDH P-256 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid or unsupported private keyECDH P-384 PUB - jwk OK: DataError: Invalid key-ECDH P-384 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public key+ECDH P-384 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: Invalid or unsupported public keyECDH P-384 PRIV - jwk OK: DataError: Invalid key-ECDH P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key-ECDH P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public key+ECDH P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid ECPrivateKey+ECDH P-384 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid or unsupported private keyECDH P-521 PUB - jwk OK: DataError: Invalid key-ECDH P-521 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: [ "SubjectPublicKeyInfo" ]: [ "SubjectPublicKeyInfo" ]: Invalid EC public key+ECDH P-521 PUB - spki OK: DataError: Error parsing subjectPublicKeyInfo: Invalid or unsupported public keyECDH P-521 PRIV - jwk OK: DataError: Invalid key-ECDH P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey" ]: EC public key does not match the private key-ECDH P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: [ "PrivateKeyInfo" ]: [ "PrivateKeyInfo", "ECPrivateKey", "publicKey" ]: Invalid EC public key+ECDH P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid ECPrivateKey+ECDH P-521 PRIV - pkcs8 OK: DataError: Error parsing privateKeyInfo: Invalid or unsupported private keydiff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-pkcs8-versions.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-pkcs8-versions.txtnew file mode 100644index 00000000000..3f77d51b94c--- /dev/null+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-pkcs8-versions.txt@@ -0,0 +1,5 @@+PrivateKeyInfo version 0: imported+PrivateKeyInfo version 1: DataError+RSAPrivateKey version 0: imported+RSAPrivateKey version 1: DataError+RSAPrivateKey version 2: DataErrordiff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-pkcs8-compressed-public-key.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-pkcs8-compressed-public-key.htmlnew file mode 100644index 00000000000..8f81a0facef--- /dev/null+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-EC-pkcs8-compressed-public-key.html@@ -0,0 +1,38 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ // A P-256 private key in PKCS#8 with d = 1, whose ECPrivateKey has its public key, the base point, in compressed form.+ const x = "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296";+ const pkcs8 = prefix =>+ "306702010030130607" ++ "2a8648ce3d020106082a8648ce3d030107044d304b020101" ++ "0420" ++ "00".repeat(31) ++ "01" ++ "a1240322" ++ "00" ++ prefix ++ x;++ promiseTest(async () => {+ const bytes = hex => Uint8Array.from(hex.match(/../g), byte => parseInt(byte, 16));+ for (const [name, prefix] of [+ ["compressed", "03"],+ ["compressed with the wrong parity", "02"],+ ]) {+ try {+ const key = await crypto.subtle.importKey(+ "pkcs8",+ bytes(pkcs8(prefix)),+ { name: "ECDSA", namedCurve: "P-256" },+ true,+ ["sign"]+ );+ const jwk = await crypto.subtle.exportKey("jwk", key);+ println(`${name}: imported, y ${jwk.y}`);+ } catch (error) {+ println(`${name}: ${error.name}`);+ }+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.htmlindex b1a0f157217..6d3561148fb 100644--- a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.html+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-MLKEM-encapsulation-key-check.html@@ -5,16 +5,19 @@const algorithm = { name: "ML-KEM-512" };const { publicKey } = await crypto.subtle.generateKey(algorithm, true, ["encapsulateBits", "decapsulateBits"]);const valid = new Uint8Array(await crypto.subtle.exportKey("raw-public", publicKey));+ const spki = new Uint8Array(await crypto.subtle.exportKey("spki", publicKey));const keys = [- ["a valid key", valid],- ["800 bytes of 0xff", new Uint8Array(800).fill(0xff)],- ["799 bytes", valid.slice(0, 799)],+ ["a valid key", "raw-public", valid],+ ["800 bytes of 0xff", "raw-public", new Uint8Array(800).fill(0xff)],+ ["799 bytes", "raw-public", valid.slice(0, 799)],+ ["a valid key in SPKI", "spki", spki],+ ["800 bytes of 0xff in SPKI", "spki", spki.slice().fill(0xff, spki.length - 800)],];- for (const [name, data] of keys) {+ for (const [name, format, data] of keys) {let key;try {- key = await crypto.subtle.importKey("raw-public", data, algorithm, true, ["encapsulateBits"]);+ key = await crypto.subtle.importKey(format, data, algorithm, true, ["encapsulateBits"]);} catch (error) {println(`${name}: import ${error.name}`);continue;diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-pkcs8-three-primes.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-pkcs8-three-primes.htmlnew file mode 100644index 00000000000..857ced40281--- /dev/null+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-pkcs8-three-primes.html@@ -0,0 +1,28 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ // A 1024-bit RSA private key in PKCS#8 with three primes, whose RSAPrivateKey has otherPrimeInfos.+ const key =+ "MIIClwIBADANBgkqhkiG9w0BAQEFAASCAoEwggJ9AgEBAoGBAJ7IzvkMlxCpXJLgCtoPPp0Wr3xovN6jZ4pxXO+24SO2sg31" ++ "fr41bdWT+mllETeO9N+iDF2LSP0q34uewWeKz78/3L8lGHitNtB64KIBXBwDPtbXd31kDBRSHis2iQ7DJrdHd4KOL45J2gRD" ++ "yDLc5cA6Z764Aqz4pgS09GL1jK+PAgMBAAECgYA5uoJdU7F8kkag86meXBqEnGHS1nWMcFZNpCeI07GI/XxAzPd2ihBTrUhB" ++ "YOfabTBdBwFnWbPPLdKGfHin00IVvz3YlYMKdLxUjHPr10Df8bhGpZmy9VfddjgHZwqq3xiCTrx5bkwmatSdOHo8mSO8ESXb" ++ "tvioU7eJt3qBQXrmyQIrMnNfNtixHCIEQjvoyLR6ksfPK9fBM+VUhFSxb3jIOfAVd1oPq6xES+imXwIrHNroS1MkyYJgWjEf" ++ "iTDiNrWS87JfsCROjlnJYp33XiCWOyJtKQtkauuOuwIrHwwG/U6u97wrWMNbhyAiCnAyGy4EdLZdo64nH4150sXfv/pJiIFT" ++ "6k77CwIrAf2wzZG9FhJi55ZAIM04rqG0tA/4vkSjDvtvA9j2eo4xD39+nLhmg2IhhQIrLg+PMIvV6vDiXmF3wrOc8GtmAnSf" ++ "P9k+VxjWbBpd4VHT3tiEqbiG3WrApjCBijCBhwIrG+w5Tb7OmtdoWhs04vv6y7zgbYa+e4JdjDs13lKx9BtvRT6iG99kZ0Jv" ++ "4wIrGM90u1fnTD5KQoYaH/W1ioJxB+DKMAROCuQxoTHpXPVjkStt70Y3eGjX8QIrCNRJ4hr3whJpRJQjq+HxwV+ifniM5wXb" ++ "4D68RYGyEVG67CD0NcHk2TTxCg==";++ promiseTest(async () => {+ const bytes = Uint8Array.from(atob(key), character => character.charCodeAt(0));+ try {+ await crypto.subtle.importKey("pkcs8", bytes, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, true, [+ "sign",+ ]);+ println("imported");+ } catch (error) {+ println(error.name);+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-pkcs8-versions.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-pkcs8-versions.htmlnew file mode 100644index 00000000000..a3f37960d9e--- /dev/null+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-pkcs8-versions.html@@ -0,0 +1,35 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const bytes = hex => Uint8Array.from(hex.match(/../g), byte => parseInt(byte, 16));+ const tryImport = async (name, data, algorithm) => {+ try {+ await crypto.subtle.importKey("pkcs8", data, algorithm, true, ["sign"]);+ println(`${name}: imported`);+ } catch (error) {+ println(`${name}: ${error.name}`);+ }+ };++ // An Ed25519 PrivateKeyInfo, and the same key as a version 1 OneAsymmetricKey without its public key.+ for (const version of [0, 1]) {+ const pkcs8 = bytes(`302e02010${version}300506032b657004220420` + "11".repeat(32));+ await tryImport(`PrivateKeyInfo version ${version}`, pkcs8, { name: "Ed25519" });+ }++ // An RSA key whose RSAPrivateKey version, after a two-byte length, is at offset 32.+ const algorithm = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };+ const { privateKey } = await crypto.subtle.generateKey(+ { ...algorithm, modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]) },+ true,+ ["sign"]+ );+ const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", privateKey));+ for (const version of [0, 1, 2]) {+ const copy = pkcs8.slice();+ copy[32] = version;+ await tryImport(`RSAPrivateKey version ${version}`, copy, algorithm);+ }+ });+</script>