• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 24063525848

06 Apr 2026 10:36PM UTC coverage: 89.448% (-0.007%) from 89.455%
24063525848

push

github

web-flow
Merge pull request #5521 from randombit/jack/fix-rollup

Rollup of small fixes

105878 of 118368 relevant lines covered (89.45%)

11475460.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.81
/src/lib/pubkey/rsa/rsa.cpp
1
/*
2
* RSA
3
* (C) 1999-2010,2015,2016,2018,2019,2023 Jack Lloyd
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include <botan/rsa.h>
9

10
#include <botan/ber_dec.h>
11
#include <botan/der_enc.h>
12
#include <botan/numthry.h>
13
#include <botan/pss_params.h>
14
#include <botan/internal/barrett.h>
15
#include <botan/internal/blinding.h>
16
#include <botan/internal/divide.h>
17
#include <botan/internal/fmt.h>
18
#include <botan/internal/keypair.h>
19
#include <botan/internal/mod_inv.h>
20
#include <botan/internal/monty.h>
21
#include <botan/internal/monty_exp.h>
22
#include <botan/internal/mp_core.h>
23
#include <botan/internal/parsing.h>
24
#include <botan/internal/pk_ops_impl.h>
25
#include <botan/internal/sig_padding.h>
26
#include <botan/internal/target_info.h>
27
#include <botan/internal/workfactor.h>
28

29
#if defined(BOTAN_HAS_THREAD_UTILS)
30
   #include <botan/internal/thread_pool.h>
31
#endif
32

33
namespace Botan {
34

35
class RSA_Public_Data final {
36
   public:
37
      RSA_Public_Data(BigInt&& n, BigInt&& e) :
12,521✔
38
            m_n(std::move(n)),
12,521✔
39
            m_e(std::move(e)),
12,521✔
40
            m_mod_n(Barrett_Reduction::for_public_modulus(m_n)),
12,521✔
41
            m_monty_n(m_n, m_mod_n),
12,521✔
42
            m_public_modulus_bits(m_n.bits()),
12,521✔
43
            m_public_modulus_bytes(m_n.bytes()) {}
12,521✔
44

45
      BigInt public_op(const BigInt& m) const {
46,098✔
46
         const size_t powm_window = 1;
46,098✔
47
         auto powm_m_n = monty_precompute(m_monty_n, m, powm_window, false);
46,098✔
48
         return monty_execute_vartime(*powm_m_n, m_e).value();
46,098✔
49
      }
46,098✔
50

51
      const BigInt& get_n() const { return m_n; }
47,027✔
52

53
      const BigInt& get_e() const { return m_e; }
3✔
54

55
      size_t public_modulus_bits() const { return m_public_modulus_bits; }
37,121✔
56

57
      size_t public_modulus_bytes() const { return m_public_modulus_bytes; }
58,666✔
58

59
      const Montgomery_Params& monty_n() const { return m_monty_n; }
824✔
60

61
      const Barrett_Reduction& reducer_mod_n() const { return m_mod_n; }
1,546✔
62

63
   private:
64
      BigInt m_n;
65
      BigInt m_e;
66
      Barrett_Reduction m_mod_n;
67
      const Montgomery_Params m_monty_n;
68
      size_t m_public_modulus_bits;
69
      size_t m_public_modulus_bytes;
70
};
71

72
class RSA_Private_Data final {
73
   public:
74
      RSA_Private_Data(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) :
1,639✔
75
            m_d(std::move(d)),
1,639✔
76
            m_p(std::move(p)),
1,639✔
77
            m_q(std::move(q)),
1,639✔
78
            m_d1(std::move(d1)),
1,639✔
79
            m_d2(std::move(d2)),
1,639✔
80
            m_c(std::move(c)),
1,639✔
81
            m_monty_p(m_p),
1,639✔
82
            m_monty_q(m_q),
1,639✔
83
            m_c_monty(m_monty_p, m_c),
1,639✔
84
            m_p_bits(m_p.bits()),
1,639✔
85
            m_q_bits(m_q.bits()) {}
1,639✔
86

87
      const BigInt& get_d() const { return m_d; }
825✔
88

89
      const BigInt& get_p() const { return m_p; }
1✔
90

91
      const BigInt& get_q() const { return m_q; }
1✔
92

93
      const BigInt& get_d1() const { return m_d1; }
×
94

95
      const BigInt& get_d2() const { return m_d2; }
×
96

97
      BigInt blinded_d1(const BigInt& m) const { return m_d1 + m * (m_p - 1); }
6,218✔
98

99
      BigInt blinded_d2(const BigInt& m) const { return m_d2 + m * (m_q - 1); }
6,218✔
100

101
      const BigInt& get_c() const { return m_c; }
×
102

103
      const Montgomery_Int& get_c_monty() const { return m_c_monty; }
6,218✔
104

105
      const Montgomery_Params& monty_p() const { return m_monty_p; }
12,436✔
106

107
      const Montgomery_Params& monty_q() const { return m_monty_q; }
6,218✔
108

109
      size_t p_bits() const { return m_p_bits; }
8,588✔
110

111
      size_t q_bits() const { return m_q_bits; }
8,588✔
112

113
      bool primes_imbalanced() const { return p_bits() != q_bits(); }
7,042✔
114

115
   private:
116
      BigInt m_d;
117
      BigInt m_p;
118
      BigInt m_q;
119
      BigInt m_d1;
120
      BigInt m_d2;
121
      BigInt m_c;
122

123
      const Montgomery_Params m_monty_p;
124
      const Montgomery_Params m_monty_q;
125
      Montgomery_Int m_c_monty;
126
      size_t m_p_bits;
127
      size_t m_q_bits;
128
};
129

130
std::shared_ptr<const RSA_Public_Data> RSA_PublicKey::public_data() const {
11,442✔
131
   return m_public;
11,442✔
132
}
133

134
const BigInt& RSA_PublicKey::get_int_field(std::string_view field) const {
10✔
135
   if(field == "n") {
10✔
136
      return m_public->get_n();
5✔
137
   } else if(field == "e") {
5✔
138
      return m_public->get_e();
3✔
139
   } else {
140
      return Public_Key::get_int_field(field);
2✔
141
   }
142
}
143

144
std::unique_ptr<Private_Key> RSA_PublicKey::generate_another(RandomNumberGenerator& rng) const {
2✔
145
   return std::make_unique<RSA_PrivateKey>(rng, m_public->public_modulus_bits(), 65537);
2✔
146
}
147

148
const BigInt& RSA_PublicKey::get_n() const {
2,826✔
149
   return m_public->get_n();
2,826✔
150
}
151

152
const BigInt& RSA_PublicKey::get_e() const {
1,158✔
153
   return m_public->get_e();
1,158✔
154
}
155

156
void RSA_PublicKey::init(BigInt&& n, BigInt&& e) {
12,535✔
157
   if(n.signum() <= 0 || n.is_even() || n.bits() < 384 || n.bits() > 16384) {
25,070✔
158
      throw Decoding_Error("Invalid RSA public key modulus");
12✔
159
   }
160
   if(e.is_even() || e <= 1 || e >= n || e.bits() > 256) {
50,091✔
161
      throw Decoding_Error("Invalid RSA public key exponent");
2✔
162
   }
163
   m_public = std::make_shared<RSA_Public_Data>(std::move(n), std::move(e));
12,521✔
164
}
12,521✔
165

166
RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
9,718✔
167
   BigInt n;
9,718✔
168
   BigInt e;
9,718✔
169
   BER_Decoder(key_bits, BER_Decoder::Limits::DER()).start_sequence().decode(n).decode(e).end_cons().verify_end();
19,467✔
170

171
   init(std::move(n), std::move(e));
9,684✔
172
}
9,808✔
173

174
bool RSA_PublicKey::supports_operation(PublicKeyOperation op) const {
1,420✔
175
   return op == PublicKeyOperation::Signature || op == PublicKeyOperation::Encryption ||
1,420✔
176
          op == PublicKeyOperation::KeyEncapsulation;
1,420✔
177
}
178

179
RSA_PublicKey::RSA_PublicKey(const BigInt& modulus, const BigInt& exponent) {
1,209✔
180
   BigInt n = modulus;
1,209✔
181
   BigInt e = exponent;
1,209✔
182
   init(std::move(n), std::move(e));
1,209✔
183
}
1,211✔
184

185
size_t RSA_PublicKey::key_length() const {
7,786✔
186
   return m_public->public_modulus_bits();
7,786✔
187
}
188

189
size_t RSA_PublicKey::estimated_strength() const {
6,305✔
190
   return if_work_factor(key_length());
6,305✔
191
}
192

193
AlgorithmIdentifier RSA_PublicKey::algorithm_identifier() const {
757✔
194
   return AlgorithmIdentifier(object_identifier(), AlgorithmIdentifier::USE_NULL_PARAM);
757✔
195
}
196

197
std::vector<uint8_t> RSA_PublicKey::raw_public_key_bits() const {
3✔
198
   throw Not_Implemented("an RSA public key does not provide a raw binary representation.");
3✔
199
}
200

201
std::vector<uint8_t> RSA_PublicKey::public_key_bits() const {
415✔
202
   std::vector<uint8_t> output;
415✔
203
   DER_Encoder der(output);
415✔
204
   der.start_sequence().encode(get_n()).encode(get_e()).end_cons();
415✔
205

206
   return output;
415✔
207
}
415✔
208

209
/*
210
* Check RSA Public Parameters
211
*/
212
bool RSA_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*strong*/) const {
9✔
213
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
27✔
214
      return false;
×
215
   }
