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

randombit / botan / 23931252384

03 Apr 2026 02:35AM UTC coverage: 89.461% (-0.06%) from 89.524%
23931252384

Pull #5514

github

web-flow
Merge ac6c66214 into 042e5bd98
Pull Request #5514: Add BER_Decoder::Limits

105548 of 117982 relevant lines covered (89.46%)

11556564.64 hits per line

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

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

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

51
      const BigInt& get_n() const { return m_n; }
55,671✔
52

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

55
      size_t public_modulus_bits() const { return m_public_modulus_bits; }
45,775✔
56

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

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

61
      const Barrett_Reduction& reducer_mod_n() const { return m_mod_n; }
1,545✔
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; }
816✔
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,215✔
98

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

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

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

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

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

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

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

113
      bool primes_imbalanced() const { return p_bits() != q_bits(); }
7,030✔
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,096✔
131
   return m_public;
20,096✔
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,190✔
149
   return m_public->get_n();
1,190✔
150
}
151

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

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

163
RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
18,702✔
164
   BigInt n;
18,702✔
165
   BigInt e;
18,702✔
166
   BER_Decoder(key_bits, BER_Decoder::Limits::DER()).start_sequence().decode(n).decode(e).end_cons().verify_end();
37,703✔
167

168
   init(std::move(n), std::move(e));
18,385✔
169
}
19,450✔
170

171
bool RSA_PublicKey::supports_operation(PublicKeyOperation op) const {
1,420✔
172
   return op == PublicKeyOperation::Signature || op == PublicKeyOperation::Encryption ||
1,420✔
173
          op == PublicKeyOperation::KeyEncapsulation;
1,420✔
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,783✔
183
   return m_public->public_modulus_bits();
7,783✔
184
}
185

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

190
AlgorithmIdentifier RSA_PublicKey::algorithm_identifier() const {
757✔
191
   return AlgorithmIdentifier(object_identifier(), AlgorithmIdentifier::USE_NULL_PARAM);
757✔
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 {
415✔
199
   std::vector<uint8_t> output;
415✔
200
   DER_Encoder der(output);
415✔
201
   der.start_sequence().encode(get_n()).encode(get_e()).end_cons();
415✔
202

203
   return output;
415✔
204
}
415✔
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,545✔
217
   return m_private;
1,545✔
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,018✔
266
   BigInt n;
1,018✔
267
   BigInt e;
1,018✔
268
   BigInt d;
1,018✔
269
   BigInt p;
1,018✔
270
   BigInt q;
1,018✔
271
   BigInt d1;
1,018✔
272
   BigInt d2;
1,018✔
273
   BigInt c;
1,018✔
274

275
   BER_Decoder(key_bits, BER_Decoder::Limits::DER())
2,036✔
276
      .start_sequence()
1,018✔
277
      .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
2,031✔
278
      .decode(n)
1,013✔
279
      .decode(e)
1,009✔
280
      .decode(d)
1,009✔
281
      .decode(p)
1,009✔
282
      .decode(q)
1,009✔
283
      .decode(d1)
1,008✔
284
      .decode(d2)
1,007✔
285
      .decode(c)
1,006✔
286
      .end_cons()
1,006✔
287
      .verify_end();
1,006✔
288

289
   RSA_PublicKey::init(std::move(n), std::move(e));
1,006✔
290

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

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

303
   BigInt e = exp;
566✔
304

305
   BigInt d = d_exp;
566✔
306

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

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

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

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

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

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

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

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

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

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

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

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

358
      n = p * q;
69✔
359

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

364
      break;
69✔
365
   }
80✔
366

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

459
   return true;
460
}
461

462
namespace {
463

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

481
   const size_t n_words = 2 * p_words;
6,215✔
482

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

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

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

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

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

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

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

513
   return BigInt::_from_words(r);
6,215✔
514
}
12,430✔
515

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

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

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

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

548
         const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
7,031✔
549
         BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
14,060✔
550
         BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(), "output size check");
7,030✔
551
         recovered.serialize_to(out);
7,030✔
552
      }
7,053✔
553

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

564
         static constexpr size_t powm_window = 4;
6,215✔
565

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

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

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

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

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

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

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

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

604
         return crt_recombine(j1, j2_p, j2, m_private->get_c_monty(), m_private->get_p(), m_private->get_q());
6,215✔
605
      }
12,430✔
606

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

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

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

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

627
         std::vector<uint8_t> out(public_modulus_bytes());
1,624✔
628
         raw_op(out, padded);
1,624✔
629
         return out;
1,624✔
630
      }
3,247✔
631

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

634
      AlgorithmIdentifier algorithm_identifier() const override;
635

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

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

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

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

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

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

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

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

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

670
      secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input) override {
5,398✔
671
         secure_vector<uint8_t> out(public_modulus_bytes());
5,398✔
672
         raw_op(out, input);
5,398✔
673
         return out;
5,375✔
674
      }
23✔
675
};
676

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

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

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

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

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

699
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
45,773✔
700

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

707
         return m_public->public_op(m);
46,153✔
708
      }
709

710
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
46,513✔
711

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

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

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

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

726
      size_t max_ptext_input_bits() const override { return public_modulus_bits() - 1; }
546✔
727

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

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

739
      bool is_valid_signature(std::span<const uint8_t> sig) override {
45,844✔
740
         const auto msg = m_padding->raw_data();
45,844✔
741
         const auto message_repr = recover_message_repr(sig.data(), sig.size());
45,844✔
742
         return m_padding->verify(message_repr, msg, public_modulus_bits() - 1);
45,773✔
743
      }
91,395✔
744

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

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

750
   private:
751
      std::vector<uint8_t> recover_message_repr(const uint8_t input[], size_t input_len) {
45,844✔
752
         if(input_len > public_modulus_bytes()) {
45,844✔
753
            throw Decoding_Error("RSA signature too large to be valid for this key");
4✔
754
         }
755
         const BigInt input_bn(input, input_len);
45,840✔
756
         return public_op(input_bn).serialize();
137,386✔
757
      }
45,840✔
758

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

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

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

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

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

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

784
}  // namespace
785

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

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

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

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

812
namespace {
813

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

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

821
   std::string padding = sig_info[1];
16,232✔
822

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

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

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

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

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

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

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

857
   return padding;
16,230✔
858
}
16,232✔
859

860
}  // namespace
861

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

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

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

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

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

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

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

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

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