10#include <botan/ber_dec.h>
11#include <botan/der_enc.h>
12#include <botan/reducer.h>
13#include <botan/internal/blinding.h>
14#include <botan/internal/divide.h>
15#include <botan/internal/emsa.h>
16#include <botan/internal/fmt.h>
17#include <botan/internal/keypair.h>
18#include <botan/internal/monty.h>
19#include <botan/internal/monty_exp.h>
20#include <botan/internal/parsing.h>
21#include <botan/internal/pk_ops_impl.h>
22#include <botan/internal/pss_params.h>
23#include <botan/internal/workfactor.h>
25#if defined(BOTAN_HAS_THREAD_UTILS)
26 #include <botan/internal/thread_pool.h>
31class RSA_Public_Data
final {
33 RSA_Public_Data(BigInt&& n, BigInt&& e) :
36 m_monty_n(std::make_shared<Montgomery_Params>(m_n)),
37 m_public_modulus_bits(m_n.bits()),
38 m_public_modulus_bytes(m_n.bytes()) {}
40 BigInt public_op(
const BigInt& m)
const {
41 const size_t powm_window = 1;
46 const BigInt& get_n()
const {
return m_n; }
48 const BigInt& get_e()
const {
return m_e; }
50 size_t public_modulus_bits()
const {
return m_public_modulus_bits; }
52 size_t public_modulus_bytes()
const {
return m_public_modulus_bytes; }
57 std::shared_ptr<const Montgomery_Params> m_monty_n;
58 size_t m_public_modulus_bits;
59 size_t m_public_modulus_bytes;
62class RSA_Private_Data
final {
64 RSA_Private_Data(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) :
73 m_monty_p(std::make_shared<Montgomery_Params>(m_p, m_mod_p)),
74 m_monty_q(std::make_shared<Montgomery_Params>(m_q, m_mod_q)),
76 m_q_bits(m_q.bits()) {}
78 const BigInt& get_d()
const {
return m_d; }
80 const BigInt& get_p()
const {
return m_p; }
82 const BigInt& get_q()
const {
return m_q; }
84 const BigInt& get_d1()
const {
return m_d1; }
86 const BigInt& get_d2()
const {
return m_d2; }
88 const BigInt& get_c()
const {
return m_c; }
90 const Modular_Reducer& mod_p()
const {
return m_mod_p; }
92 const Modular_Reducer& mod_q()
const {
return m_mod_q; }
94 const std::shared_ptr<const Montgomery_Params>& monty_p()
const {
return m_monty_p; }
96 const std::shared_ptr<const Montgomery_Params>& monty_q()
const {
return m_monty_q; }
98 size_t p_bits()
const {
return m_p_bits; }
100 size_t q_bits()
const {
return m_q_bits; }
110 Modular_Reducer m_mod_p;
111 Modular_Reducer m_mod_q;
112 std::shared_ptr<const Montgomery_Params> m_monty_p;
113 std::shared_ptr<const Montgomery_Params> m_monty_q;
125 }
else if(field ==
"e") {
133 return std::make_unique<RSA_PrivateKey>(rng,
m_public->public_modulus_bits(),
m_public->get_e().to_u32bit());
145 if(n.is_negative() || n.is_even() || n.bits() < 5 || e.is_negative() || e.is_even()) {
148 m_public = std::make_shared<RSA_Public_Data>(std::move(n), std::move(e));
155 init(std::move(n), std::move(e));
166 init(std::move(n), std::move(e));
170 return m_public->public_modulus_bits();
182 throw Not_Implemented(
"an RSA public key does not provide a raw binary representation.");
186 std::vector<uint8_t> output;
210 .
encode(
static_cast<size_t>(0))
224 return m_private->get_p();
228 return m_private->get_q();
232 return m_private->get_d();
236 return m_private->get_c();
240 return m_private->get_d1();
244 return m_private->get_d2();
248 m_private = std::make_shared<RSA_Private_Data>(
249 std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
253 BigInt n, e, d, p, q, d1, d2, c;
270 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
286 const BigInt p_minus_1 = p - 1;
287 const BigInt q_minus_1 = q - 1;
290 const BigInt phi_n =
lcm(p_minus_1, q_minus_1);
300 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
311 if(exp < 3 || exp % 2 == 0) {
315 const size_t p_bits = (bits + 1) / 2;
316 const size_t q_bits = bits - p_bits;
321 for(
size_t attempt = 0;; ++attempt) {
330 const BigInt diff = p - q;
331 if(diff.
bits() < (bits / 2) - 100) {
337 if(n.
bits() != bits) {
344 const BigInt p_minus_1 = p - 1;
345 const BigInt q_minus_1 = q - 1;
347 const BigInt phi_n =
lcm(p_minus_1, q_minus_1);
358 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
363 return m_private->get_p();
364 }
else if(field ==
"q") {
365 return m_private->get_q();
366 }
else if(field ==
"d") {
367 return m_private->get_d();
368 }
else if(field ==
"c") {
369 return m_private->get_c();
370 }
else if(field ==
"d1") {
371 return m_private->get_d1();
372 }
else if(field ==
"d2") {
373 return m_private->get_d2();
380 return std::make_unique<RSA_PublicKey>(
get_n(),
get_e());
413 const size_t prob = (strong) ? 128 : 12;
438class RSA_Private_Operation {
440 size_t public_modulus_bits()
const {
return m_public->public_modulus_bits(); }
442 size_t public_modulus_bytes()
const {
return m_public->public_modulus_bytes(); }
444 explicit RSA_Private_Operation(
const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
445 m_public(rsa.public_data()),
446 m_private(rsa.private_data()),
450 [this](const BigInt& k) {
return m_public->public_op(k); },
451 [
this](
const BigInt& k) {
return inverse_mod(k, m_public->get_n()); }),
453 m_max_d1_bits(m_private->p_bits() + m_blinding_bits),
454 m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {}
456 void raw_op(std::span<uint8_t> out, std::span<const uint8_t> input) {
457 if(input.size() > public_modulus_bytes()) {
458 throw Decoding_Error(
"RSA input is too long for this key");
460 const BigInt input_bn(input.data(), input.size());
461 if(input_bn >= m_public->get_n()) {
462 throw Decoding_Error(
"RSA input is too large for this key");
467 const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
468 BOTAN_ASSERT(input_bn == m_public->public_op(recovered),
"RSA consistency check");
469 BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(),
"output size check");
470 recovered.serialize_to(out);
474 BigInt rsa_private_op(
const BigInt& m)
const {
481 static constexpr size_t powm_window = 4;
484 const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
486#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
487 #define BOTAN_RSA_USE_ASYNC
490#if defined(BOTAN_RSA_USE_ASYNC)
500 const BigInt masked_d1 = m_private->get_d1() + (d1_mask * (m_private->get_p() - 1));
501 auto powm_d1_p =
monty_precompute(m_private->monty_p(), m_private->mod_p().reduce(m), powm_window);
502 BigInt j1 =
monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
504#if defined(BOTAN_RSA_USE_ASYNC)
509 const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
510 const BigInt masked_d2 = m_private->get_d2() + (d2_mask * (m_private->get_q() - 1));
511 auto powm_d2_q =
monty_precompute(m_private->monty_q(), m_private->mod_q().reduce(m), powm_window);
512 const BigInt j2 =
monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits);
514#if defined(BOTAN_RSA_USE_ASYNC)
515 BigInt j1 = future_j1.get();
532 m_private->mod_p().multiply(m_private->mod_p().reduce((m_private->get_p() + j1) - j2), m_private->get_c());
533 return j1 * m_private->get_q() + j2;
536 std::shared_ptr<const RSA_Public_Data> m_public;
537 std::shared_ptr<const RSA_Private_Data> m_private;
541 const size_t m_blinding_bits;
542 const size_t m_max_d1_bits;
543 const size_t m_max_d2_bits;
546class RSA_Signature_Operation
final :
public PK_Ops::Signature,
547 private RSA_Private_Operation {
549 void update(std::span<const uint8_t> msg)
override { m_emsa->update(msg.data(), msg.size()); }
551 std::vector<uint8_t> sign(RandomNumberGenerator& rng)
override {
552 const size_t max_input_bits = public_modulus_bits() - 1;
553 const auto msg = m_emsa->raw_data();
554 const auto padded = m_emsa->encoding_of(msg, max_input_bits, rng);
556 std::vector<uint8_t> out(public_modulus_bytes());
561 size_t signature_length()
const override {
return public_modulus_bytes(); }
563 AlgorithmIdentifier algorithm_identifier()
const override;
565 std::string hash_function()
const override {
return m_emsa->hash_function(); }
567 RSA_Signature_Operation(
const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
568 RSA_Private_Operation(rsa, rng), m_emsa(EMSA::create_or_throw(padding)) {}
571 std::unique_ptr<EMSA> m_emsa;
574AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier()
const {
575 const std::string emsa_name = m_emsa->name();
578 const std::string full_name =
"RSA/" + emsa_name;
579 const OID oid = OID::from_string(full_name);
580 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM);
581 }
catch(Lookup_Error&) {}
583 if(emsa_name.starts_with(
"EMSA4(")) {
584 auto parameters = PSS_Params::from_emsa_name(m_emsa->name()).serialize();
585 return AlgorithmIdentifier(
"RSA/EMSA4", parameters);
588 throw Not_Implemented(
"No algorithm identifier defined for RSA with " + emsa_name);
591class RSA_Decryption_Operation
final :
public PK_Ops::Decryption_with_EME,
592 private RSA_Private_Operation {
594 RSA_Decryption_Operation(
const RSA_PrivateKey& rsa, std::string_view eme, RandomNumberGenerator& rng) :
595 PK_Ops::Decryption_with_EME(eme), RSA_Private_Operation(rsa, rng) {}
597 size_t plaintext_length(
size_t )
const override {
return public_modulus_bytes(); }
599 secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input)
override {
600 secure_vector<uint8_t> out(public_modulus_bytes());
606class RSA_KEM_Decryption_Operation
final :
public PK_Ops::KEM_Decryption_with_KDF,
607 private RSA_Private_Operation {
609 RSA_KEM_Decryption_Operation(
const RSA_PrivateKey& key, std::string_view kdf, RandomNumberGenerator& rng) :
610 PK_Ops::KEM_Decryption_with_KDF(kdf), RSA_Private_Operation(key, rng) {}
612 size_t raw_kem_shared_key_length()
const override {
return public_modulus_bytes(); }
614 size_t encapsulated_key_length()
const override {
return public_modulus_bytes(); }
616 void raw_kem_decrypt(std::span<uint8_t> out_shared_key, std::span<const uint8_t> encapsulated_key)
override {
617 raw_op(out_shared_key, encapsulated_key);
624class RSA_Public_Operation {
626 explicit RSA_Public_Operation(
const RSA_PublicKey& rsa) : m_public(rsa.public_data()) {}
628 size_t public_modulus_bits()
const {
return m_public->public_modulus_bits(); }
631 BigInt public_op(
const BigInt& m)
const {
632 if(m >= m_public->get_n()) {
633 throw Decoding_Error(
"RSA public op - input is too large");
636 return m_public->public_op(m);
639 size_t public_modulus_bytes()
const {
return m_public->public_modulus_bytes(); }
641 const BigInt& get_n()
const {
return m_public->get_n(); }
644 std::shared_ptr<const RSA_Public_Data> m_public;
647class RSA_Encryption_Operation
final :
public PK_Ops::Encryption_with_EME,
648 private RSA_Public_Operation {
650 RSA_Encryption_Operation(
const RSA_PublicKey& rsa, std::string_view eme) :
651 PK_Ops::Encryption_with_EME(eme), RSA_Public_Operation(rsa) {}
653 size_t ciphertext_length(
size_t )
const override {
return public_modulus_bytes(); }
655 size_t max_ptext_input_bits()
const override {
return public_modulus_bits() - 1; }
657 std::vector<uint8_t> raw_encrypt(std::span<const uint8_t> input, RandomNumberGenerator& )
override {
658 BigInt input_bn(input);
659 return public_op(input_bn).serialize(public_modulus_bytes());
663class RSA_Verify_Operation
final :
public PK_Ops::Verification,
664 private RSA_Public_Operation {
666 void update(std::span<const uint8_t> msg)
override { m_emsa->update(msg.data(), msg.size()); }
668 bool is_valid_signature(std::span<const uint8_t> sig)
override {
669 const auto msg = m_emsa->raw_data();
670 const auto message_repr = recover_message_repr(sig.data(), sig.size());
671 return m_emsa->verify(message_repr, msg, public_modulus_bits() - 1);
674 RSA_Verify_Operation(
const RSA_PublicKey& rsa, std::string_view padding) :
675 RSA_Public_Operation(rsa), m_emsa(EMSA::create_or_throw(padding)) {}
677 std::string hash_function()
const override {
return m_emsa->hash_function(); }
680 std::vector<uint8_t> recover_message_repr(
const uint8_t input[],
size_t input_len) {
681 if(input_len > public_modulus_bytes()) {
682 throw Decoding_Error(
"RSA signature too large to be valid for this key");
684 BigInt input_bn(input, input_len);
685 return public_op(input_bn).serialize();
688 std::unique_ptr<EMSA> m_emsa;
691class RSA_KEM_Encryption_Operation
final :
public PK_Ops::KEM_Encryption_with_KDF,
692 private RSA_Public_Operation {
694 RSA_KEM_Encryption_Operation(
const RSA_PublicKey& key, std::string_view kdf) :
695 PK_Ops::KEM_Encryption_with_KDF(kdf), RSA_Public_Operation(key) {}
698 size_t raw_kem_shared_key_length()
const override {
return public_modulus_bytes(); }
700 size_t encapsulated_key_length()
const override {
return public_modulus_bytes(); }
702 void raw_kem_encrypt(std::span<uint8_t> out_encapsulated_key,
703 std::span<uint8_t> raw_shared_key,
704 RandomNumberGenerator& rng)
override {
705 const BigInt r = BigInt::random_integer(rng, 1, get_n());
706 const BigInt c = public_op(r);
708 c.serialize_to(out_encapsulated_key);
709 r.serialize_to(raw_shared_key);
716 std::string_view params,
717 std::string_view provider)
const {
718 if(provider ==
"base" || provider.empty()) {
719 return std::make_unique<RSA_Encryption_Operation>(*
this, params);
725 std::string_view provider)
const {
726 if(provider ==
"base" || provider.empty()) {
727 return std::make_unique<RSA_KEM_Encryption_Operation>(*
this, params);
733 std::string_view provider)
const {
734 if(provider ==
"base" || provider.empty()) {
735 return std::make_unique<RSA_Verify_Operation>(*
this, params);
746 if(sig_info.empty() || sig_info.size() != 2 || sig_info[0] !=
"RSA") {
747 throw Decoding_Error(
"Unknown AlgorithmIdentifier for RSA X.509 signatures");
750 std::string padding = sig_info[1];
752 if(padding ==
"EMSA4") {
755 throw Decoding_Error(
"PSS params must be provided");
761 const std::string hash_algo = pss_params.hash_function();
762 if(hash_algo !=
"SHA-1" && hash_algo !=
"SHA-224" && hash_algo !=
"SHA-256" && hash_algo !=
"SHA-384" &&
763 hash_algo !=
"SHA-512") {
764 throw Decoding_Error(
"Unacceptable hash for PSS signatures");
767 if(pss_params.mgf_function() !=
"MGF1") {
768 throw Decoding_Error(
"Unacceptable MGF for PSS signatures");
775 if(pss_params.hash_algid() != pss_params.mgf_hash_algid()) {
776 throw Decoding_Error(
"Unacceptable MGF hash for PSS signatures");
779 if(pss_params.trailer_field() != 1) {
780 throw Decoding_Error(
"Unacceptable trailer field for PSS signatures");
783 padding +=
fmt(
"({},MGF1,{})", hash_algo, pss_params.salt_length());
792 std::string_view provider)
const {
793 if(provider ==
"base" || provider.empty()) {
794 return std::make_unique<RSA_Verify_Operation>(*
this, parse_rsa_signature_algorithm(alg_id));
801 std::string_view params,
802 std::string_view provider)
const {
803 if(provider ==
"base" || provider.empty()) {
804 return std::make_unique<RSA_Decryption_Operation>(*
this, params, rng);
811 std::string_view params,
812 std::string_view provider)
const {
813 if(provider ==
"base" || provider.empty()) {
814 return std::make_unique<RSA_KEM_Decryption_Operation>(*
this, params, rng);
821 std::string_view params,
822 std::string_view provider)
const {
823 if(provider ==
"base" || provider.empty()) {
824 return std::make_unique<RSA_Signature_Operation>(*
this, params, rng);
#define BOTAN_DEBUG_ASSERT(expr)
#define BOTAN_ASSERT(expr, assertion_made)
const std::vector< uint8_t > & parameters() const
virtual const BigInt & get_int_field(std::string_view field) const
virtual OID object_identifier() const
BER_Decoder & decode(bool &out)
BER_Decoder start_sequence()
BER_Decoder & decode_and_check(const T &expected, std::string_view error_msg)
static BigInt from_u64(uint64_t n)
secure_vector< uint8_t > get_contents()
DER_Encoder & start_sequence()
DER_Encoder & encode(bool b)
std::string to_formatted_string() const
const BigInt & get_q() const
const BigInt & get_int_field(std::string_view field) const override
std::shared_ptr< const RSA_Private_Data > private_data() const
std::unique_ptr< PK_Ops::Decryption > create_decryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
const BigInt & get_c() const
std::unique_ptr< PK_Ops::Signature > create_signature_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
RSA_PrivateKey(const AlgorithmIdentifier &alg_id, std::span< const uint8_t > key_bits)
const BigInt & get_p() const
const BigInt & get_d2() const
bool check_key(RandomNumberGenerator &rng, bool) const override
const BigInt & get_d() const
secure_vector< uint8_t > private_key_bits() const override
std::unique_ptr< PK_Ops::KEM_Decryption > create_kem_decryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
std::unique_ptr< Public_Key > public_key() const override
const BigInt & get_d1() const
std::unique_ptr< PK_Ops::Encryption > create_encryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
void init(BigInt &&n, BigInt &&e)
size_t key_length() const override
std::unique_ptr< PK_Ops::Verification > create_verification_op(std::string_view params, std::string_view provider) const override
std::unique_ptr< PK_Ops::Verification > create_x509_verification_op(const AlgorithmIdentifier &alg_id, std::string_view provider) const override
const BigInt & get_int_field(std::string_view field) const override
const BigInt & get_n() const
size_t estimated_strength() const override
std::unique_ptr< PK_Ops::KEM_Encryption > create_kem_encryption_op(std::string_view params, std::string_view provider) const override
std::unique_ptr< Private_Key > generate_another(RandomNumberGenerator &rng) const override
std::vector< uint8_t > raw_public_key_bits() const override
AlgorithmIdentifier algorithm_identifier() const override
std::vector< uint8_t > public_key_bits() const override
std::shared_ptr< const RSA_Public_Data > m_public
std::shared_ptr< const RSA_Public_Data > public_data() const
const BigInt & get_e() const
bool supports_operation(PublicKeyOperation op) const override
bool check_key(RandomNumberGenerator &rng, bool) const override
auto run(F &&f, Args &&... args) -> std::future< typename std::invoke_result< F, Args... >::type >
static Thread_Pool & global_instance()
int(* update)(CTX *, const void *, CC_LONG len)
int(* final)(unsigned char *, CTX *)
bool signature_consistency_check(RandomNumberGenerator &rng, const Private_Key &private_key, const Public_Key &public_key, std::string_view padding)
std::string fmt(std::string_view format, const T &... args)
BigInt lcm(const BigInt &a, const BigInt &b)
std::vector< std::string > split_on(std::string_view str, char delim)
size_t low_zero_bits(const BigInt &n)
bool is_prime(const BigInt &n, RandomNumberGenerator &rng, size_t prob, bool is_random)
BigInt ct_modulo(const BigInt &x, const BigInt &y)
BigInt generate_rsa_prime(RandomNumberGenerator &keygen_rng, RandomNumberGenerator &prime_test_rng, size_t bits, const BigInt &coprime, size_t prob)
std::vector< T, secure_allocator< T > > secure_vector
BigInt monty_execute_vartime(const Montgomery_Exponentation_State &precomputed_state, const BigInt &k)
size_t if_work_factor(size_t bits)
BigInt inverse_mod(const BigInt &n, const BigInt &mod)
BigInt monty_execute(const Montgomery_Exponentation_State &precomputed_state, const BigInt &k, size_t max_k_bits)
std::shared_ptr< const Montgomery_Exponentation_State > monty_precompute(const std::shared_ptr< const Montgomery_Params > ¶ms, const BigInt &g, size_t window_bits, bool const_time)