216
   return true;
217
}
218

219
std::shared_ptr<const RSA_Private_Data> RSA_PrivateKey::private_data() const {
1,546✔
220
   return m_private;
1,546✔
221
}
222

223
secure_vector<uint8_t> RSA_PrivateKey::private_key_bits() const {
99✔
224
   return DER_Encoder()
198✔
225
      .start_sequence()
99✔
226
      .encode(static_cast<size_t>(0))
99✔
227
      .encode(get_n())
99✔
228
      .encode(get_e())
99✔
229
      .encode(get_d())
99✔
230
      .encode(get_p())
99✔
231
      .encode(get_q())
99✔
232
      .encode(get_d1())
99✔
233
      .encode(get_d2())
99✔
234
      .encode(get_c())
99✔
235
      .end_cons()
99✔
236
      .get_contents();
198✔
237
}
238

239
const BigInt& RSA_PrivateKey::get_p() const {
234✔
240
   return m_private->get_p();
234✔
241
}
242

243
const BigInt& RSA_PrivateKey::get_q() const {
217✔
244
   return m_private->get_q();
217✔
245
}
246

247
const BigInt& RSA_PrivateKey::get_d() const {
166✔
248
   return m_private->get_d();
166✔
249
}
250

251
const BigInt& RSA_PrivateKey::get_c() const {
118✔
252
   return m_private->get_c();
118✔
253
}
254

