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

randombit / botan / 22248456082

21 Feb 2026 02:16AM UTC coverage: 90.33% (-1.6%) from 91.977%
22248456082

push

github

web-flow
Merge pull request #5370 from randombit/jack/misc-int-imprv

Misc BigInt related improvements

102993 of 114019 relevant lines covered (90.33%)

11610383.67 hits per line

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

94.32
/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) :
21,271✔
38
            m_n(std::move(n)),
21,271✔
39
            m_e(std::move(e)),
21,271✔
40
            m_mod_n(Barrett_Reduction::for_public_modulus(m_n)),
21,271✔
41
            m_monty_n(m_n, m_mod_n),
21,271✔
42
            m_public_modulus_bits(m_n.bits()),
21,271✔
43
            m_public_modulus_bytes(m_n.bytes()) {}
21,271✔
44

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

51
      const BigInt& get_n() const { return m_n; }
40,089✔
52

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

55
      size_t public_modulus_bits() const { return m_public_modulus_bits; }
30,457✔
56

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

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

61
      const Barrett_Reduction& reducer_mod_n() const { return m_mod_n; }
1,544✔
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,641✔
75
            m_d(std::move(d)),
1,641✔
76
            m_p(std::move(p)),
1,641✔
77
            m_q(std::move(q)),
1,641✔
78
            m_d1(std::move(d1)),
1,641✔
79
            m_d2(std::move(d2)),
1,641✔
80
            m_c(std::move(c)),
1,641✔
81
            m_monty_p(m_p),
1,641✔
82
            m_monty_q(m_q),
1,641✔
83
            m_c_monty(m_monty_p, m_c),
1,641✔
84
            m_p_bits(m_p.bits()),
1,641✔
85
            m_q_bits(m_q.bits()) {}
1,641✔
86

87
      const BigInt& get_d() const { return m_d; }
779✔
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,033✔
98

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

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

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

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

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

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

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

113
      bool primes_imbalanced() const { return p_bits() != q_bits(); }
6,811✔
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 {
20,174✔
131
   return m_public;
20,174✔
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(), m_public->get_e().to_u32bit());
2✔
146
}
147

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

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

156
void RSA_PublicKey::init(BigInt&& n, BigInt&& e) {
22,073✔
157
   if(n.is_negative() || n.is_even() || n.bits() < 5 /* n >= 3*5 */ || e.is_negative() || e.is_even()) {
65,609✔
158
      throw Decoding_Error("Invalid RSA public key parameters");
802✔
159
   }
160
   m_public = std::make_shared<RSA_Public_Data>(std::move(n), std::move(e));
21,271✔
161
}
21,271✔
162

163
RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
19,265✔
164
   BigInt n;
19,265✔
165
   BigInt e;
19,265✔
166
   BER_Decoder(key_bits).start_sequence().decode(n).decode(e).end_cons();
19,294✔
167

168
   init(std::move(n), std::move(e));
19,220✔
169
}
20,953✔
170

171
bool RSA_PublicKey::supports_operation(PublicKeyOperation op) const {
1,412✔
172
   return op == PublicKeyOperation::Signature || op == PublicKeyOperation::Encryption ||
1,412✔
173
          op == PublicKeyOperation::KeyEncapsulation;
1,412✔
174
}
175

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

182
size_t RSA_PublicKey::key_length() const {
7,785✔
183
   return m_public->public_modulus_bits();
7,785✔
184
}
185

186
size_t RSA_PublicKey::estimated_strength() const {
6,301✔
187
   return if_work_factor(key_length());
6,301✔
188
}
189

190
AlgorithmIdentifier RSA_PublicKey::algorithm_identifier() const {
756✔
191
   return AlgorithmIdentifier(object_identifier(), AlgorithmIdentifier::USE_NULL_PARAM);
756✔
192
}
193

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

198
std::vector<uint8_t> RSA_PublicKey::public_key_bits() const {
414✔
199
   std::vector<uint8_t> output;
414✔
200
   DER_Encoder der(output);
414✔
201
   der.start_sequence().encode(get_n()).encode(get_e()).end_cons();
414✔
202

203
   return output;
414✔
204
}
414✔
205

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

