Skip to content

Truly independent web browser

LibCrypto: Hold RSA keys as OpenSSL keys

Shannon Booth4f3a4685d1bd
diff --git a/Libraries/LibCrypto/KeyHandle.cpp b/Libraries/LibCrypto/KeyHandle.cpp
index 6cde161809b..9d4af9aec02 100644
--- a/Libraries/LibCrypto/KeyHandle.cpp
+++ b/Libraries/LibCrypto/KeyHandle.cpp
@@ -44,7 +44,6 @@ void crypto_key_destroy_handle(KeyHandle* handle)
[](ByteBuffer& data) { secure_zero(data.data(), data.size()); },
[](OKPPublicKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },
[](OKPPrivateKey& data) { secure_zero(data.bytes.data(), data.bytes.size()); },
- [](::Crypto::PK::RSAPrivateKey& data) { data.clear_sensitive_data(); },
[](::Crypto::PK::MLDSAPrivateKey& data) { data.clear_sensitive_data(); },
[](::Crypto::PK::MLKEMPrivateKey& data) { data.clear_sensitive_data(); },
[](auto&) { });
@@ -80,14 +79,6 @@ void crypto_key_okp_handle_bytes(KeyHandle const* handle, ReadonlyBytes* bytes)
static_assert(to_underlying(HandleTag::ECPrivateKey) == 4);
static_assert(to_underlying(HandleTag::OKPPrivateKey) == 10);
-static ByteBuffer export_big_integer(::Crypto::UnsignedBigInteger const& value)
-{
- auto buffer = MUST(ByteBuffer::create_zeroed(value.byte_length()));
- auto written = value.export_data(buffer.bytes());
- VERIFY(written.size() == buffer.size());
- return buffer;
-}
-
void crypto_key_encode_handle(KeyHandle const* handle, void* state, void (*steps)(void*, CryptoKeyHandleFields const*))
{
CryptoKeyHandleFields fields;
@@ -105,19 +96,15 @@ void crypto_key_encode_handle(KeyHandle const* handle, void* state, void (*steps
},
[&](::Crypto::PK::RSAPublicKey const& rsa_key) {
fields.handle_tag = to_underlying(HandleTag::RSAPublicKey);
- add_exported(export_big_integer(rsa_key.modulus()));
- add_exported(export_big_integer(rsa_key.public_exponent()));
+ 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);
- add_exported(export_big_integer(rsa_key.modulus()));
- add_exported(export_big_integer(rsa_key.private_exponent()));
- add_exported(export_big_integer(rsa_key.public_exponent()));
- add_exported(export_big_integer(rsa_key.prime1()));
- add_exported(export_big_integer(rsa_key.prime2()));
- add_exported(export_big_integer(rsa_key.exponent1()));
- add_exported(export_big_integer(rsa_key.exponent2()));
- add_exported(export_big_integer(rsa_key.coefficient()));
+ 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);
@@ -180,15 +167,19 @@ static ErrorOr<KeyHandle> handle_from_fields(CryptoKeyHandleFields const& fields
auto copy = [&](size_t index) -> ErrorOr<ByteBuffer> {
return TRY(ByteBuffer::copy(buffer(index)));
};
- auto big_integer = [&](size_t index) { return ::Crypto::UnsignedBigInteger::import_data(buffer(index)); };
switch (static_cast<HandleTag>(fields.handle_tag)) {
case HandleTag::ByteBuffer:
return TRY(copy(0));
case HandleTag::RSAPublicKey:
- return ::Crypto::PK::RSAPublicKey { big_integer(0), big_integer(1) };
- case HandleTag::RSAPrivateKey:
- return ::Crypto::PK::RSAPrivateKey { big_integer(0), big_integer(1), big_integer(2), big_integer(3), big_integer(4), big_integer(5), big_integer(6), big_integer(7) };
+ 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: {
diff --git a/Libraries/LibCrypto/PK/RSA.cpp b/Libraries/LibCrypto/PK/RSA.cpp
index 4905d58348e..a558db443d7 100644
--- a/Libraries/LibCrypto/PK/RSA.cpp
+++ b/Libraries/LibCrypto/PK/RSA.cpp
@@ -6,27 +6,255 @@
*/
#include <AK/ByteBuffer.h>
+#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>
+#include <openssl/bn.h>
#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 {
-void RSAPrivateKey::clear_sensitive_data()
+static ErrorOr<ByteBuffer> integer_bytes(UnsignedBigInteger const& integer)
{
- m_private_exponent.clear_sensitive_data();
- m_prime_1.clear_sensitive_data();
- m_prime_2.clear_sensitive_data();
- m_exponent_1.clear_sensitive_data();
- m_exponent_2.clear_sensitive_data();
- m_coefficient.clear_sensitive_data();
+ 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;
+ 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);
+ AK_MAKE_NONMOVABLE(ParameterBuilder);
+
+public:
+ ParameterBuilder() = default;
+
+ ~ParameterBuilder()
+ {
+ OSSL_PARAM_BLD_free(m_builder);
+ for (auto* integer : m_integers)
+ BN_clear_free(integer);
+ }
+
+ ErrorOr<void> push_integer(char const* name, ReadonlyBytes bytes, bool secret)
+ {
+ if (!m_builder)
+ m_builder = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());
+
+ auto* integer = OPENSSL_TRY_PTR(secret ? BN_secure_new() : BN_new());
+ TRY(m_integers.try_append(integer));
+ OPENSSL_TRY_PTR(BN_bin2bn(bytes.data(), bytes.size(), integer));
+ OPENSSL_TRY(OSSL_PARAM_BLD_push_BN(m_builder, name, integer));
+ 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:
+ OSSL_PARAM_BLD* m_builder { nullptr };
+ Vector<BIGNUM*, 8> m_integers;
+};
+
+static ErrorOr<OpenSSL_SharedPKEY> key_from_parameters(int selection, ParameterBuilder& builder)
+{
+ auto* params = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_to_param(builder.ptr()));
+ ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };
+
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr)));
+ OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));
+
+ EVP_PKEY* key = nullptr;
+ OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key, selection, params));
+ return OpenSSL_SharedPKEY { TRY(OpenSSL_PKEY::wrap(key)) };
+}
+
+// https://www.rfc-editor.org/rfc/rfc8017#section-3.1
+// [...] the RSA public exponent e is an integer between 3 and n - 1 [...]
+// NB: An odd e above 1 is at least 3.
+static ErrorOr<bool> public_exponent_is_valid(EVP_PKEY* key)
+{
+ BIGNUM* n = nullptr;
+ BIGNUM* e = nullptr;
+ ScopeGuard const free_values = [&] {
+ BN_free(n);
+ BN_free(e);
+ };
+ OPENSSL_TRY(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_RSA_N, &n));
+ OPENSSL_TRY(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_RSA_E, &e));
+ 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()))
+{
+}
+
+ErrorOr<RSAPublicKey> RSAPublicKey::from_components(ReadonlyBytes modulus, ReadonlyBytes public_exponent)
+{
+ 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));
+ return 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())))
+ return false;
+
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, m_key.ptr(), nullptr)));
+ return 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() };
+}
+
+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<RSA::KeyPairType> RSA::parse_rsa_key(ReadonlyBytes der, bool is_private, Vector<StringView> current_scope)
@@ -58,73 +286,60 @@ ErrorOr<RSA::KeyPairType> RSA::parse_rsa_key(ReadonlyBytes der, bool is_private,
ERROR_WITH_SCOPE(TRY(String::formatted("Invalid version value at {}", current_scope)));
}
- PUSH_SCOPE("modulus");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, modulus);
- POP_SCOPE();
-
- PUSH_SCOPE("publicExponent");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, public_exponent);
- POP_SCOPE();
-
- PUSH_SCOPE("privateExponent");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, private_exponent);
- POP_SCOPE();
-
- PUSH_SCOPE("prime1");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, prime1);
- POP_SCOPE();
-
- PUSH_SCOPE("prime2");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, prime2);
- POP_SCOPE();
-
- PUSH_SCOPE("exponent1");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, exponent1);
- POP_SCOPE();
-
- PUSH_SCOPE("exponent2");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, exponent2);
- POP_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));
+ }
- PUSH_SCOPE("coefficient");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, coefficient);
- POP_SCOPE();
+ // 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");
+ }
- keypair.private_key = {
- modulus,
- private_exponent,
- public_exponent,
- prime1,
- prime2,
- exponent1,
- exponent2,
- coefficient,
- };
- keypair.public_key = { modulus, public_exponent };
+ 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;
- } else {
- // RSAPublicKey ::= SEQUENCE {
- // modulus INTEGER,
- // publicExponent INTEGER
- // }
+ }
- ENTER_TYPED_SCOPE(Sequence, "RSAPublicKey");
+ // RSAPublicKey ::= SEQUENCE {
+ // modulus INTEGER,
+ // publicExponent INTEGER
+ // }
- PUSH_SCOPE("modulus");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, modulus);
- POP_SCOPE();
+ ENTER_TYPED_SCOPE(Sequence, "RSAPublicKey");
- PUSH_SCOPE("publicExponent");
- READ_OBJECT(Integer, Crypto::UnsignedBigInteger, public_exponent);
- POP_SCOPE();
+ PUSH_SCOPE("modulus");
+ READ_OBJECT(Integer, Crypto::UnsignedBigInteger, modulus);
+ POP_SCOPE();
- keypair.public_key = { move(modulus), move(public_exponent) };
+ PUSH_SCOPE("publicExponent");
+ READ_OBJECT(Integer, Crypto::UnsignedBigInteger, public_exponent);
+ POP_SCOPE();
- EXIT_SCOPE();
- return keypair;
+ 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)
@@ -141,227 +356,33 @@ ErrorOr<void> RSA::validate_key_generation_parameters(size_t bits)
return {};
}
-ErrorOr<RSA::KeyPairType> RSA::generate_key_pair(size_t bits, UnsignedBigInteger e)
+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()));
- auto e_bn = TRY(unsigned_big_integer_to_openssl_bignum(e));
-
- auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());
- ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); };
+ ParameterBuilder builder;
+ TRY(builder.push_size(OSSL_PKEY_PARAM_RSA_BITS, bits));
+ TRY(builder.push_integer(OSSL_PKEY_PARAM_RSA_E, public_exponent, false));
- OPENSSL_TRY(OSSL_PARAM_BLD_push_size_t(params_bld, OSSL_PKEY_PARAM_RSA_BITS, bits));
- OPENSSL_TRY(OSSL_PARAM_BLD_push_BN(params_bld, OSSL_PKEY_PARAM_RSA_E, e_bn.ptr()));
-
- auto* params = OSSL_PARAM_BLD_to_param(params_bld);
+ 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));
- auto key = TRY(OpenSSL_PKEY::create());
- auto* key_ptr = key.ptr();
- OPENSSL_TRY(EVP_PKEY_generate(ctx.ptr(), &key_ptr));
-
-#define OPENSSL_GET_KEY_PARAM(param, openssl_name) \
- auto param##_bn = TRY(OpenSSL_BN::create()); \
- auto* param##_bn_ptr = param##_bn.ptr(); \
- OPENSSL_TRY(EVP_PKEY_get_bn_param(key.ptr(), openssl_name, &param##_bn_ptr)); \
- auto param = TRY(openssl_bignum_to_unsigned_big_integer(param##_bn));
-
- OPENSSL_GET_KEY_PARAM(n, OSSL_PKEY_PARAM_RSA_N);
- OPENSSL_GET_KEY_PARAM(d, OSSL_PKEY_PARAM_RSA_D);
- OPENSSL_GET_KEY_PARAM(p, OSSL_PKEY_PARAM_RSA_FACTOR1);
- OPENSSL_GET_KEY_PARAM(q, OSSL_PKEY_PARAM_RSA_FACTOR2);
- OPENSSL_GET_KEY_PARAM(dp, OSSL_PKEY_PARAM_RSA_EXPONENT1);
- OPENSSL_GET_KEY_PARAM(dq, OSSL_PKEY_PARAM_RSA_EXPONENT2);
- OPENSSL_GET_KEY_PARAM(qinv, OSSL_PKEY_PARAM_RSA_COEFFICIENT1);
-
-#undef OPENSSL_GET_KEY_PARAM
-
- KeyPairType keys {
- { n, e },
- { n, d, e, p, q, dp, dq, qinv }
- };
- return keys;
-}
-
-#define OPENSSL_SET_KEY_PARAM_NOT_ZERO(param, openssl_name, value) \
- auto param##_bn = TRY(unsigned_big_integer_to_openssl_bignum(value)); \
- if (!value.is_zero()) { \
- OPENSSL_TRY(OSSL_PARAM_BLD_push_BN(params_bld, openssl_name, param##_bn.ptr())); \
- }
-
-static ErrorOr<OpenSSL_PKEY> public_key_to_openssl_pkey(RSAPublicKey const& public_key)
-{
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr)));
-
- OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));
-
- auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());
- ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); };
+ EVP_PKEY* key = nullptr;
+ OPENSSL_TRY(EVP_PKEY_generate(ctx.ptr(), &key));
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(n, OSSL_PKEY_PARAM_RSA_N, public_key.modulus());
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(e, OSSL_PKEY_PARAM_RSA_E, public_key.public_exponent());
-
- auto* params = OSSL_PARAM_BLD_to_param(params_bld);
- ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };
-
- auto key = TRY(OpenSSL_PKEY::create());
- auto* key_ptr = key.ptr();
- OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key_ptr, EVP_PKEY_PUBLIC_KEY, params));
- return key;
-}
-
-static ErrorOr<OpenSSL_PKEY> private_key_to_openssl_pkey(RSAPrivateKey const& private_key)
-{
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr)));
-
- OPENSSL_TRY(EVP_PKEY_fromdata_init(ctx.ptr()));
-
- auto* params_bld = OPENSSL_TRY_PTR(OSSL_PARAM_BLD_new());
- ScopeGuard const free_params_bld = [&] { OSSL_PARAM_BLD_free(params_bld); };
-
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(n, OSSL_PKEY_PARAM_RSA_N, private_key.modulus());
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(e, OSSL_PKEY_PARAM_RSA_E, private_key.public_exponent());
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(d, OSSL_PKEY_PARAM_RSA_D, private_key.private_exponent());
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(p, OSSL_PKEY_PARAM_RSA_FACTOR1, private_key.prime1());
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(q, OSSL_PKEY_PARAM_RSA_FACTOR2, private_key.prime2());
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(dp, OSSL_PKEY_PARAM_RSA_EXPONENT1, private_key.exponent1());
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(dq, OSSL_PKEY_PARAM_RSA_EXPONENT2, private_key.exponent2());
- OPENSSL_SET_KEY_PARAM_NOT_ZERO(qinv, OSSL_PKEY_PARAM_RSA_COEFFICIENT1, private_key.coefficient());
-
- auto* params = OSSL_PARAM_BLD_to_param(params_bld);
- ScopeGuard const free_params = [&] { OSSL_PARAM_free(params); };
-
- auto key = TRY(OpenSSL_PKEY::create());
- auto* key_ptr = key.ptr();
- OPENSSL_TRY(EVP_PKEY_fromdata(ctx.ptr(), &key_ptr, EVP_PKEY_KEYPAIR, params));
- return key;
-}
-
-#undef OPENSSL_SET_KEY_PARAM_NOT_ZERO
-
-// https://www.rfc-editor.org/rfc/rfc3447.html#section-3.1
-ErrorOr<bool> RSAPublicKey::is_valid() const
-{
- // In a valid RSA public key, the RSA modulus n is a product of u
- // distinct odd primes r_i, i = 1, 2, ..., u, where u >= 2, and the RSA
- // public exponent e is an integer between 3 and n - 1 satisfying GCD(e,
- // \lambda(n)) = 1, where \lambda(n) = LCM(r_1 - 1, ..., r_u - 1).
-
- if (!m_public_exponent.is_odd())
- return false;
-
- if (m_public_exponent < 3 || m_public_exponent >= m_modulus)
- return false;
-
- return true;
+ 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) };
}
-// https://www.rfc-editor.org/rfc/rfc3447.html#section-3.2
-ErrorOr<bool> RSAPrivateKey::is_valid() const
+ErrorOr<RSA::KeyPairType> RSA::generate_key_pair(size_t bits)
{
- if (!m_public_exponent.is_odd())
- return false;
-
- if (m_public_exponent < 3 || m_public_exponent >= m_modulus)
- return false;
-
- if (!m_prime_1.is_zero() && !m_prime_2.is_zero() && !m_exponent_1.is_zero() && !m_exponent_2.is_zero() && !m_coefficient.is_zero()) {
- // In a valid RSA private key with the second representation, the two
- // factors p and q are the first two prime factors of the RSA modulus n
- // (i.e., r_1 and r_2), the CRT exponents dP and dQ are positive
- // integers less than p and q respectively satisfying
- // e * dP == 1 (mod (p-1))
- // e * dQ == 1 (mod (q-1)) ,
- // and the CRT coefficient qInv is a positive integer less than p
- // satisfying
- // q * qInv == 1 (mod p).
- // If u > 2, the representation will include one or more triplets (r_i,
- // d_i, t_i), i = 3, ..., u. The factors r_i are the additional prime
- // factors of the RSA modulus n. Each CRT exponent d_i (i = 3, ..., u)
- // satisfies
- // e * d_i == 1 (mod (r_i - 1)).
- // Each CRT coefficient t_i (i = 3, ..., u) is a positive integer less
- // than r_i satisfying
- // R_i * t_i == 1 (mod r_i) ,
- // where R_i = r_1 * r_2 * ... * r_(i-1).
-
- if (m_exponent_1 >= m_prime_1 || m_exponent_2 >= m_prime_2 || m_coefficient >= m_prime_1)
- return false;
-
- if (m_prime_1.multiplied_by(m_prime_2) != m_modulus)
- return false;
-
- auto tmp_bn = TRY(OpenSSL_BN::create());
-
- auto e = TRY(unsigned_big_integer_to_openssl_bignum(m_public_exponent)),
- p = TRY(unsigned_big_integer_to_openssl_bignum(m_prime_1)),
- q = TRY(unsigned_big_integer_to_openssl_bignum(m_prime_2));
-
- auto dp = TRY(unsigned_big_integer_to_openssl_bignum(m_exponent_1)),
- dq = TRY(unsigned_big_integer_to_openssl_bignum(m_exponent_2));
-
- auto* bn_ctx = OPENSSL_TRY_PTR(BN_CTX_new());
- ScopeGuard const free_bn_ctx = [&] { BN_CTX_free(bn_ctx); };
-
- auto p1 = TRY(OpenSSL_BN::create());
- OPENSSL_TRY(BN_sub(p1.ptr(), p.ptr(), BN_value_one()));
-
- OPENSSL_TRY(BN_mod_mul(tmp_bn.ptr(), e.ptr(), dp.ptr(), p1.ptr(), bn_ctx));
- if (!BN_is_one(tmp_bn.ptr()))
- return false;
-
- auto q1 = TRY(OpenSSL_BN::create());
- OPENSSL_TRY(BN_sub(q1.ptr(), q.ptr(), BN_value_one()));
-
- OPENSSL_TRY(BN_mod_mul(tmp_bn.ptr(), e.ptr(), dq.ptr(), q1.ptr(), bn_ctx));
- if (!BN_is_one(tmp_bn.ptr()))
- return false;
-
- auto q_inv = TRY(unsigned_big_integer_to_openssl_bignum(m_coefficient));
- OPENSSL_TRY(BN_mod_mul(tmp_bn.ptr(), q.ptr(), q_inv.ptr(), p.ptr(), bn_ctx));
- if (!BN_is_one(tmp_bn.ptr()))
- return false;
-
- if (!m_private_exponent.is_zero()) {
- if (m_private_exponent >= m_modulus)
- return false;
-
- auto lambda = TRY(m_prime_1.minus(1)).lcm(TRY(m_prime_2.minus(1)));
- auto lambda_bn = TRY(unsigned_big_integer_to_openssl_bignum(lambda));
-
- auto d = TRY(unsigned_big_integer_to_openssl_bignum(m_private_exponent));
-
- OPENSSL_TRY(BN_mod_mul(tmp_bn.ptr(), d.ptr(), e.ptr(), lambda_bn.ptr(), bn_ctx));
- if (!BN_is_one(tmp_bn.ptr()))
- return false;
- }
-
- return true;
- }
-
- if (!m_modulus.is_zero() && !m_private_exponent.is_zero()) {
- // In a valid RSA private key with the first representation, the RSA
- // modulus n is the same as in the corresponding RSA public key and is
- // the product of u distinct odd primes r_i, i = 1, 2, ..., u, where u
- // >= 2. The RSA private exponent d is a positive integer less than n
- // satisfying
- // e * d == 1 (mod \lambda(n)),
- // where e is the corresponding RSA public exponent and \lambda(n) is
- // defined as in Section 3.1.
-
- if (m_private_exponent >= m_modulus)
- return false;
-
- return true;
- }
-
- return false;
+ 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)
@@ -382,8 +403,8 @@ static ErrorOr<Array<OSSL_PARAM, 5>> oaep_parameters(Hash::HashKind hash_kind, R
ErrorOr<ByteBuffer> rsa_oaep_encrypt(RSAPublicKey const& public_key, Hash::HashKind hash_kind, ReadonlyBytes label, ReadonlyBytes plaintext)
{
- auto key = TRY(public_key_to_openssl_pkey(public_key));
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.ptr(), nullptr)));
+ 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()));
@@ -401,8 +422,8 @@ ErrorOr<ByteBuffer> rsa_oaep_decrypt(RSAPrivateKey const& private_key, Hash::Has
if (ciphertext.size() != private_key.length())
return Error::from_string_literal("RSA ciphertext has an invalid length");
- auto key = TRY(private_key_to_openssl_pkey(private_key));
- auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new_from_pkey(nullptr, key.ptr(), nullptr)));
+ 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()));
@@ -411,16 +432,17 @@ ErrorOr<ByteBuffer> rsa_oaep_decrypt(RSAPrivateKey const& private_key, Hash::Has
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 out.slice(0, out_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 = TRY(private_key_to_openssl_pkey(private_key));
+ 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.ptr(), params));
+ 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()));
@@ -432,16 +454,17 @@ static ErrorOr<ByteBuffer> sign(RSAPrivateKey const& private_key, Hash::HashKind
static ErrorOr<bool> verify(RSAPublicKey const& public_key, Hash::HashKind hash_kind, OSSL_PARAM const* params, ReadonlyBytes message, ReadonlyBytes signature)
{
- if (!TRY(public_key.is_valid()))
+ if (signature.size() != public_key.length())
return false;
- if (signature.size() != public_key.length())
+ // NB: Keys are checked in full when they are imported, so this only keeps the rule on e, which is cheap.
+ if (!TRY(public_exponent_is_valid(public_key.openssl_key())))
return false;
- auto key = TRY(public_key_to_openssl_pkey(public_key));
+ auto* key = public_key.openssl_key();
auto ctx = TRY(OpenSSL_MD_CTX::create());
- OPENSSL_TRY(EVP_DigestVerifyInit_ex(ctx.ptr(), nullptr, TRY(Hash::openssl_digest_name(hash_kind)), nullptr, nullptr, key.ptr(), params));
+ OPENSSL_TRY(EVP_DigestVerifyInit_ex(ctx.ptr(), nullptr, TRY(Hash::openssl_digest_name(hash_kind)), nullptr, nullptr, key, params));
auto result = EVP_DigestVerify(ctx.ptr(), signature.data(), signature.size(), message.data(), message.size());
if (result == 1)
diff --git a/Libraries/LibCrypto/PK/RSA.h b/Libraries/LibCrypto/PK/RSA.h
index 8d105c7afb4..8cf9fea13b8 100644
--- a/Libraries/LibCrypto/PK/RSA.h
+++ b/Libraries/LibCrypto/PK/RSA.h
@@ -8,140 +8,105 @@
#pragma once
-#include <LibCrypto/ASN1/DER.h>
-#include <LibCrypto/BigInt/UnsignedBigInteger.h>
+#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>
-#include <LibCrypto/PK/PK.h>
+// NB: RSA key components are big-endian unsigned integers.
namespace Crypto::PK {
class RSAPublicKey {
public:
- RSAPublicKey(UnsignedBigInteger n, UnsignedBigInteger e)
- : m_modulus(move(n))
- , m_public_exponent(move(e))
- , m_length(m_modulus.byte_length())
- {
- }
-
- RSAPublicKey()
- : m_modulus(0)
- , m_public_exponent(0)
- {
- }
-
- UnsignedBigInteger const& modulus() const { return m_modulus; }
- UnsignedBigInteger const& public_exponent() const { return m_public_exponent; }
+ RSAPublicKey() = default;
+
+ static ErrorOr<RSAPublicKey> from_components(ReadonlyBytes modulus, ReadonlyBytes public_exponent);
+
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
- {
- ASN1::Encoder encoder;
- TRY(encoder.write_constructed(ASN1::Class::Universal, ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {
- TRY(encoder.write(m_modulus));
- TRY(encoder.write(m_public_exponent));
- return {};
- }));
+ ErrorOr<ByteBuffer> export_as_der() const;
- return encoder.finish();
- }
+ EVP_PKEY* openssl_key() const { return m_key.ptr(); }
private:
- UnsignedBigInteger m_modulus;
- UnsignedBigInteger m_public_exponent;
+ RSAPublicKey(OpenSSL_SharedPKEY key);
+
+ OpenSSL_SharedPKEY m_key;
size_t m_length { 0 };
};
+struct RSACRTComponents {
+ ReadonlyBytes prime1;
+ ReadonlyBytes prime2;
+ ReadonlyBytes exponent1;
+ ReadonlyBytes exponent2;
+ ReadonlyBytes coefficient;
+};
+
class RSAPrivateKey {
public:
- RSAPrivateKey(UnsignedBigInteger n, UnsignedBigInteger d, UnsignedBigInteger e)
- : m_modulus(move(n))
- , m_private_exponent(move(d))
- , m_public_exponent(move(e))
- , m_length(m_modulus.byte_length())
- {
- }
-
- RSAPrivateKey(UnsignedBigInteger n, UnsignedBigInteger d, UnsignedBigInteger e, UnsignedBigInteger p, UnsignedBigInteger q, UnsignedBigInteger dp, UnsignedBigInteger dq, UnsignedBigInteger qinv)
- : m_modulus(move(n))
- , m_private_exponent(move(d))
- , m_public_exponent(move(e))
- , m_prime_1(move(p))
- , m_prime_2(move(q))
- , m_exponent_1(move(dp))
- , m_exponent_2(move(dq))
- , m_coefficient(move(qinv))
- , m_length(m_modulus.byte_length())
- {
- }
+ // NB: The order matches libcrypto_rust's RsaJwkInteger.
+ enum class Component : u8 {
+ Modulus,
+ PublicExponent,
+ PrivateExponent,
+ Prime1,
+ Prime2,
+ Exponent1,
+ Exponent2,
+ Coefficient,
+ };
RSAPrivateKey() = default;
- UnsignedBigInteger const& modulus() const { return m_modulus; }
- void clear_sensitive_data();
+ static ErrorOr<RSAPrivateKey> from_components(ReadonlyBytes modulus, ReadonlyBytes public_exponent, ReadonlyBytes private_exponent, Optional<RSACRTComponents>);
- UnsignedBigInteger const& private_exponent() const { return m_private_exponent; }
- UnsignedBigInteger const& public_exponent() const { return m_public_exponent; }
- UnsignedBigInteger const& prime1() const { return m_prime_1; }
- UnsignedBigInteger const& prime2() const { return m_prime_2; }
- UnsignedBigInteger const& exponent1() const { return m_exponent_1; }
- UnsignedBigInteger const& exponent2() const { return m_exponent_2; }
- UnsignedBigInteger const& coefficient() const { return m_coefficient; }
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
- {
- if (m_prime_1.is_zero() || m_prime_2.is_zero()) {
- return Error::from_string_literal("Cannot export private key without prime factors");
- }
-
- ASN1::Encoder encoder;
- TRY(encoder.write_constructed(ASN1::Class::Universal, ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {
- TRY(encoder.write(0x00u)); // version
- TRY(encoder.write(m_modulus));
- TRY(encoder.write(m_public_exponent));
- TRY(encoder.write(m_private_exponent));
- TRY(encoder.write(m_prime_1));
- TRY(encoder.write(m_prime_2));
- TRY(encoder.write(m_exponent_1));
- TRY(encoder.write(m_exponent_2));
- TRY(encoder.write(m_coefficient));
- return {};
- }));
-
- return encoder.finish();
- }
+ ErrorOr<ByteBuffer> export_as_der() const;
+
+ EVP_PKEY* openssl_key() const { return m_key.ptr(); }
private:
- UnsignedBigInteger m_modulus;
- UnsignedBigInteger m_private_exponent;
- UnsignedBigInteger m_public_exponent;
- UnsignedBigInteger m_prime_1;
- UnsignedBigInteger m_prime_2;
- UnsignedBigInteger m_exponent_1; // d mod (p-1)
- UnsignedBigInteger m_exponent_2; // d mod (q-1)
- UnsignedBigInteger m_coefficient; // q^-1 mod p
+ 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 };
};
-template<typename PubKey, typename PrivKey>
struct RSAKeyPair {
- PubKey public_key;
- PrivKey private_key;
+ RSAPublicKey public_key;
+ RSAPrivateKey private_key;
};
class RSA {
public:
- using KeyPairType = RSAKeyPair<RSAPublicKey, RSAPrivateKey>;
+ 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, UnsignedBigInteger e = 65537);
+ 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);
diff --git a/Libraries/LibCrypto/RustBindings.cpp b/Libraries/LibCrypto/RustBindings.cpp
index 74dda707834..61f644406db 100644
--- a/Libraries/LibCrypto/RustBindings.cpp
+++ b/Libraries/LibCrypto/RustBindings.cpp
@@ -8,6 +8,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/AnyOf.h>
#include <AK/Memory.h>
#include <AK/Random.h>
#include <LibCrypto/ASN1/ASN1.h>
@@ -134,7 +135,6 @@ void crypto_asn1_delete_key_info(Asn1Structure structure, void* key_info)
}
VERIFY(structure == Asn1Structure::PrivateKeyInfo);
auto* storage = static_cast<PrivateKeyStorage*>(key_info);
- storage->value.rsa.clear_sensitive_data();
storage->value.mldsa.clear_sensitive_data();
storage->value.mlkem.clear_sensitive_data();
secure_zero(storage->value.raw_key.data(), storage->value.raw_key.size());
@@ -184,7 +184,7 @@ bool crypto_rsa_validate_modulus_length(u32 modulus_length)
bool crypto_rsa_generate_key_pair(u32 modulus_length, ReadonlyBytes public_exponent, KeyHandle** out_public_key, KeyHandle** out_private_key)
{
- auto key_pair = ::Crypto::PK::RSA::generate_key_pair(modulus_length, ::Crypto::UnsignedBigInteger::import_data(public_exponent));
+ 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));
@@ -208,12 +208,12 @@ bool crypto_rsa_read_key_metadata(KeyHandle const* key, u32* modulus_length, voi
{
auto result = key->visit(
[&](::Crypto::PK::RSAPublicKey const& public_key) {
- *modulus_length = public_key.modulus().byte_length() * 8;
- return export_rsa_exponent(public_key.public_exponent());
+ *modulus_length = public_key.modulus_bits();
+ return public_key.public_exponent();
},
[&](::Crypto::PK::RSAPrivateKey const& private_key) {
- *modulus_length = private_key.modulus().byte_length() * 8;
- return export_rsa_exponent(private_key.public_exponent());
+ *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);
@@ -221,21 +221,20 @@ bool crypto_rsa_read_key_metadata(KeyHandle const* key, u32* modulus_length, voi
KeyHandle* crypto_rsa_key_from_jwk_components(bool is_private, ReadonlySpan<ReadonlyBytes> components)
{
- auto n = ::Crypto::UnsignedBigInteger::import_data(components[0]);
- auto e = ::Crypto::UnsignedBigInteger::import_data(components[1]);
- if (!is_private)
- return new KeyHandle(::Crypto::PK::RSAPublicKey(move(n), move(e)));
+ auto key = [&]() -> ErrorOr<KeyHandle> {
+ if (!is_private)
+ return TRY(::Crypto::PK::RSAPublicKey::from_components(components[0], components[1]));
- auto d = ::Crypto::UnsignedBigInteger::import_data(components[2]);
- if (components.size() == 3)
- return new KeyHandle(::Crypto::PK::RSAPrivateKey(move(n), move(d), move(e)));
-
- auto p = ::Crypto::UnsignedBigInteger::import_data(components[3]);
- auto q = ::Crypto::UnsignedBigInteger::import_data(components[4]);
- auto dp = ::Crypto::UnsignedBigInteger::import_data(components[5]);
- auto dq = ::Crypto::UnsignedBigInteger::import_data(components[6]);
- auto qi = ::Crypto::UnsignedBigInteger::import_data(components[7]);
- return new KeyHandle(::Crypto::PK::RSAPrivateKey(move(n), move(d), move(e), move(p), move(q), move(dp), move(dq), move(qi)));
+ // 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)
@@ -254,37 +253,20 @@ bool crypto_rsa_export_der(KeyHandle const* key, bool is_public, void* state, Re
bool crypto_rsa_export_jwk_integer(KeyHandle const* key, u8 component, void* state, ReceiveEncodedBytes receive)
{
- auto const& integer = key->visit(
- [&](::Crypto::PK::RSAPublicKey const& public_key) -> ::Crypto::UnsignedBigInteger const& {
+ 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) -> ::Crypto::UnsignedBigInteger const& {
- switch (component) {
- case 0:
- return private_key.modulus();
- case 1:
- return private_key.public_exponent();
- case 2:
- return private_key.private_exponent();
- case 3:
- return private_key.prime1();
- case 4:
- return private_key.prime2();
- case 5:
- return private_key.exponent1();
- case 6:
- return private_key.exponent2();
- case 7:
- return private_key.coefficient();
- }
- VERIFY_NOT_REACHED();
+ [&](::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&) -> ::Crypto::UnsignedBigInteger const& { VERIFY_NOT_REACHED(); });
- auto bytes = ByteBuffer::create_uninitialized(integer.byte_length());
- if (bytes.is_error())
+ [](auto const&) -> ErrorOr<ByteBuffer> { VERIFY_NOT_REACHED(); });
+ if (integer.is_error())
return false;
- receive(state, integer.export_data(bytes.value().span()));
+ receive(state, integer.value());
+ secure_zero(integer.value().data(), integer.value().size());
return true;
}
@@ -293,7 +275,12 @@ bool crypto_rsa_oaep_cipher(bool encrypt, ::Crypto::Hash::HashKind hash_kind, Ke
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);
- return receive_byte_result(result, state, receive);
+ 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)
@@ -1060,7 +1047,7 @@ KeyHandle* crypto_public_key_for_private_key(KeyHandle const* key, FlatPtr raw_n
{
auto result = key->visit(
[](::Crypto::PK::RSAPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
- return ::Crypto::PK::RSAPublicKey { private_key.modulus(), private_key.public_exponent() };
+ return TRY(private_key.public_key());
},
[](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<KeyHandle> {
if (private_key.public_key().has_value())
diff --git a/Libraries/LibDNS/Validator.cpp b/Libraries/LibDNS/Validator.cpp
index 773b2c0bda7..ec32d73f865 100644
--- a/Libraries/LibDNS/Validator.cpp
+++ b/Libraries/LibDNS/Validator.cpp
@@ -121,10 +121,7 @@ static ErrorOr<bool> verify_signature(Records::DNSKEY const& key, ReadonlyBytes
: key.algorithm == Algorithm::RSASHA512 ? Crypto::Hash::HashKind::SHA512
: Crypto::Hash::HashKind::SHA1;
auto components = TRY(key.rsa_public_key_components());
- Crypto::PK::RSAPublicKey public_key {
- Crypto::UnsignedBigInteger::import_data(components.modulus),
- Crypto::UnsignedBigInteger::import_data(components.exponent),
- };
+ auto public_key = TRY(Crypto::PK::RSAPublicKey::from_components(components.modulus, components.exponent));
if (!TRY(public_key.is_valid()))
return false;
return Crypto::PK::rsa_pkcs1_verify(public_key, hash_kind, signed_data, signature);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
index 2c70929e7c6..f67b2b809d8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs
@@ -5584,7 +5584,8 @@ fn parse_jwk_rsa_key(jwk: &JsonWebKey, is_private: bool) -> WebIdlResult<KeyHand
vec![n, e]
};
let components: Vec<_> = components.iter().map(Bytes::as_slice).collect();
- Ok(libcrypto_rust::rsa_key_from_components(is_private, &components).expect("LibCrypto returns an RSA key"))
+ libcrypto_rust::rsa_key_from_components(is_private, &components)
+ .ok_or_else(|| dom_error("DataError", b"Invalid key"))
}
fn rsa_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool) -> WebIdlResult<Bytes> {
diff --git a/Tests/LibCrypto/TestRSA.cpp b/Tests/LibCrypto/TestRSA.cpp
index e8e0fff5fd7..f581a826f8c 100644
--- a/Tests/LibCrypto/TestRSA.cpp
+++ b/Tests/LibCrypto/TestRSA.cpp
@@ -13,6 +13,11 @@
#include <LibTest/TestCase.h>
#include <cstring>
+static Crypto::UnsignedBigInteger to_integer(ByteBuffer const& bytes)
+{
+ return Crypto::UnsignedBigInteger::import_data(bytes);
+}
+
static ByteBuffer operator""_b(char const* string, size_t length)
{
return ByteBuffer::copy(string, length).release_value();
@@ -38,7 +43,8 @@ TEST_CASE(test_RSA_rejects_invalid_public_key)
__builtin_memcpy(encoded_message.data() + separator + 1, digest_info_prefix.data(), digest_info_prefix.size());
__builtin_memcpy(encoded_message.data() + separator + 1 + digest_info_prefix.size(), digest.bytes().data(), digest.bytes().size());
- Crypto::PK::RSAPublicKey invalid_key { Crypto::UnsignedBigInteger::import_data(modulus), 1 };
+ u8 const exponent_one[] { 1 };
+ 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)));
}
@@ -54,10 +60,10 @@ TEST_CASE(test_RSA_ASN1_PKCS1_DER_parse)
"H1cKKQQvueWm6sxW9P5sUrZ3"sv));
auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::parse_rsa_key(der, true, {}));
- if (keypair.public_key.public_exponent() != 65537) {
+ if (to_integer(TRY_OR_FAIL(keypair.public_key.public_exponent())) != 65537) {
FAIL("Invalid public exponent");
}
- if (keypair.private_key.private_exponent() != "4234603516465654167360850580101327813936403862038934287300450163438938741499875303761385527882335478349599685406941909381269804396099893549838642251053393"_bigint) {
+ if (to_integer(TRY_OR_FAIL(keypair.private_key.component(Crypto::PK::RSAPrivateKey::Component::PrivateExponent))) != "4234603516465654167360850580101327813936403862038934287300450163438938741499875303761385527882335478349599685406941909381269804396099893549838642251053393"_bigint) {
FAIL("Invalid private exponent");
}
}
@@ -86,11 +92,11 @@ TEST_CASE(test_RSA_ASN1_PKCS8_DER_parse)
auto decoder = Crypto::ASN1::Decoder { der };
auto private_key = TRY_OR_FAIL(Crypto::Certificate::parse_private_key_info(decoder, {})).rsa;
- if (private_key.public_exponent() != 65537) {
+ if (to_integer(TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PublicExponent))) != 65537) {
FAIL("Invalid public exponent");
}
- if (private_key.private_exponent() != "16848664331299797559656678180469464902267415922431923391961407795209879741791261105581093539484181644099608161661780611501562625272630894063592208758992911105496755004417051031019663332258403844985328863382168329621318366311519850803972480500782200178279692319955495383119697563295214236936264406600739633470565823022975212999060908747002623721589308539473108154612454595201561671949550531384574873324370774408913092560971930541734744950937900805812300970883306404011323308000168926094053141613790857814489531436452649384151085451448183385611208320292948291211969430321231180227006521681776197974694030147965578466993"_bigint) {
+ if (to_integer(TRY_OR_FAIL(private_key.component(Crypto::PK::RSAPrivateKey::Component::PrivateExponent))) != "16848664331299797559656678180469464902267415922431923391961407795209879741791261105581093539484181644099608161661780611501562625272630894063592208758992911105496755004417051031019663332258403844985328863382168329621318366311519850803972480500782200178279692319955495383119697563295214236936264406600739633470565823022975212999060908747002623721589308539473108154612454595201561671949550531384574873324370774408913092560971930541734744950937900805812300970883306404011323308000168926094053141613790857814489531436452649384151085451448183385611208320292948291211969430321231180227006521681776197974694030147965578466993"_bigint) {
FAIL("Invalid private exponent");
}
}
@@ -160,7 +166,9 @@ TEST_CASE(test_RSA_PSS_rejects_short_signature)
TEST_CASE(test_RSA_rejects_exponent_one)
{
auto keypair = TRY_OR_FAIL(Crypto::PK::RSA::generate_key_pair(1024));
- Crypto::PK::RSAPublicKey public_key { keypair.public_key.modulus(), Crypto::UnsignedBigInteger { 1 } };
+ 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 };
diff --git a/Tests/LibTLS/TestTLSCertificateParser.cpp b/Tests/LibTLS/TestTLSCertificateParser.cpp
index ff0a28ed215..3527dc9629d 100644
--- a/Tests/LibTLS/TestTLSCertificateParser.cpp
+++ b/Tests/LibTLS/TestTLSCertificateParser.cpp
@@ -50,9 +50,14 @@ TEST_CASE(test_private_key_info_decode)
EXPECT_EQ(private_key_info.algorithm.identifier, Crypto::ASN1::rsa_encryption_oid);
auto& key = private_key_info.rsa;
+ using Component = Crypto::PK::RSAPrivateKey::Component;
+ auto component = [&](Component component) {
+ auto bytes = MUST(key.component(component));
+ return Crypto::UnsignedBigInteger::import_data(bytes);
+ };
EXPECT_EQ(key.length() * 8, 512u);
- EXPECT_EQ(key.public_exponent(), 65537);
+ EXPECT_EQ(component(Component::PublicExponent), 65537);
// $ openssl rsa -in testcase.pem -text
@@ -63,7 +68,7 @@ TEST_CASE(test_private_key_info_decode)
0x63, 0x2a, 0x21, 0x56, 0x3e, 0x81, 0xf1, 0x67, 0xe7, 0xe8, 0x47, 0x1a, 0xcb, 0xbf, 0x87,
0x7d, 0xb1, 0x5f, 0xc4, 0x4f
};
- EXPECT_EQ(key.modulus(), Crypto::UnsignedBigInteger(modulus));
+ EXPECT_EQ(component(Component::Modulus), Crypto::UnsignedBigInteger(modulus));
u8 const private_exponent[] = {
0x69, 0x0b, 0x7e, 0xd4, 0x26, 0x48, 0xd6, 0x41, 0x11, 0xf2, 0xc4, 0xff, 0x37, 0xc6, 0xe6,
@@ -72,40 +77,40 @@ TEST_CASE(test_private_key_info_decode)
0x25, 0xbb, 0x8a, 0xb1, 0xe3, 0xcf, 0xdf, 0x62, 0xdf, 0x02, 0xbf, 0xac, 0xfa, 0x26, 0xe4,
0x34, 0x65, 0x01, 0x31
};
- EXPECT_EQ(key.private_exponent(), Crypto::UnsignedBigInteger(private_exponent));
+ EXPECT_EQ(component(Component::PrivateExponent), Crypto::UnsignedBigInteger(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_EQ(key.prime1(), Crypto::UnsignedBigInteger(prime1));
+ EXPECT_EQ(component(Component::Prime1), Crypto::UnsignedBigInteger(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_EQ(key.prime2(), Crypto::UnsignedBigInteger(prime2));
+ EXPECT_EQ(component(Component::Prime2), Crypto::UnsignedBigInteger(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_EQ(key.exponent1(), Crypto::UnsignedBigInteger(exponent1));
+ EXPECT_EQ(component(Component::Exponent1), Crypto::UnsignedBigInteger(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_EQ(key.exponent2(), Crypto::UnsignedBigInteger(exponent2));
+ EXPECT_EQ(component(Component::Exponent2), Crypto::UnsignedBigInteger(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_EQ(key.coefficient(), Crypto::UnsignedBigInteger(coefficient));
+ EXPECT_EQ(component(Component::Coefficient), Crypto::UnsignedBigInteger(coefficient));
}
diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index 2bf4ee0788a..fe9ac8e1df6 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -713,10 +713,7 @@ inline GC::Ref<Web::Crypto::CryptoKey> build_live_crypto_key(StringView type, St
// Fabricate RsaKeyAlgorithm directly to pin the encode-only tag-1 branch.
inline GC::Ref<Web::Crypto::CryptoKey> build_live_crypto_key_with_rsa_key_algorithm(StringView type, StringView usage, StringView name, u32 modulus_length, ReadonlyBytes public_exponent, ReadonlyBytes modulus)
{
- auto exponent = ::Crypto::UnsignedBigInteger::import_data(public_exponent);
- auto modulus_value = ::Crypto::UnsignedBigInteger::import_data(modulus);
-
- auto key = Web::Crypto::CryptoKey::create(::Crypto::PK::RSAPublicKey { modulus_value, exponent });
+ auto key = Web::Crypto::CryptoKey::create(MUST(::Crypto::PK::RSAPublicKey::from_components(modulus, public_exponent)));
key->set_type(type == "public"sv ? Web::Crypto::KeyType::Public : (type == "private"sv ? Web::Crypto::KeyType::Private : Web::Crypto::KeyType::Secret));
key->set_extractable(false);
key->set_usages({ usage == "verify"sv ? Web::Bindings::KeyUsage::Verify : Web::Bindings::KeyUsage::Sign });
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-pkcs8-zero-crt-values.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-pkcs8-zero-crt-values.txt
new file mode 100644
index 00000000000..84ddd303cc9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-RSA-pkcs8-zero-crt-values.txt
@@ -0,0 +1,5 @@
+original: imported
+qi zero: DataError
+dp zero: DataError
+p and q zero: DataError
+all five CRT zero: DataError
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-pkcs8-zero-crt-values.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-pkcs8-zero-crt-values.html
new file mode 100644
index 00000000000..5cb1a63ba4c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-RSA-pkcs8-zero-crt-values.html
@@ -0,0 +1,78 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ // An RSA private key in PKCS#8, and copies of it with some of its prime factors and CRT values set to zero.
+ const keys = [
+ [
+ "original",
+ "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJ79swBPqi8fciAvU2rRaQ7swg7esyxbGQgFK+yet2zrbRp/" +
+ "QB2E6JsHnQ0BbYm9nTOTR/r/Gi50ZifrW6tw1o8aOqTWfGMEFmv6uw5u1Q4SI6sR6zXM7iyJZ/BSAFmkQMtbpkm05tyXC/yp" +
+ "yv2du0YAJUuH50x+KyxV13+S3UJZAgMBAAECgYANB6ey39SHtiEJSDei6nSct4ST6WZvvSuI/7uA0eUgdQ7k/AbKJIlXo0EY" +
+ "vsQ2ZKbMgkaE6IFBy2JP5TcHDuFWifM0VJYqTRGslXIpl6ruW7dRS1XxIhw+v7iGvGgyR0LVBasx1bdlxq5Jzvtli6YWvwXw" +
+ "MmFTObY+xwB2XetGgQJBAMqc4eX1EjoQkaBQl+iEEWqDvNypdHFO4luVprNxE2IH9tbHjldT03sfSis3ePICFvJAhY+PEmQd" +
+ "XZp6zmt2ECkCQQDI4lXxgYGJoX2L/3T1unb5z9TqUZrX6QgegiTHXNyRMefMf23GFs0lEqlguqwiR5VJcLPXxAM9TWoysyLD" +
+ "5iaxAkBobjIU55sMaIvWuJODmcasQthuV70XxdPv5pN0e7zE01wL2fFo22DuXfNJkR76hc8z78OnedO93FDplZCdXM35AkB4" +
+ "WurE/COBMykGFLKdeu9HcpaNIQFVtL9xj+W7ME7SCwVnBz3cvdKBELI8SvtQunSeAJEvh7etJdGnuJ3uotixAkAopWP0mUTj" +
+ "FmkZ0VqVJeETSakt91hM+XXi8WpA0s5xvvgC8cphYzsoyLTVVIghMp9xEmsrNvgG42hyeqCMSNNQ",
+ ],
+ [
+ "qi zero",
+ "MIICNgIBADANBgkqhkiG9w0BAQEFAASCAiAwggIcAgEAAoGBAJ79swBPqi8fciAvU2rRaQ7swg7esyxbGQgFK+yet2zrbRp/" +
+ "QB2E6JsHnQ0BbYm9nTOTR/r/Gi50ZifrW6tw1o8aOqTWfGMEFmv6uw5u1Q4SI6sR6zXM7iyJZ/BSAFmkQMtbpkm05tyXC/yp" +
+ "yv2du0YAJUuH50x+KyxV13+S3UJZAgMBAAECgYANB6ey39SHtiEJSDei6nSct4ST6WZvvSuI/7uA0eUgdQ7k/AbKJIlXo0EY" +
+ "vsQ2ZKbMgkaE6IFBy2JP5TcHDuFWifM0VJYqTRGslXIpl6ruW7dRS1XxIhw+v7iGvGgyR0LVBasx1bdlxq5Jzvtli6YWvwXw" +
+ "MmFTObY+xwB2XetGgQJBAMqc4eX1EjoQkaBQl+iEEWqDvNypdHFO4luVprNxE2IH9tbHjldT03sfSis3ePICFvJAhY+PEmQd" +
+ "XZp6zmt2ECkCQQDI4lXxgYGJoX2L/3T1unb5z9TqUZrX6QgegiTHXNyRMefMf23GFs0lEqlguqwiR5VJcLPXxAM9TWoysyLD" +
+ "5iaxAkBobjIU55sMaIvWuJODmcasQthuV70XxdPv5pN0e7zE01wL2fFo22DuXfNJkR76hc8z78OnedO93FDplZCdXM35AkB4" +
+ "WurE/COBMykGFLKdeu9HcpaNIQFVtL9xj+W7ME7SCwVnBz3cvdKBELI8SvtQunSeAJEvh7etJdGnuJ3uotixAgEA",
+ ],
+ [
+ "dp zero",
+ "MIICNgIBADANBgkqhkiG9w0BAQEFAASCAiAwggIcAgEAAoGBAJ79swBPqi8fciAvU2rRaQ7swg7esyxbGQgFK+yet2zrbRp/" +
+ "QB2E6JsHnQ0BbYm9nTOTR/r/Gi50ZifrW6tw1o8aOqTWfGMEFmv6uw5u1Q4SI6sR6zXM7iyJZ/BSAFmkQMtbpkm05tyXC/yp" +
+ "yv2du0YAJUuH50x+KyxV13+S3UJZAgMBAAECgYANB6ey39SHtiEJSDei6nSct4ST6WZvvSuI/7uA0eUgdQ7k/AbKJIlXo0EY" +
+ "vsQ2ZKbMgkaE6IFBy2JP5TcHDuFWifM0VJYqTRGslXIpl6ruW7dRS1XxIhw+v7iGvGgyR0LVBasx1bdlxq5Jzvtli6YWvwXw" +
+ "MmFTObY+xwB2XetGgQJBAMqc4eX1EjoQkaBQl+iEEWqDvNypdHFO4luVprNxE2IH9tbHjldT03sfSis3ePICFvJAhY+PEmQd" +
+ "XZp6zmt2ECkCQQDI4lXxgYGJoX2L/3T1unb5z9TqUZrX6QgegiTHXNyRMefMf23GFs0lEqlguqwiR5VJcLPXxAM9TWoysyLD" +
+ "5iaxAgEAAkB4WurE/COBMykGFLKdeu9HcpaNIQFVtL9xj+W7ME7SCwVnBz3cvdKBELI8SvtQunSeAJEvh7etJdGnuJ3uotix" +
+ "AkAopWP0mUTjFmkZ0VqVJeETSakt91hM+XXi8WpA0s5xvvgC8cphYzsoyLTVVIghMp9xEmsrNvgG42hyeqCMSNNQ",
+ ],
+ [
+ "p and q zero",
+ "MIIB9QIBADANBgkqhkiG9w0BAQEFAASCAd8wggHbAgEAAoGBAJ79swBPqi8fciAvU2rRaQ7swg7esyxbGQgFK+yet2zrbRp/" +
+ "QB2E6JsHnQ0BbYm9nTOTR/r/Gi50ZifrW6tw1o8aOqTWfGMEFmv6uw5u1Q4SI6sR6zXM7iyJZ/BSAFmkQMtbpkm05tyXC/yp" +
+ "yv2du0YAJUuH50x+KyxV13+S3UJZAgMBAAECgYANB6ey39SHtiEJSDei6nSct4ST6WZvvSuI/7uA0eUgdQ7k/AbKJIlXo0EY" +
+ "vsQ2ZKbMgkaE6IFBy2JP5TcHDuFWifM0VJYqTRGslXIpl6ruW7dRS1XxIhw+v7iGvGgyR0LVBasx1bdlxq5Jzvtli6YWvwXw" +
+ "MmFTObY+xwB2XetGgQIBAAIBAAJAaG4yFOebDGiL1riTg5nGrELYble9F8XT7+aTdHu8xNNcC9nxaNtg7l3zSZEe+oXPM+/D" +
+ "p3nTvdxQ6ZWQnVzN+QJAeFrqxPwjgTMpBhSynXrvR3KWjSEBVbS/cY/luzBO0gsFZwc93L3SgRCyPEr7ULp0ngCRL4e3rSXR" +
+ "p7id7qLYsQJAKKVj9JlE4xZpGdFalSXhE0mpLfdYTPl14vFqQNLOcb74AvHKYWM7KMi01VSIITKfcRJrKzb4BuNocnqgjEjT" +
+ "UA==",
+ ],
+ [
+ "all five CRT zero",
+ "MIIBOAIBADANBgkqhkiG9w0BAQEFAASCASIwggEeAgEAAoGBAJ79swBPqi8fciAvU2rRaQ7swg7esyxbGQgFK+yet2zrbRp/" +
+ "QB2E6JsHnQ0BbYm9nTOTR/r/Gi50ZifrW6tw1o8aOqTWfGMEFmv6uw5u1Q4SI6sR6zXM7iyJZ/BSAFmkQMtbpkm05tyXC/yp" +
+ "yv2du0YAJUuH50x+KyxV13+S3UJZAgMBAAECgYANB6ey39SHtiEJSDei6nSct4ST6WZvvSuI/7uA0eUgdQ7k/AbKJIlXo0EY" +
+ "vsQ2ZKbMgkaE6IFBy2JP5TcHDuFWifM0VJYqTRGslXIpl6ruW7dRS1XxIhw+v7iGvGgyR0LVBasx1bdlxq5Jzvtli6YWvwXw" +
+ "MmFTObY+xwB2XetGgQIBAAIBAAIBAAIBAAIBAA==",
+ ],
+ ];
+
+ promiseTest(async () => {
+ const bytes = base64 => Uint8Array.from(atob(base64), character => character.charCodeAt(0));
+ for (const [name, key] of keys) {
+ try {
+ await crypto.subtle.importKey(
+ "pkcs8",
+ bytes(key),
+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
+ true,
+ ["sign"]
+ );
+ println(`${name}: imported`);
+ } catch (error) {
+ println(`${name}: ${error.name}`);
+ }
+ }
+ });
+</script>