255
const BigInt& RSA_PrivateKey::get_d1() const {
118✔
256
   return m_private->get_d1();
118✔
257
}
258

259
const BigInt& RSA_PrivateKey::get_d2() const {
118✔
260
   return m_private->get_d2();
118✔
261
}
262

263
void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) {
1,639✔
264
   if(d < 2 || p < 3 || q < 3 || p == q) {
6,556✔
265
      throw Decoding_Error("Invalid RSA private key parameters");
×
266
   }
267
   if(p * q != get_n()) {
3,278✔
268
      throw Decoding_Error("Invalid RSA private key: p * q != n");
×
269
   }
270
   m_private = std::make_shared<RSA_Private_Data>(
1,639✔
271
      std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
1,639✔
272
}
1,639✔
273

274
RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
1,018✔
275
   BigInt n;
1,018✔
276
   BigInt e;
1,018✔
277
   BigInt d;
1,018✔
278
   BigInt p;
1,018✔
279
   BigInt q;
1,018✔
280
   BigInt d1;
1,018✔
281
   BigInt d2;
1,018✔
282
   BigInt c;
1,018✔
283

284
   BER_Decoder(key_bits, BER_Decoder::Limits::DER())
2,036✔
285
      .start_sequence()
1,018✔
286
      .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
2,031✔
287
      .decode(n)
1,013✔
288
      .decode(e)
1,009✔
289
      .decode(d)
1,009✔
290
      .decode(p)
1,009✔
291
      .decode(q)
1,009✔
292
      .decode(d1)
1,008✔
293
      .decode(d2)
1,007✔
294
      .decode(c)
1,006✔
295
      .end_cons()
1,006✔
296
      .verify_end();
1,006✔
297

298
   RSA_PublicKey::init(std::move(n), std::move(e));
1,006✔
299

300
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
1,005✔
301
}
1,122✔
302

303
RSA_PrivateKey::RSA_PrivateKey(
566✔
304
   const BigInt& prime1, const BigInt& prime2, const BigInt& exp, const BigInt& d_exp, const BigInt& mod) {
566✔
305
   BigInt p = prime1;
566✔
306
   BigInt q = prime2;
566✔
307
   BigInt n = mod;
566✔
308
   if(n.is_zero()) {
1,132✔
309
      n = p * q;
565✔
310
   }
311

312
   BigInt e = exp;
566✔
313

314
   BigInt d = d_exp;
566✔
315

316
   const BigInt p_minus_1 = p - 1;
566✔
317
   const BigInt q_minus_1 = q - 1;
566✔
318

319
   if(d.is_zero()) {
1,132✔
320
      const BigInt phi_n = lcm(p_minus_1, q_minus_1);
565✔
321
      d = compute_rsa_secret_exponent(e, phi_n, p, q);
565✔
322
   }
565✔
323

324
   BigInt d1 = ct_modulo(d, p_minus_1);
566✔
325
   BigInt d2 = ct_modulo(d, q_minus_1);
566✔
326
   BigInt c = inverse_mod_secret_prime(ct_modulo(q, p), p);
566✔
327

328
   RSA_PublicKey::init(std::move(n), std::move(e));
566✔
329

330
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
565✔
331
}
576✔
332