216
std::shared_ptr<const RSA_Private_Data> RSA_PrivateKey::private_data() const {
1,544✔
217
   return m_private;
1,544✔
218
}
219

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

236
const BigInt& RSA_PrivateKey::get_p() const {
241✔
237
   return m_private->get_p();
241✔
238
}
239

240
const BigInt& RSA_PrivateKey::get_q() const {
222✔
241
   return m_private->get_q();
222✔
242
}
243

244
const BigInt& RSA_PrivateKey::get_d() const {
169✔
245
   return m_private->get_d();
169✔
246
}
247

248
const BigInt& RSA_PrivateKey::get_c() const {
119✔
249
   return m_private->get_c();
119✔
250
}
251

252
const BigInt& RSA_PrivateKey::get_d1() const {
119✔
253
   return m_private->get_d1();
119✔
254
}
255

256
const BigInt& RSA_PrivateKey::get_d2() const {
119✔
257
   return m_private->get_d2();
119✔
258
}
259

260
void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) {
1,641✔
261
   m_private = std::make_shared<RSA_Private_Data>(
1,641✔
262
      std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
1,641✔
263
}
1,641✔
264

265
RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
1,024✔
266
   BigInt n;
1,024✔
267
   BigInt e;
1,024✔
268
   BigInt d;
1,024✔
269
   BigInt p;
1,024✔
270
   BigInt q;
1,024✔
271
   BigInt d1;
1,024✔
272
   BigInt d2;
1,024✔
273
   BigInt c;
1,024✔
274

275
   BER_Decoder(key_bits)
2,046✔
276
      .start_sequence()
1,022✔
277
      .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
2,041✔
278
      .decode(n)
1,019✔
279
      .decode(e)
1,018✔
280
      .decode(d)
1,017✔
281
      .decode(p)
1,017✔
282
      .decode(q)
1,017✔
283
      .decode(d1)
1,016✔
284
      .decode(d2)
1,015✔
285
      .decode(c)
1,011✔
286
      .end_cons();
1,011✔
287

288
   RSA_PublicKey::init(std::move(n), std::move(e));
1,008✔
289

290
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
1,006✔
291
}
1,168✔
292

293
RSA_PrivateKey::RSA_PrivateKey(
566✔
294
   const BigInt& prime1, const BigInt& prime2, const BigInt& exp, const BigInt& d_exp, const BigInt& mod) {
566✔
295
   BigInt p = prime1;
566✔
296
   BigInt q = prime2;
566✔
297
   BigInt n = mod;
566✔
298
   if(n.is_zero()) {
1,132✔
299
      n = p * q;
565✔
300
   }
301

302
   BigInt e = exp;
566✔
303

304
   BigInt d = d_exp;
566✔
305

306
   const BigInt p_minus_1 = p - 1;
566✔
307
   const BigInt q_minus_1 = q - 1;
566✔
308

309
   if(d.is_zero()) {
1,132✔
310
      const BigInt phi_n = lcm(p_minus_1, q_minus_1);
565✔
311
      d = compute_rsa_secret_exponent(e, phi_n, p, q);
565✔
312
   }
565✔
313

314
   BigInt d1 = ct_modulo(d, p_minus_1);
566✔
315
   BigInt d2 = ct_modulo(d, q_minus_1);
566✔
316
   BigInt c = inverse_mod_secret_prime(ct_modulo(q, p), p);
566✔
317

318
   RSA_PublicKey::init(std::move(n), std::move(e));
566✔
319

320
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
566✔
321
}
566✔
322

323
/*
324
* Create a RSA private key
325
*/
326
RSA_PrivateKey::RSA_PrivateKey(RandomNumberGenerator& rng, size_t bits, size_t exp) {
70✔
327
   if(bits < 1024) {
70✔
328
      throw Invalid_Argument(fmt("Cannot create an RSA key only {} bits long", bits));
×
329
   }
330

331
   if(exp < 3 || exp % 2 == 0) {
70✔
332
      throw Invalid_Argument("Invalid RSA encryption exponent");
×
333
   }
334

335
   const size_t p_bits = (bits + 1) / 2;
70✔
336
   const size_t q_bits = bits - p_bits;
70✔
337

338
   BigInt p;
70✔
339
   BigInt q;
70✔
340
   BigInt n;
70✔
341
   BigInt e = BigInt::from_u64(exp);
70✔
342

343
   for(size_t attempt = 0;; ++attempt) {
11✔
344
      if(attempt > 10) {
81✔
345
         throw Internal_Error("RNG failure during RSA key generation");
1✔
346
      }
347

348
      // TODO could generate primes in thread pool
349
      p = generate_rsa_prime(rng, rng, p_bits, e);
80✔
350
      q = generate_rsa_prime(rng, rng, q_bits, e);
80✔
351

352
      const BigInt diff = p - q;
80✔
353
      if(diff.bits() < (bits / 2) - 100) {
80✔
354
         continue;
11✔
355
      }
356

357
      n = p * q;
69✔
358

359
      if(n.bits() != bits) {
69✔
360
         continue;
×
361
      }
362

363
      break;
69✔
364
   }
80✔
365

366
   const BigInt p_minus_1 = p - 1;
69✔
367
   const BigInt q_minus_1 = q - 1;
69✔
368

369
   const BigInt phi_n = lcm(p_minus_1, q_minus_1);
69✔
370
   // This is guaranteed because p,q == 3 mod 4
371
   BOTAN_DEBUG_ASSERT(low_zero_bits(phi_n) == 1);
69✔
372

373
   BigInt d = compute_rsa_secret_exponent(e, phi_n, p, q);
69✔
374
   BigInt d1 = ct_modulo(d, p_minus_1);
69✔
375
   BigInt d2 = ct_modulo(d, q_minus_1);
69✔
376
   BigInt c = inverse_mod_secret_prime(ct_modulo(q, p), p);
69✔
377

378
   RSA_PublicKey::init(std::move(n), std::move(e));
69✔
379

380
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
69✔
381
}
74✔
382

383
const BigInt& RSA_PrivateKey::get_int_field(std::string_view field) const {
6✔
384
   if(field == "p") {
6✔
385
      return m_private->get_p();
1✔
386
   } else if(field == "q") {
5✔
387
      return m_private->get_q();
1✔
388
   } else if(field == "d") {
4✔
389
      return m_private->get_d();
1✔
390
   } else if(field == "c") {
3✔
391
      return m_private->get_c();
×
392
   } else if(field == "d1") {
3✔
393
      return m_private->get_d1();
×
394
   } else if(field == "d2") {
3✔
395
      return m_private->get_d2();
×
396
   } else {
397
      return RSA_PublicKey::get_int_field(field);
3✔
398
   }
399
}
400

401
std::unique_ptr<Public_Key> RSA_PrivateKey::public_key() const {
570✔
402
   return std::make_unique<RSA_PublicKey>(get_n(), get_e());
570✔
403
}
404

405
/*
406
* Check Private RSA Parameters
407
*/
408
bool RSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const {
18✔
409
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
54✔
410
      return false;
×
411
   }
412

413
   if(get_d() < 2 || get_p() < 3 || get_q() < 3) {
18✔
414
      return false;
×
415
   }
416

417
   if(get_p() * get_q() != get_n()) {
36✔
418
      return false;
419
   }
420

421
   if(get_p() == get_q()) {
18✔
422
      return false;
423
   }
424

425
   if(get_d1() != ct_modulo(get_d(), get_p() - 1)) {
18✔
426
      return false;
427
   }
428
   if(get_d2() != ct_modulo(get_d(), get_q() - 1)) {
18✔
429
      return false;
430
   }
431
   if(get_c() != inverse_mod_secret_prime(ct_modulo(get_q(), get_p()), get_p())) {
18✔
432
      return false;
433
   }
434

435
   const size_t prob = (strong) ? 128 : 12;
18✔
436

437
   if(!is_prime(get_p(), rng, prob)) {
18✔
438
      return false;
439
   }
440
   if(!is_prime(get_q(), rng, prob)) {
17✔
441
      return false;
442
   }
443