333
/*
334
* Create a RSA private key
335
*/
336
RSA_PrivateKey::RSA_PrivateKey(RandomNumberGenerator& rng, size_t bits, size_t exp) {
70✔
337
   constexpr size_t MIN_RSA_BITS = 1024;
70✔
338
   constexpr size_t MAX_RSA_BITS = 16384;
70✔
339
   constexpr size_t MOD_RSA_BITS = 8;
70✔
340

341
   if(bits < MIN_RSA_BITS) {
70✔
342
      throw Invalid_Argument(fmt("Cannot create an RSA key of {} bits: must be at least {} bits", bits, MIN_RSA_BITS));
×
343
   } else if(bits > MAX_RSA_BITS) {
70✔
344
      throw Invalid_Argument(
×
345
         fmt("Cannot create an RSA key of {} bits: must be no more than {} bits", bits, MAX_RSA_BITS));
×
346
   } else if(bits % MOD_RSA_BITS != 0) {
70✔
347
      throw Invalid_Argument(
×
348
         fmt("Cannot create an RSA key of {} bits: must be a multiple of {} bits", bits, MOD_RSA_BITS));
×
349
   }
350

351
   if(exp < 3 || exp % 2 == 0) {
70✔
352
      throw Invalid_Argument("Invalid RSA encryption exponent");
×
353
   }
354

355
   const size_t p_bits = (bits + 1) / 2;
70✔
356
   const size_t q_bits = bits - p_bits;
70✔
357

358
   BigInt p;
70✔
359
   BigInt q;
70✔
360
   BigInt n;
70✔
361
   BigInt e = BigInt::from_u64(exp);
70✔
362

363
   for(size_t attempt = 0;; ++attempt) {
11✔
364
      if(attempt > 10) {
81✔
365
         throw Internal_Error("RNG failure during RSA key generation");
1✔
366
      }
367

368
      // TODO could generate primes in thread pool
369
      p = generate_rsa_prime(rng, rng, p_bits, e);
80✔
370
      q = generate_rsa_prime(rng, rng, q_bits, e);
80✔
371

372
      const BigInt diff = p - q;
80✔
373
      if(diff.bits() < (bits / 2) - 100) {
80✔
374
         continue;
11✔
375
      }
376

377
      n = p * q;
69✔
378

379
      if(n.bits() != bits) {
69✔
380
         continue;
×
381
      }
382

383
      break;
69✔
384
   }
80✔
385

386
   const BigInt p_minus_1 = p - 1;
69✔
387
   const BigInt q_minus_1 = q - 1;
69✔
388

389
   const BigInt phi_n = lcm(p_minus_1, q_minus_1);
69✔
390
   // This is guaranteed because p,q == 3 mod 4
391
   BOTAN_DEBUG_ASSERT(low_zero_bits(phi_n) == 1);
69✔
392

393
   BigInt d = compute_rsa_secret_exponent(e, phi_n, p, q);
69✔
394
   BigInt d1 = ct_modulo(d, p_minus_1);
69✔
395
   BigInt d2 = ct_modulo(d, q_minus_1);
69✔
396
   BigInt c = inverse_mod_secret_prime(ct_modulo(q, p), p);
69✔
397

398
   RSA_PublicKey::init(std::move(n), std::move(e));
69✔
399

400
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
69✔
401
}
74✔
402

403
const BigInt& RSA_PrivateKey::get_int_field(std::string_view field) const {
6✔
404
   if(field == "p") {
6✔
405
      return m_private->get_p();
1✔
406
   } else if(field == "q") {
5✔
407
      return m_private->get_q();
1✔
408
   } else if(field == "d") {
4✔
409
      return m_private->get_d();
1✔
410
   } else if(field == "c") {
3✔
411
      return m_private->get_c();
×
412
   } else if(field == "d1") {
3✔
413
      return m_private->get_d1();
×
414
   } else if(field == "d2") {
3✔
415
      return m_private->get_d2();
×
416
   } else {
417
      return RSA_PublicKey::get_int_field(field);
3✔
418
   }
419
}
420

421
std::unique_ptr<Public_Key> RSA_PrivateKey::public_key() const {
570✔
422
   return std::make_unique<RSA_PublicKey>(get_n(), get_e());
570✔
423
}
424

425
/*
426
* Check Private RSA Parameters
427
*/
428
bool RSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const {
17✔
429
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
51✔
430
      return false;
×
431
   }
432

433
   if(get_d() < 2 || get_p() < 3 || get_q() < 3) {
17✔
434
      return false;
×
435
   }
436

437
   if(get_p() * get_q() != get_n()) {
34✔
438
      return false;
439
   }
440

441
   if(get_p() == get_q()) {
17✔
442
      return false;
443
   }
444

445
   if(get_d1() != ct_modulo(get_d(), get_p() - 1)) {
17✔
446
      return false;
447
   }
448
   if(get_d2() != ct_modulo(get_d(), get_q() - 1)) {
17✔
449
      return false;
450
   }
451
   if(get_c() != inverse_mod_secret_prime(ct_modulo(get_q(), get_p()), get_p())) {
17✔
452
      return false;
453
   }
454

455
   const size_t prob = (strong) ? 128 : 12;
17✔
456

457
   if(!is_prime(get_p(), rng, prob)) {
17✔
458
      return false;
459
   }
460
   if(!is_prime(get_q(), rng, prob)) {
17✔
461
      return false;
462
   }
463

464
   if(strong) {
17✔
465
      if(ct_modulo(get_e() * get_d(), lcm(get_p() - 1, get_q() - 1)) != 1) {
28✔
466
         return false;
467
      }
468

469
#if defined(BOTAN_HAS_PSS) && defined(BOTAN_HAS_SHA_256)
470
      const std::string padding = "PSS(SHA-256)";
14✔
471
#else
472
      const std::string padding = "Raw";
473
#endif
474

475
      return KeyPair::signature_consistency_check(rng, *this, padding);
14✔
476
   }
14✔
477

478
   return true;
479
}
480