444
   if(strong) {
17✔
445
      if(ct_modulo(get_e() * get_d(), lcm(get_p() - 1, get_q() - 1)) != 1) {
28✔
446
         return false;
447
      }
448

449
#if defined(BOTAN_HAS_PSS) && defined(BOTAN_HAS_SHA_256)
450
      const std::string padding = "PSS(SHA-256)";
14✔
451
#else
452
      const std::string padding = "Raw";
453
#endif
454

455
      return KeyPair::signature_consistency_check(rng, *this, padding);
14✔
456
   }
14✔
457

458
   return true;
459
}
460

461
namespace {
462

463
/*
464
* To recover the final value from the CRT representation (j1,j2)
465
* we use Garner's algorithm:
466
* c = q^-1 mod p (this is precomputed)
467
* h = c*(j1-j2) mod p
468
* r = h*q + j2
469
*/
470
BigInt crt_recombine(const Montgomery_Int& j1,
6,033✔
471
                     const Montgomery_Int& j2_p,
472
                     const BigInt& j2,
473
                     const Montgomery_Int& c_monty,
474
                     const BigInt& p,
475
                     const BigInt& q) {
476
   // We skip CRT entirely if the primes are not balanced (same bitlength) so q is also of this size
477
   const size_t p_words = p.sig_words();
6,033✔
478
   BOTAN_ASSERT_NOMSG(p_words == q.sig_words());
6,033✔
479

480
   const size_t n_words = 2 * p_words;
6,033✔
481

482
   // Ensure sufficient storage
483
   BOTAN_ASSERT_NOMSG(j1.repr().size() >= p_words);
6,033✔
484
   BOTAN_ASSERT_NOMSG(j2_p.repr().size() >= p_words);
6,033✔
485
   BOTAN_ASSERT_NOMSG(j2.size() >= p_words);
6,033✔
486

487
   /*
488
   * Compute h = (j1 - j2) * c mod p
489
   *
490
   * This doesn't quite match up with the "Smooth-CRT" proposal; there we would
491
   * multiply by a precomputed c * R2, which would have the effect of both
492
   * multiplying by c and immediately converting from Montgomery to standard form.
493
   */
494
   secure_vector<word> ws(2 * p_words);
6,033✔
495

496
   const Montgomery_Int h_monty = (j1 - j2_p).mul(c_monty, ws);
6,033✔
497

498
   const BigInt h = h_monty.value();
6,033✔
499
   // Montgomery_Int always returns values sized to the modulus
500
   BOTAN_ASSERT_NOMSG(h.size() >= p_words);
6,033✔
501
   BOTAN_DEBUG_ASSERT(h.sig_words() <= p_words);
6,033✔
502

503
   // Compute r = h * q
504
   secure_vector<word> r(2 * p_words);
6,033✔
505

506
   bigint_mul(r.data(), r.size(), h._data(), h.size(), p_words, q._data(), q.size(), p_words, ws.data(), ws.size());
6,033✔
507

508
   // r += j2
509
   const word carry = bigint_add2(r.data(), n_words, j2._data(), p_words);
6,033✔
510
   BOTAN_ASSERT_NOMSG(carry == 0);  // should not be possible since it would imply r > the public modulus
6,033✔
511

512
   return BigInt::_from_words(r);
6,033✔
513
}
12,066✔
514

515
/**
516
* RSA private (decrypt/sign) operation
517
*/
518
class RSA_Private_Operation {
519
   protected:
520
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
1,623✔
521

522
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
8,460✔
523

524
      explicit RSA_Private_Operation(const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
1,544✔
525
            m_public(rsa.public_data()),
1,544✔
526
            m_private(rsa.private_data()),
1,544✔
527
            m_blinder(
1,544✔
528
               m_public->reducer_mod_n(),
1,544✔
529
               rng,
530
               [this](const BigInt& k) { return m_public->public_op(k); },
3,099✔
531
               [this](const BigInt& k) { return inverse_mod_rsa_public_modulus(k, m_public->get_n()); }),
3,099✔
532
            m_blinding_bits(64),
1,544✔
533
            m_max_d1_bits(m_private->p_bits() + m_blinding_bits),
1,544✔
534
            m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {}
1,544✔
535

536
      void raw_op(std::span<uint8_t> out, std::span<const uint8_t> input) {
6,838✔
537
         if(input.size() > public_modulus_bytes()) {
6,838✔
538
            throw Decoding_Error("RSA input is too long for this key");
×
539
         }
540
         const BigInt input_bn(input.data(), input.size());
6,838✔
541
         if(input_bn >= m_public->get_n()) {
6,838✔
542
            throw Decoding_Error("RSA input is too large for this key");
26✔
543
         }
544
         // TODO: This should be a function on blinder
545
         // BigInt Blinder::run_blinded_function(std::function<BigInt, BigInt> fn, const BigInt& input);
546

547
         const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
6,812✔
548
         BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
13,622✔
549
         BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(), "output size check");
6,811✔
550
         recovered.serialize_to(out);
6,811✔
551
      }
6,838✔
552

553
   private:
554
      BigInt rsa_private_op(const BigInt& m) const {
6,811✔
555
         /*
556
         All normal implementations generate p/q of the same bitlength,
557
         so this should rarely occur in practice
558
         */
559
         if(m_private->primes_imbalanced()) {
6,811✔
560
            return monty_exp(m_public->monty_n(), m, m_private->get_d(), m_public->get_n().bits()).value();
778✔
561
         }
562

563
         static constexpr size_t powm_window = 4;
6,033✔
564

565
         // Compute this in main thread to avoid racing on the rng
566
         const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
6,033✔
567

568
#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
569
   #define BOTAN_RSA_USE_ASYNC
570
#endif
571

572
#if defined(BOTAN_RSA_USE_ASYNC)
573
         /*
574
         * Precompute m.sig_words in the main thread before calling async. Otherwise
575
         * the two threads race (during Barrett_Reduction::reduce) and while the output
576
         * is correct in both threads, helgrind warns.
577
         */
578
         m.sig_words();
6,033✔
579

580
         auto future_j1 = Thread_Pool::global_instance().run([this, &m, &d1_mask]() {
6,033✔
581
#endif
582
            const BigInt masked_d1 = m_private->blinded_d1(d1_mask);
6,033✔
583
            auto powm_d1_p = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_p(), m), powm_window);
6,033✔
584
            auto j1 = monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
6,033✔
585

586
#if defined(BOTAN_RSA_USE_ASYNC)
587
            return j1;
12,066✔
588
         });
12,066✔
589
#endif
590

591
         const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
6,033✔
592
         const BigInt masked_d2 = m_private->blinded_d2(d2_mask);
6,033✔
593
         auto powm_d2_q = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_q(), m), powm_window);
6,033✔
594
         const auto j2 = monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits).value();
6,033✔
595

596
#if defined(BOTAN_RSA_USE_ASYNC)
597
         auto j1 = future_j1.get();
6,033✔
598
#endif
599

600
         // Reduce j2 modulo p
601
         const auto j2_p = Montgomery_Int::from_wide_int(m_private->monty_p(), j2);
6,033✔
602

603
         return crt_recombine(j1, j2_p, j2, m_private->get_c_monty(), m_private->get_p(), m_private->get_q());
6,033✔
604
      }
12,066✔
605

606
      std::shared_ptr<const RSA_Public_Data> m_public;
607
      std::shared_ptr<const RSA_Private_Data> m_private;
608

609
      // XXX could the blinder starting pair be shared?
610
      Blinder m_blinder;
611
      const size_t m_blinding_bits;
612
      const size_t m_max_d1_bits;
613
      const size_t m_max_d2_bits;
614
};
615

616
class RSA_Signature_Operation final : public PK_Ops::Signature,
×
617
                                      private RSA_Private_Operation {
618
   public:
619
      void update(std::span<const uint8_t> msg) override { m_padding->update(msg.data(), msg.size()); }
1,624✔
620

621
      std::vector<uint8_t> sign(RandomNumberGenerator& rng) override {
1,623✔
622
         const size_t max_input_bits = public_modulus_bits() - 1;
1,623✔
623
         const auto msg = m_padding->raw_data();
1,623✔
624
         const auto padded = m_padding->encoding_of(msg, max_input_bits, rng);
1,623✔
625

626
         std::vector<uint8_t> out(public_modulus_bytes());
1,622✔
627
         raw_op(out, padded);
1,622✔
628
         return out;
1,622✔
629
      }
3,243✔
630

631
      size_t signature_length() const override { return public_modulus_bytes(); }
344✔
632

633
      AlgorithmIdentifier algorithm_identifier() const override;
634

635
      std::string hash_function() const override { return m_padding->hash_function(); }
98✔
636

637
      RSA_Signature_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
1,231✔
638
            RSA_Private_Operation(rsa, rng), m_padding(SignaturePaddingScheme::create_or_throw(padding)) {}
1,231✔
639

640
   private:
641
      std::unique_ptr<SignaturePaddingScheme> m_padding;
642
};
643