481
namespace {
482

483
/*
484
* To recover the final value from the CRT representation (j1,j2)
485
* we use Garner's algorithm:
486
* c = q^-1 mod p (this is precomputed)
487
* h = c*(j1-j2) mod p
488
* r = h*q + j2
489
*/
490
BigInt crt_recombine(const Montgomery_Int& j1,
6,218✔
491
                     const Montgomery_Int& j2_p,
492
                     const BigInt& j2,
493
                     const Montgomery_Int& c_monty,
494
                     const BigInt& p,
495
                     const BigInt& q) {
496
   // We skip CRT entirely if the primes are not balanced (same bitlength) so q is also of this size
497
   const size_t p_words = p.sig_words();
6,218✔
498
   BOTAN_ASSERT_NOMSG(p_words == q.sig_words());
6,218✔
499

500
   const size_t n_words = 2 * p_words;
6,218✔
501

502
   // Ensure sufficient storage
503
   BOTAN_ASSERT_NOMSG(j1.repr().size() >= p_words);
6,218✔
504
   BOTAN_ASSERT_NOMSG(j2_p.repr().size() >= p_words);
6,218✔
505
   BOTAN_ASSERT_NOMSG(j2.size() >= p_words);
6,218✔
506

507
   /*
508
   * Compute h = (j1 - j2) * c mod p
509
   *
510
   * This doesn't quite match up with the "Smooth-CRT" proposal; there we would
511
   * multiply by a precomputed c * R2, which would have the effect of both
512
   * multiplying by c and immediately converting from Montgomery to standard form.
513
   */
514
   secure_vector<word> ws(2 * p_words);
6,218✔
515

516
   const Montgomery_Int h_monty = (j1 - j2_p).mul(c_monty, ws);
6,218✔
517

518
   const BigInt h = h_monty.value();
6,218✔
519
   // Montgomery_Int always returns values sized to the modulus
520
   BOTAN_ASSERT_NOMSG(h.size() >= p_words);
6,218✔
521
   BOTAN_DEBUG_ASSERT(h.sig_words() <= p_words);
6,218✔
522

523
   // Compute r = h * q
524
   secure_vector<word> r(2 * p_words);
6,218✔
525

526
   bigint_mul(r.data(), r.size(), h._data(), h.size(), p_words, q._data(), q.size(), p_words, ws.data(), ws.size());
6,218✔
527

528
   // r += j2
529
   const word carry = bigint_add2(r.data(), n_words, j2._data(), p_words);
6,218✔
530
   BOTAN_ASSERT_NOMSG(carry == 0);  // should not be possible since it would imply r > the public modulus
6,218✔
531

532
   return BigInt::_from_words(r);
6,218✔
533
}
12,436✔
534

535
/**
536
* RSA private (decrypt/sign) operation
537
*/
538
class RSA_Private_Operation {
539
   protected:
540
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
1,626✔
541

542
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
8,679✔
543

544
      explicit RSA_Private_Operation(const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
1,546✔
545
            m_public(rsa.public_data()),
1,546✔
546
            m_private(rsa.private_data()),
1,546✔
547
            m_blinder(
1,546✔
548
               m_public->reducer_mod_n(),
1,546✔
549
               rng,
550
               [this](const BigInt& k) { return m_public->public_op(k); },
3,103✔
551
               [this](const BigInt& k) { return inverse_mod_rsa_public_modulus(k, m_public->get_n()); }),
3,103✔
552
            m_blinding_bits(64),
1,546✔
553
            m_max_d1_bits(m_private->p_bits() + m_blinding_bits),
1,546✔
554
            m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {}
1,546✔
555

556
      void raw_op(std::span<uint8_t> out, std::span<const uint8_t> input) {
7,054✔
557
         if(input.size() > public_modulus_bytes()) {
7,054✔
558
            throw Decoding_Error("RSA input is too long for this key");
×
559
         }
560
         const BigInt input_bn(input.data(), input.size());
7,054✔
561
         if(input_bn >= m_public->get_n()) {
7,054✔
562
            throw Decoding_Error("RSA input is too large for this key");
11✔
563
         }
564
         // TODO: This should be a function on blinder
565
         // BigInt Blinder::run_blinded_function(std::function<BigInt, BigInt> fn, const BigInt& input);
566

567
         const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
7,043✔
568
         BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
14,084✔
569
         BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(), "output size check");
7,042✔
570
         recovered.serialize_to(out);
7,042✔
571
      }
7,054✔
572

573
   private:
574
      BigInt rsa_private_op(const BigInt& m) const {
7,042✔
575
         /*
576
         All normal implementations generate p/q of the same bitlength,
577
         so this should rarely occur in practice
578
         */
579
         if(m_private->primes_imbalanced()) {
7,042✔
580
            return monty_exp(m_public->monty_n(), m, m_private->get_d(), m_public->get_n().bits()).value();
824✔
581
         }
582

583
         static constexpr size_t powm_window = 4;
6,218✔
584

585
         // Compute this in main thread to avoid racing on the rng
586
         const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
6,218✔
587

588
#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
589
   #define BOTAN_RSA_USE_ASYNC
590
#endif
591

592
#if defined(BOTAN_RSA_USE_ASYNC)
593
         /*
594
         * Precompute m.sig_words in the main thread before calling async. Otherwise
595
         * the two threads race (during Barrett_Reduction::reduce) and while the output
596
         * is correct in both threads, helgrind warns.
597
         */
598
         m.sig_words();
6,218✔
599

600
         auto future_j1 = Thread_Pool::global_instance().run([this, &m, &d1_mask]() {
6,218✔
601
#endif
602
            const BigInt masked_d1 = m_private->blinded_d1(d1_mask);
6,218✔
603
            auto powm_d1_p = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_p(), m), powm_window);
6,218✔
604
            auto j1 = monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
6,218✔
605

606
#if defined(BOTAN_RSA_USE_ASYNC)
607
            return j1;
12,436✔
608
         });
12,436✔
609
#endif
610

611
         const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
6,218✔
612
         const BigInt masked_d2 = m_private->blinded_d2(d2_mask);
6,218✔
613
         auto powm_d2_q = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_q(), m), powm_window);