644
AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier() const {
63✔
645
   const std::string padding_name = m_padding->name();
63✔
646

647
   try {
63✔
648
      const std::string full_name = "RSA/" + padding_name;
63✔
649
      const OID oid = OID::from_string(full_name);
63✔
650
      return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM);
58✔
651
   } catch(Lookup_Error&) {}
63✔
652

653
   if(padding_name.starts_with("PSS(")) {
5✔
654
      auto parameters = PSS_Params::from_padding_name(m_padding->name()).serialize();
5✔
655
      return AlgorithmIdentifier("RSA/PSS", parameters);
4✔
656
   }
4✔
657

658
   throw Invalid_Argument(fmt("Signatures using RSA/{} are not supported", padding_name));
2✔
659
}
62✔
660

661
class RSA_Decryption_Operation final : public PK_Ops::Decryption_with_Padding,
662
                                       private RSA_Private_Operation {
663
   public:
664
      RSA_Decryption_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
291✔
665
            PK_Ops::Decryption_with_Padding(padding), RSA_Private_Operation(rsa, rng) {}
291✔
666

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

669
      secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input) override {
5,185✔
670
         secure_vector<uint8_t> out(public_modulus_bytes());
5,185✔
671
         raw_op(out, input);
5,185✔
672
         return out;
5,158✔
673
      }
27✔
674
};
675

676
class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KDF,
677
                                           private RSA_Private_Operation {
678
   public:
679
      RSA_KEM_Decryption_Operation(const RSA_PrivateKey& key, std::string_view kdf, RandomNumberGenerator& rng) :
22✔
680
            PK_Ops::KEM_Decryption_with_KDF(kdf), RSA_Private_Operation(key, rng) {}
22✔
681

682
      size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
71✔
683

684
      size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
10✔
685

686
      void raw_kem_decrypt(std::span<uint8_t> out_shared_key, std::span<const uint8_t> encapsulated_key) override {
31✔
687
         raw_op(out_shared_key, encapsulated_key);
31✔
688
      }
31✔
689
};
690

691
/**
692
* RSA public (encrypt/verify) operation
693
*/
694
class RSA_Public_Operation {
×
695
   public:
696
      explicit RSA_Public_Operation(const RSA_PublicKey& rsa) : m_public(rsa.public_data()) {}
18,311✔
697

698
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
30,455✔
699

700
   protected:
701
      BigInt public_op(const BigInt& m) const {
30,891✔
702
         if(m >= m_public->get_n()) {
30,891✔
703
            throw Decoding_Error("RSA public op - input is too large");
49✔
704
         }
705

706
         return m_public->public_op(m);
30,842✔
707
      }
708

709
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
31,248✔
710

711
      const BigInt& get_n() const { return m_public->get_n(); }
22✔
712

713
   private:
714
      std::shared_ptr<const RSA_Public_Data> m_public;
715
};
716

717
class RSA_Encryption_Operation final : public PK_Ops::Encryption_with_Padding,
×
718
                                       private RSA_Public_Operation {
719
   public:
720
      RSA_Encryption_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
297✔
721
            PK_Ops::Encryption_with_Padding(padding), RSA_Public_Operation(rsa) {}
297✔
722

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

725
      size_t max_ptext_input_bits() const override { return public_modulus_bits() - 1; }
553✔
726

727
      std::vector<uint8_t> raw_encrypt(std::span<const uint8_t> input, RandomNumberGenerator& /*rng*/) override {
365✔
728
         const BigInt input_bn(input);
365✔
729
         return public_op(input_bn).serialize(public_modulus_bytes());
730✔
730
      }
365✔
731
};
732