6,218✔
614
         const auto j2 = monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits).value();
6,218✔
615

616
#if defined(BOTAN_RSA_USE_ASYNC)
617
         auto j1 = future_j1.get();
6,218✔
618
#endif
619

620
         // Reduce j2 modulo p
621
         const auto j2_p = Montgomery_Int::from_wide_int(m_private->monty_p(), j2);
6,218✔
622

623
         return crt_recombine(j1, j2_p, j2, m_private->get_c_monty(), m_private->get_p(), m_private->get_q());
6,218✔
624
      }
12,436✔
625

626
      std::shared_ptr<const RSA_Public_Data> m_public;
627
      std::shared_ptr<const RSA_Private_Data> m_private;
628

629
      // XXX could the blinder starting pair be shared?
630
      Blinder m_blinder;
631
      const size_t m_blinding_bits;
632
      const size_t m_max_d1_bits;
633
      const size_t m_max_d2_bits;
634
};
635

636
class RSA_Signature_Operation final : public PK_Ops::Signature,
×
637
                                      private RSA_Private_Operation {
638
   public:
639
      void update(std::span<const uint8_t> msg) override { m_padding->update(msg.data(), msg.size()); }
1,627✔
640

641
      std::vector<uint8_t> sign(RandomNumberGenerator& rng) override {
1,626✔
642
         const size_t max_input_bits = public_modulus_bits() - 1;
1,626✔
643
         const auto msg = m_padding->raw_data();
1,626✔
644
         const auto padded = m_padding->encoding_of(msg, max_input_bits, rng);
1,626✔
645

646
         std::vector<uint8_t> out(public_modulus_bytes());
1,625✔
647
         raw_op(out, padded);
1,625✔
648
         return out;
1,625✔
649
      }
3,249✔
650

651
      size_t signature_length() const override { return public_modulus_bytes(); }
344✔
652

653
      AlgorithmIdentifier algorithm_identifier() const override;
654

655
      std::string hash_function() const override { return m_padding->hash_function(); }
99✔
656

657
      RSA_Signature_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
1,233✔
658
            RSA_Private_Operation(rsa, rng), m_padding(SignaturePaddingScheme::create_or_throw(padding)) {}
1,233✔
659

660
   private:
661
      std::unique_ptr<SignaturePaddingScheme> m_padding;
662
};
663

664
AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier() const {
64✔
665
   const std::string padding_name = m_padding->name();
64✔
666

667
   try {
64✔
668
      const std::string full_name = "RSA/" + padding_name;
64✔
669
      const OID oid = OID::from_string(full_name);
64✔
670
      return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM);
59✔
671
   } catch(Lookup_Error&) {}
64✔
672

673
   if(padding_name.starts_with("PSS(")) {
5✔
674
      auto parameters = PSS_Params::from_padding_name(m_padding->name()).serialize();
5✔
675
      return AlgorithmIdentifier("RSA/PSS", parameters);
4✔
676
   }
4✔
677

678
   throw Invalid_Argument(fmt("Signatures using RSA/{} are not supported", padding_name));
2✔
679
}
63✔
680

681
class RSA_Decryption_Operation final : public PK_Ops::Decryption_with_Padding,
682
                                       private RSA_Private_Operation {
683
   public:
684
      RSA_Decryption_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
291✔
685
            PK_Ops::Decryption_with_Padding(padding), RSA_Private_Operation(rsa, rng) {}
291✔
686

687
      size_t plaintext_length(size_t /*ctext_len*/) const override { return public_modulus_bytes(); }
190✔
688

689
      secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input) override {
5,398✔
690
         secure_vector<uint8_t> out(public_modulus_bytes());
5,398✔
691
         raw_op(out, input);
5,398✔
692
         return out;
5,386✔
693
      }
12✔
694
};
695