733
class RSA_Verify_Operation final : public PK_Ops::Verification,
×
734
                                   private RSA_Public_Operation {
735
   public:
736
      void update(std::span<const uint8_t> msg) override { m_padding->update(msg.data(), msg.size()); }
30,569✔
737

738
      bool is_valid_signature(std::span<const uint8_t> sig) override {
30,572✔
739
         const auto msg = m_padding->raw_data();
30,572✔
740
         const auto message_repr = recover_message_repr(sig.data(), sig.size());
30,572✔
741
         return m_padding->verify(message_repr, msg, public_modulus_bits() - 1);
30,455✔
742
      }
60,843✔
743

744
      RSA_Verify_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
18,311✔
745
            RSA_Public_Operation(rsa), m_padding(SignaturePaddingScheme::create_or_throw(padding)) {}
18,311✔
746

747
      std::string hash_function() const override { return m_padding->hash_function(); }
16,008✔
748

749
   private:
750
      std::vector<uint8_t> recover_message_repr(const uint8_t input[], size_t input_len) {
30,572✔
751
         if(input_len > public_modulus_bytes()) {
30,572✔
752
            throw Decoding_Error("RSA signature too large to be valid for this key");
68✔
753
         }
754
         const BigInt input_bn(input, input_len);
30,504✔
755
         return public_op(input_bn).serialize();
91,414✔
756
      }
30,504✔
757

758
      std::unique_ptr<SignaturePaddingScheme> m_padding;
759
};
760

761
class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KDF,
×
762
                                           private RSA_Public_Operation {
763
   public:
764
      RSA_KEM_Encryption_Operation(const RSA_PublicKey& key, std::string_view kdf) :
22✔
765
            PK_Ops::KEM_Encryption_with_KDF(kdf), RSA_Public_Operation(key) {}
22✔
766

767
   private:
768
      size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
44✔
769

770
      size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
77✔
771

772
      void raw_kem_encrypt(std::span<uint8_t> out_encapsulated_key,
22✔
773
                           std::span<uint8_t> raw_shared_key,
774
                           RandomNumberGenerator& rng) override {
775
         const BigInt r = BigInt::random_integer(rng, BigInt::one(), get_n());
22✔
776
         const BigInt c = public_op(r);
22✔
777

778
         c.serialize_to(out_encapsulated_key);
22✔
779
         r.serialize_to(raw_shared_key);
22✔
780
      }
22✔
781
};
782

783
}  // namespace
784

785
std::unique_ptr<PK_Ops::Encryption> RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
861✔
786
                                                                        std::string_view params,
787
                                                                        std::string_view provider) const {
788
   if(provider == "base" || provider.empty()) {
1,050✔
789
      return std::make_unique<RSA_Encryption_Operation>(*this, params);
297✔
790
   }
791
   throw Provider_Not_Found(algo_name(), provider);
1,128✔
792
}
793

794
std::unique_ptr<PK_Ops::KEM_Encryption> RSA_PublicKey::create_kem_encryption_op(std::string_view params,
22✔
795
                                                                                std::string_view provider) const {
796
   if(provider == "base" || provider.empty()) {
22✔
797
      return std::make_unique<RSA_KEM_Encryption_Operation>(*this, params);
22✔
798
   }
799
   throw Provider_Not_Found(algo_name(), provider);
×
800
}
801

802
std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_verification_op(std::string_view params,
4,750✔
803
                                                                            std::string_view provider) const {
804
   if(provider == "base" || provider.empty()) {
5,666✔
805
      return std::make_unique<RSA_Verify_Operation>(*this, params);
2,008✔
806
   }
807

808
   throw Provider_Not_Found(algo_name(), provider);
5,484✔
809
}
810