696
class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KDF,
697
                                           private RSA_Private_Operation {
698
   public:
699
      RSA_KEM_Decryption_Operation(const RSA_PrivateKey& key, std::string_view kdf, RandomNumberGenerator& rng) :
22✔
700
            PK_Ops::KEM_Decryption_with_KDF(kdf), RSA_Private_Operation(key, rng) {}
22✔
701

702
      size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
71✔
703

704
      size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
10✔
705

706
      void raw_kem_decrypt(std::span<uint8_t> out_shared_key, std::span<const uint8_t> encapsulated_key) override {
31✔
707
         raw_op(out_shared_key, encapsulated_key);
31✔
708
      }
31✔
709
};
710

711
/**
712
* RSA public (encrypt/verify) operation
713
*/
714
class RSA_Public_Operation {
×
715
   public:
716
      explicit RSA_Public_Operation(const RSA_PublicKey& rsa) : m_public(rsa.public_data()) {}
9,584✔
717

718
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
37,119✔
719

720
   protected:
721
      BigInt public_op(const BigInt& m) const {
37,565✔
722
         if(m >= m_public->get_n()) {
37,565✔
723
            throw Decoding_Error("RSA public op - input is too large");
66✔
724
         }
725

726
         return m_public->public_op(m);
37,499✔
727
      }
728

729
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
37,858✔
730

731
      const BigInt& get_n() const { return m_public->get_n(); }
22✔
732

733
   private:
734
      std::shared_ptr<const RSA_Public_Data> m_public;
735
};
736

737
class RSA_Encryption_Operation final : public PK_Ops::Encryption_with_Padding,
×
738
                                       private RSA_Public_Operation {
739
   public:
740
      RSA_Encryption_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
290✔
741
            PK_Ops::Encryption_with_Padding(padding), RSA_Public_Operation(rsa) {}
290✔
742

743
      size_t ciphertext_length(size_t /*ptext_len*/) const override { return public_modulus_bytes(); }
190✔
744

745
      size_t max_ptext_input_bits() const override { return public_modulus_bits() - 1; }
546✔
746

747
      std::vector<uint8_t> raw_encrypt(std::span<const uint8_t> input, RandomNumberGenerator& /*rng*/) override {
358✔
748
         const BigInt input_bn(input);
358✔
749
         return public_op(input_bn).serialize(public_modulus_bytes());
716✔
750
      }
358✔
751
};
752

753
class RSA_Verify_Operation final : public PK_Ops::Verification,
×
754
                                   private RSA_Public_Operation {
755
   public:
756
      void update(std::span<const uint8_t> msg) override { m_padding->update(msg.data(), msg.size()); }
37,186✔
757

758
      bool is_valid_signature(std::span<const uint8_t> sig) override {
37,189✔
759
         const auto msg = m_padding->raw_data();
37,189✔
760
         const auto message_repr = recover_message_repr(sig.data(), sig.size());
37,189✔
761
         return m_padding->verify(message_repr, msg, public_modulus_bits() - 1);
37,119✔
762
      }
74,087✔
763

764
      RSA_Verify_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
9,584✔
765
            RSA_Public_Operation(rsa), m_padding(SignaturePaddingScheme::create_or_throw(padding)) {}
9,584✔
766

767
      std::string hash_function() const override { return m_padding->hash_function(); }
7,395✔
768

769
   private:
770
      std::vector<uint8_t> recover_message_repr(const uint8_t input[], size_t input_len) {
37,189✔
771
         if(input_len > public_modulus_bytes()) {
37,189✔
772
            throw Decoding_Error("RSA signature too large to be valid for this key");
4✔
773
         }
774
         const BigInt input_bn(input, input_len);
37,185✔
775
         return public_op(input_bn).serialize();
111,423✔
776
      }
37,185✔
777

778
      std::unique_ptr<SignaturePaddingScheme> m_padding;
779
};
780

781
class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KDF,
×
782
                                           private RSA_Public_Operation {
783
   public:
784
      RSA_KEM_Encryption_Operation(const RSA_PublicKey& key, std::string_view kdf) :
22✔
785
            PK_Ops::KEM_Encryption_with_KDF(kdf), RSA_Public_Operation(key) {}
22✔
786

787
   private:
788
      size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
44✔
789

790
      size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
77✔
791

792
      void raw_kem_encrypt(std::span<uint8_t> out_encapsulated_key,
22✔
793
                           std::span<uint8_t> raw_shared_key,
794
                           RandomNumberGenerator& rng) override {
795
         const BigInt r = BigInt::random_integer(rng, BigInt::one(), get_n());
22✔
796
         const BigInt c = public_op(r);
22✔
797

798
         c.serialize_to(out_encapsulated_key);
22✔
799
         r.serialize_to(raw_shared_key);
22✔
800
      }
22✔
801
};
802

803
}  // namespace
804

805
std::unique_ptr<PK_Ops::Encryption> RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
854✔
806
                                                                        std::string_view params,
807
                                                                        std::string_view provider) const {
808
   if(provider == "base" || provider.empty()) {
1,043✔
809
      return std::make_unique<RSA_Encryption_Operation>(*this, params);
290✔
810
   }
811
   throw Provider_Not_Found(algo_name(), provider);
1,128✔
812
}
813