811
namespace {
812

813
std::string parse_rsa_signature_algorithm(const AlgorithmIdentifier& alg_id) {
16,306✔
814
   const auto sig_info = split_on(alg_id.oid().to_formatted_string(), '/');
16,306✔
815

816
   if(sig_info.empty() || sig_info.size() != 2 || sig_info[0] != "RSA") {
16,306✔
817
      throw Decoding_Error("Unknown AlgorithmIdentifier for RSA X.509 signatures");
1✔
818
   }
819

820
   std::string padding = sig_info[1];
16,305✔
821

822
   if(padding == "PSS") {
16,305✔
823
      // "MUST contain RSASSA-PSS-params"
824
      if(alg_id.parameters().empty()) {
509✔
825
         throw Decoding_Error("PSS params must be provided");
×
826
      }
827

828
      const PSS_Params pss_params(alg_id.parameters());
511✔
829

830
      // hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
831
      // We also support SHA-3 (is also supported by e.g. OpenSSL and bouncycastle)
832
      const std::string hash_algo = pss_params.hash_function();
509✔
833
      if(hash_algo != "SHA-1" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384" &&
490✔
834
         hash_algo != "SHA-512" && hash_algo != "SHA-3(224)" && hash_algo != "SHA-3(256)" &&
10✔
835
         hash_algo != "SHA-3(384)" && hash_algo != "SHA-3(512)") {
509✔
836
         throw Decoding_Error("Unacceptable hash for PSS signatures");
×
837
      }
838

839
      if(pss_params.mgf_function() != "MGF1") {
509✔
840
         throw Decoding_Error("Unacceptable MGF for PSS signatures");
×
841
      }
842

843
      // For MGF1, it is strongly RECOMMENDED that the underlying hash
844
      // function be the same as the one identified by hashAlgorithm
845
      if(pss_params.hash_algid() != pss_params.mgf_hash_algid()) {
509✔
846
         throw Decoding_Error("Unacceptable MGF hash for PSS signatures");
2✔
847
      }
848

849
      if(pss_params.trailer_field() != 1) {
507✔
850
         throw Decoding_Error("Unacceptable trailer field for PSS signatures");
×
851
      }
852

853
      padding += fmt("({},MGF1,{})", hash_algo, pss_params.salt_length());
1,016✔
854
   }
509✔
855

856
   return padding;
16,303✔
857
}
16,306✔
858

859
}  // namespace
860

861
std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_x509_verification_op(const AlgorithmIdentifier& alg_id,
16,306✔
862
                                                                                 std::string_view provider) const {
863
   if(provider == "base" || provider.empty()) {
16,306✔
864
      return std::make_unique<RSA_Verify_Operation>(*this, parse_rsa_signature_algorithm(alg_id));
16,306✔
865
   }
866

867
   throw Provider_Not_Found(algo_name(), provider);
×
868
}
869

870
std::unique_ptr<PK_Ops::Decryption> RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
930✔
871
                                                                         std::string_view params,
872
                                                                         std::string_view provider) const {
873
   if(provider == "base" || provider.empty()) {
1,144✔
874
      return std::make_unique<RSA_Decryption_Operation>(*this, params, rng);
291✔
875
   }
876

877
   throw Provider_Not_Found(algo_name(), provider);
1,278✔
878
}
879

880
std::unique_ptr<PK_Ops::KEM_Decryption> RSA_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
22✔
881
                                                                                 std::string_view params,
882
                                                                                 std::string_view provider) const {
883
   if(provider == "base" || provider.empty()) {
22✔
884
      return std::make_unique<RSA_KEM_Decryption_Operation>(*this, params, rng);
22✔
885
   }
886

887
   throw Provider_Not_Found(algo_name(), provider);
×
888
}
889

890
std::unique_ptr<PK_Ops::Signature> RSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
2,251✔
891
                                                                       std::string_view params,
892
                                                                       std::string_view provider) const {
893
   if(provider == "base" || provider.empty()) {
2,593✔
894
      return std::make_unique<RSA_Signature_Operation>(*this, params, rng);
1,231✔
895
   }
896

897
   throw Provider_Not_Found(algo_name(), provider);
2,040✔
898
}
899

900
}  // 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