814
std::unique_ptr<PK_Ops::KEM_Encryption> RSA_PublicKey::create_kem_encryption_op(std::string_view params,
22✔
815
                                                                                std::string_view provider) const {
816
   if(provider == "base" || provider.empty()) {
22✔
817
      return std::make_unique<RSA_KEM_Encryption_Operation>(*this, params);
22✔
818
   }
819
   throw Provider_Not_Found(algo_name(), provider);
×
820
}
821

822
std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_verification_op(std::string_view params,
4,752✔
823
                                                                            std::string_view provider) const {
824
   if(provider == "base" || provider.empty()) {
5,668✔
825
      return std::make_unique<RSA_Verify_Operation>(*this, params);
2,010✔
826
   }
827

828
   throw Provider_Not_Found(algo_name(), provider);
5,484✔
829
}
830

831
namespace {
832

833
std::string parse_rsa_signature_algorithm(const AlgorithmIdentifier& alg_id) {
7,576✔
834
   const auto sig_info = split_on(alg_id.oid().to_formatted_string(), '/');
7,576✔
835

836
   if(sig_info.empty() || sig_info.size() != 2 || sig_info[0] != "RSA") {
7,576✔
837
      throw Decoding_Error("Unknown AlgorithmIdentifier for RSA X.509 signatures");
×
838
   }
839

840
   std::string padding = sig_info[1];
7,576✔
841

842
   if(padding != "PSS") {
7,576✔
843
      if(!alg_id.parameters_are_null_or_empty()) {
7,190✔
844
         throw Decoding_Error("Non-PSS RSA signature algorithm OID has unexpected parameters");
×
845
      }
846
   }
847

848
   if(padding == "PSS") {
7,576✔
849
      // "MUST contain RSASSA-PSS-params"
850
      if(alg_id.parameters().empty()) {
386✔
851
         throw Decoding_Error("PSS params must be provided");
×
852
      }
853

854
      const PSS_Params pss_params(alg_id.parameters());
388✔
855

856
      // hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
857
      // We also support SHA-3 (is also supported by e.g. OpenSSL and bouncycastle)
858
      const std::string hash_algo = pss_params.hash_function();
386✔
859
      if(hash_algo != "SHA-1" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384" &&
367✔
860
         hash_algo != "SHA-512" && hash_algo != "SHA-3(224)" && hash_algo != "SHA-3(256)" &&
10✔
861
         hash_algo != "SHA-3(384)" && hash_algo != "SHA-3(512)") {
386✔
862
         throw Decoding_Error("Unacceptable hash for PSS signatures");
×
863
      }
864

865
      if(pss_params.mgf_function() != "MGF1") {
386✔
866
         throw Decoding_Error("Unacceptable MGF for PSS signatures");
×
867
      }
868

869
      // For MGF1, it is strongly RECOMMENDED that the underlying hash
870
      // function be the same as the one identified by hashAlgorithm
871
      if(pss_params.hash_algid() != pss_params.mgf_hash_algid()) {
386✔
872
         throw Decoding_Error("Unacceptable MGF hash for PSS signatures");
2✔
873
      }
874

875
      if(pss_params.trailer_field() != 1) {
384✔
876
         throw Decoding_Error("Unacceptable trailer field for PSS signatures");
×
877
      }
878

879
      padding += fmt("({},MGF1,{})", hash_algo, pss_params.salt_length());
770✔
880
   }
386✔
881

882
   return padding;
7,574✔
883
}
7,576✔
884

885
}  // namespace
886

887
std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_x509_verification_op(const AlgorithmIdentifier& alg_id,
7,576✔
888
                                                                                 std::string_view provider) const {
889
   if(provider == "base" || provider.empty()) {
7,576✔
890
      return std::make_unique<RSA_Verify_Operation>(*this, parse_rsa_signature_algorithm(alg_id));
7,576✔
891
   }
892

893
   throw Provider_Not_Found(algo_name(), provider);
×
894
}
895

896
std::unique_ptr<PK_Ops::Decryption> RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
930✔
897
                                                                         std::string_view params,
898
                                                                         std::string_view provider) const {
899
   if(provider == "base" || provider.empty()) {
1,144✔
900
      return std::make_unique<RSA_Decryption_Operation>(*this, params, rng);
291✔
901
   }
902

903
   throw Provider_Not_Found(algo_name(), provider);
1,278✔
904
}
905

906
std::unique_ptr<PK_Ops::KEM_Decryption> RSA_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
22✔
907
                                                                                 std::string_view params,
908
                                                                                 std::string_view provider) const {
909
   if(provider == "base" || provider.empty()) {
22✔
910
      return std::make_unique<RSA_KEM_Decryption_Operation>(*this, params, rng);
22✔
911
   }
912

913
   throw Provider_Not_Found(algo_name(), provider);
×
914
}
915

916
std::unique_ptr<PK_Ops::Signature> RSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
2,253✔
917
                                                                       std::string_view params,
918
                                                                       std::string_view provider) const {
919
   if(provider == "base" || provider.empty()) {
2,595✔
920
      return std::make_unique<RSA_Signature_Operation>(*this, params, rng);
1,233✔
921
   }
922

923
   throw Provider_Not_Found(algo_name(), provider);
2,040✔
924
}
925

926
}  // namespace Botan
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc