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

randombit / botan / 13064650714

31 Jan 2025 01:33AM UTC coverage: 91.22% (-0.009%) from 91.229%
13064650714

Pull #4617

github

web-flow
Merge 8770e3cff into 1564edf7b
Pull Request #4617: Fix build/test errors caught by test_all_configs.py

94145 of 103207 relevant lines covered (91.22%)

11401116.62 hits per line

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

94.39
/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/reducer.h>
15
#include <botan/internal/blinding.h>
16
#include <botan/internal/divide.h>
17
#include <botan/internal/emsa.h>
18
#include <botan/internal/fmt.h>
19
#include <botan/internal/keypair.h>
20
#include <botan/internal/mod_inv.h>
21
#include <botan/internal/monty.h>
22
#include <botan/internal/monty_exp.h>
23
#include <botan/internal/parsing.h>
24
#include <botan/internal/pk_ops_impl.h>
25
#include <botan/internal/workfactor.h>
26

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

31
namespace Botan {
32

33
class RSA_Public_Data final {
34
   public:
35
      RSA_Public_Data(BigInt&& n, BigInt&& e) :
17,472✔
36
            m_n(std::move(n)),
17,472✔
37
            m_e(std::move(e)),
17,472✔
38
            m_mod_n(Modular_Reducer::for_public_modulus(m_n)),
17,472✔
39
            m_monty_n(std::make_shared<Montgomery_Params>(m_n, m_mod_n)),
17,472✔
40
            m_public_modulus_bits(m_n.bits()),
17,472✔
41
            m_public_modulus_bytes(m_n.bytes()) {}
17,472✔
42

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

49
      const BigInt& get_n() const { return m_n; }
36,289✔
50

51
      const BigInt& get_e() const { return m_e; }
5✔
52

53
      size_t public_modulus_bits() const { return m_public_modulus_bits; }
26,769✔
54

55
      size_t public_modulus_bytes() const { return m_public_modulus_bytes; }
47,584✔
56

57
      const std::shared_ptr<const Montgomery_Params>& monty_n() const { return m_monty_n; }
783✔
58

59
      const Modular_Reducer& reducer_mod_n() const { return m_mod_n; }
1,517✔
60

61
   private:
62
      BigInt m_n;
63
      BigInt m_e;
64
      Modular_Reducer m_mod_n;
65
      std::shared_ptr<const Montgomery_Params> m_monty_n;
66
      size_t m_public_modulus_bits;
67
      size_t m_public_modulus_bytes;
68
};
69

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

85
      const BigInt& get_d() const { return m_d; }
784✔
86

87
      const BigInt& get_p() const { return m_p; }
5,997✔
88

89
      const BigInt& get_q() const { return m_q; }
11,993✔
90

91
      const BigInt& get_d1() const { return m_d1; }
5,996✔
92

93
      const BigInt& get_d2() const { return m_d2; }
5,996✔
94

95
      const BigInt& get_c() const { return m_c; }
×
96

97
      const Montgomery_Int& get_c_monty() const { return m_c_monty; }
5,996✔
98

99
      const std::shared_ptr<const Montgomery_Params>& monty_p() const { return m_monty_p; }
11,992✔
100

101
      const std::shared_ptr<const Montgomery_Params>& monty_q() const { return m_monty_q; }
5,996✔
102

103
      size_t p_bits() const { return m_p_bits; }
8,296✔
104

105
      size_t q_bits() const { return m_q_bits; }
8,296✔
106

107
      bool primes_imbalanced() const { return p_bits() != q_bits(); }
6,779✔
108

109
   private:
110
      BigInt m_d;
111
      BigInt m_p;
112
      BigInt m_q;
113
      BigInt m_d1;
114
      BigInt m_d2;
115
      BigInt m_c;
116

117
      std::shared_ptr<const Montgomery_Params> m_monty_p;
118
      std::shared_ptr<const Montgomery_Params> m_monty_q;
119
      Montgomery_Int m_c_monty;
120
      size_t m_p_bits;
121
      size_t m_q_bits;
122
};
123

124
std::shared_ptr<const RSA_Public_Data> RSA_PublicKey::public_data() const {
16,635✔
125
   return m_public;
16,635✔
126
}
127

128
const BigInt& RSA_PublicKey::get_int_field(std::string_view field) const {
10✔
129
   if(field == "n") {
10✔
130
      return m_public->get_n();
5✔
131
   } else if(field == "e") {
5✔
132
      return m_public->get_e();
3✔
133
   } else {
134
      return Public_Key::get_int_field(field);
2✔
135
   }
136
}
137

138
std::unique_ptr<Private_Key> RSA_PublicKey::generate_another(RandomNumberGenerator& rng) const {
2✔
139
   return std::make_unique<RSA_PrivateKey>(rng, m_public->public_modulus_bits(), m_public->get_e().to_u32bit());
2✔
140
}
141

142
const BigInt& RSA_PublicKey::get_n() const {
957✔
143
   return m_public->get_n();
957✔
144
}
145

146
const BigInt& RSA_PublicKey::get_e() const {
928✔
147
   return m_public->get_e();
928✔
148
}
149

150
void RSA_PublicKey::init(BigInt&& n, BigInt&& e) {
18,252✔
151
   if(n.is_negative() || n.is_even() || n.bits() < 5 /* n >= 3*5 */ || e.is_negative() || e.is_even()) {
54,168✔
152
      throw Decoding_Error("Invalid RSA public key parameters");
780✔
153
   }
154
   m_public = std::make_shared<RSA_Public_Data>(std::move(n), std::move(e));
17,472✔
155
}
17,472✔
156

157
RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
15,666✔
158
   BigInt n, e;
15,666✔
159
   BER_Decoder(key_bits).start_sequence().decode(n).decode(e).end_cons();
16,495✔
160

161
   init(std::move(n), std::move(e));
15,632✔
162
}
16,477✔
163

164
bool RSA_PublicKey::supports_operation(PublicKeyOperation op) const {
1,466✔
165
   return op == PublicKeyOperation::Signature || op == PublicKeyOperation::Encryption ||
1,466✔
166
          op == PublicKeyOperation::KeyEncapsulation;
1,466✔
167
}
168

169
RSA_PublicKey::RSA_PublicKey(const BigInt& modulus, const BigInt& exponent) {
987✔
170
   BigInt n = modulus;
987✔
171
   BigInt e = exponent;
987✔
172
   init(std::move(n), std::move(e));
987✔
173
}
988✔
174

175
size_t RSA_PublicKey::key_length() const {
4,942✔
176
   return m_public->public_modulus_bits();
4,942✔
177
}
178

179
size_t RSA_PublicKey::estimated_strength() const {
3,545✔
180
   return if_work_factor(key_length());
3,545✔
181
}
182

183
AlgorithmIdentifier RSA_PublicKey::algorithm_identifier() const {
761✔
184
   return AlgorithmIdentifier(object_identifier(), AlgorithmIdentifier::USE_NULL_PARAM);
761✔
185
}
186

187
std::vector<uint8_t> RSA_PublicKey::raw_public_key_bits() const {
3✔
188
   throw Not_Implemented("an RSA public key does not provide a raw binary representation.");
3✔
189
}
190

191
std::vector<uint8_t> RSA_PublicKey::public_key_bits() const {
419✔
192
   std::vector<uint8_t> output;
419✔
193
   DER_Encoder der(output);
419✔
194
   der.start_sequence().encode(get_n()).encode(get_e()).end_cons();
419✔
195

196
   return output;
419✔
197
}
419✔
198

199
/*
200
* Check RSA Public Parameters
201
*/
202
bool RSA_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*strong*/) const {
9✔
203
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
27✔
204
      return false;
×
205
   }
206
   return true;
207
}
208

209
std::shared_ptr<const RSA_Private_Data> RSA_PrivateKey::private_data() const {
1,517✔
210
   return m_private;
1,517✔
211
}
212

213
secure_vector<uint8_t> RSA_PrivateKey::private_key_bits() const {
99✔
214
   return DER_Encoder()
198✔
215
      .start_sequence()
99✔
216
      .encode(static_cast<size_t>(0))
99✔
217
      .encode(get_n())
99✔
218
      .encode(get_e())
99✔
219
      .encode(get_d())
99✔
220
      .encode(get_p())
99✔
221
      .encode(get_q())
99✔
222
      .encode(get_d1())
99✔
223
      .encode(get_d2())
99✔
224
      .encode(get_c())
99✔
225
      .end_cons()
99✔
226
      .get_contents();
198✔
227
}
228

229
const BigInt& RSA_PrivateKey::get_p() const {
186✔
230
   return m_private->get_p();
186✔
231
}
232

233
const BigInt& RSA_PrivateKey::get_q() const {
174✔
234
   return m_private->get_q();
174✔
235
}
236

237
const BigInt& RSA_PrivateKey::get_d() const {
142✔
238
   return m_private->get_d();
142✔
239
}
240

241
const BigInt& RSA_PrivateKey::get_c() const {
112✔
242
   return m_private->get_c();
112✔
243
}
244

245
const BigInt& RSA_PrivateKey::get_d1() const {
112✔
246
   return m_private->get_d1();
112✔
247
}
248

249
const BigInt& RSA_PrivateKey::get_d2() const {
112✔
250
   return m_private->get_d2();
112✔
251
}
252

253
void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) {
1,630✔
254
   m_private = std::make_shared<RSA_Private_Data>(
1,630✔
255
      std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
1,630✔
256
}
1,630✔
257

258
RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
1,024✔
259
   BigInt n, e, d, p, q, d1, d2, c;
1,024✔
260

261
   BER_Decoder(key_bits)
2,046✔
262
      .start_sequence()
1,040✔
263
      .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
2,041✔
264
      .decode(n)
1,019✔
265
      .decode(e)
1,018✔
266
      .decode(d)
1,017✔
267
      .decode(p)
1,017✔
268
      .decode(q)
1,017✔
269
      .decode(d1)
1,016✔
270
      .decode(d2)
1,015✔
271
      .decode(c)
1,011✔
272
      .end_cons();
1,011✔
273

274
   RSA_PublicKey::init(std::move(n), std::move(e));
1,008✔
275

276
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
1,006✔
277
}
1,150✔
278

279
RSA_PrivateKey::RSA_PrivateKey(
558✔
280
   const BigInt& prime1, const BigInt& prime2, const BigInt& exp, const BigInt& d_exp, const BigInt& mod) {
558✔
281
   BigInt p = prime1;
558✔
282
   BigInt q = prime2;
558✔
283
   BigInt n = mod;
558✔
284
   if(n.is_zero()) {
1,116✔
285
      n = p * q;
557✔
286
   }
287

288
   BigInt e = exp;
558✔
289

290
   BigInt d = d_exp;
558✔
291

292
   const BigInt p_minus_1 = p - 1;
558✔
293
   const BigInt q_minus_1 = q - 1;
558✔
294

295
   if(d.is_zero()) {
1,116✔
296
      const BigInt phi_n = lcm(p_minus_1, q_minus_1);
557✔
297
      d = compute_rsa_secret_exponent(e, phi_n, p, q);
557✔
298
   }
557✔
299

300
   BigInt d1 = ct_modulo(d, p_minus_1);
558✔
301
   BigInt d2 = ct_modulo(d, q_minus_1);
558✔
302
   BigInt c = inverse_mod_secret_prime(ct_modulo(q, p), p);
558✔
303

304
   RSA_PublicKey::init(std::move(n), std::move(e));
558✔
305

306
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
558✔
307
}
1,674✔
308

309
/*
310
* Create a RSA private key
311
*/
312
RSA_PrivateKey::RSA_PrivateKey(RandomNumberGenerator& rng, size_t bits, size_t exp) {
67✔
313
   if(bits < 1024) {
67✔
314
      throw Invalid_Argument(fmt("Cannot create an RSA key only {} bits long", bits));
×
315
   }
316

317
   if(exp < 3 || exp % 2 == 0) {
67✔
318
      throw Invalid_Argument("Invalid RSA encryption exponent");
×
319
   }
320

321
   const size_t p_bits = (bits + 1) / 2;
67✔
322
   const size_t q_bits = bits - p_bits;
67✔
323

324
   BigInt p, q, n;
67✔
325
   BigInt e = BigInt::from_u64(exp);
67✔
326

327
   for(size_t attempt = 0;; ++attempt) {
11✔
328
      if(attempt > 10) {
78✔
329
         throw Internal_Error("RNG failure during RSA key generation");
1✔
330
      }
331

332
      // TODO could generate primes in thread pool
333
      p = generate_rsa_prime(rng, rng, p_bits, e);
77✔
334
      q = generate_rsa_prime(rng, rng, q_bits, e);
78✔
335

336
      const BigInt diff = p - q;
77✔
337
      if(diff.bits() < (bits / 2) - 100) {
77✔
338
         continue;
11✔
339
      }
340

341
      n = p * q;
66✔
342

343
      if(n.bits() != bits) {
66✔
344
         continue;
×
345
      }
346

347
      break;
66✔
348
   }
11✔
349

350
   const BigInt p_minus_1 = p - 1;
66✔
351
   const BigInt q_minus_1 = q - 1;
66✔
352

353
   const BigInt phi_n = lcm(p_minus_1, q_minus_1);
66✔
354
   // This is guaranteed because p,q == 3 mod 4
355
   BOTAN_DEBUG_ASSERT(low_zero_bits(phi_n) == 1);
66✔
356

357
   BigInt d = compute_rsa_secret_exponent(e, phi_n, p, q);
66✔
358
   BigInt d1 = ct_modulo(d, p_minus_1);
66✔
359
   BigInt d2 = ct_modulo(d, q_minus_1);
66✔
360
   BigInt c = inverse_mod_secret_prime(ct_modulo(q, p), p);
66✔
361

362
   RSA_PublicKey::init(std::move(n), std::move(e));
66✔
363

364
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
66✔
365
}
268✔
366

367
const BigInt& RSA_PrivateKey::get_int_field(std::string_view field) const {
6✔
368
   if(field == "p") {
6✔
369
      return m_private->get_p();
1✔
370
   } else if(field == "q") {
5✔
371
      return m_private->get_q();
1✔
372
   } else if(field == "d") {
4✔
373
      return m_private->get_d();
1✔
374
   } else if(field == "c") {
3✔
375
      return m_private->get_c();
×
376
   } else if(field == "d1") {
3✔
377
      return m_private->get_d1();
×
378
   } else if(field == "d2") {
3✔
379
      return m_private->get_d2();
×
380
   } else {
381
      return RSA_PublicKey::get_int_field(field);
3✔
382
   }
383
}
384

385
std::unique_ptr<Public_Key> RSA_PrivateKey::public_key() const {
354✔
386
   return std::make_unique<RSA_PublicKey>(get_n(), get_e());
354✔
387
}
388

389
/*
390
* Check Private RSA Parameters
391
*/
392
bool RSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const {
11✔
393
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
33✔
394
      return false;
×
395
   }
396

397
   if(get_d() < 2 || get_p() < 3 || get_q() < 3) {
11✔
398
      return false;
×
399
   }
400

401
   if(get_p() * get_q() != get_n()) {
33✔
402
      return false;
403
   }
404

405
   if(get_p() == get_q()) {
11✔
406
      return false;
407
   }
408

409
   if(get_d1() != ct_modulo(get_d(), get_p() - 1)) {
33✔
410
      return false;
411
   }
412
   if(get_d2() != ct_modulo(get_d(), get_q() - 1)) {
33✔
413
      return false;
414
   }
415
   if(get_c() != inverse_mod_secret_prime(ct_modulo(get_q(), get_p()), get_p())) {
33✔
416
      return false;
417
   }
418

419
   const size_t prob = (strong) ? 128 : 12;
11✔
420

421
   if(!is_prime(get_p(), rng, prob)) {
11✔
422
      return false;
423
   }
424
   if(!is_prime(get_q(), rng, prob)) {
10✔
425
      return false;
426
   }
427

428
   if(strong) {
10✔
429
      if(ct_modulo(get_e() * get_d(), lcm(get_p() - 1, get_q() - 1)) != 1) {
56✔
430
         return false;
431
      }
432

433
#if defined(BOTAN_HAS_PSS) && defined(BOTAN_HAS_SHA_256)
434
      const std::string padding = "PSS(SHA-256)";
8✔
435
#else
436
      const std::string padding = "Raw";
437
#endif
438

439
      return KeyPair::signature_consistency_check(rng, *this, padding);
8✔
440
   }
8✔
441

442
   return true;
443
}
444

445
namespace {
446

447
/**
448
* RSA private (decrypt/sign) operation
449
*/
450
class RSA_Private_Operation {
451
   protected:
452
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
1,625✔
453

454
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
8,424✔
455

456
      explicit RSA_Private_Operation(const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
1,517✔
457
            m_public(rsa.public_data()),
1,517✔
458
            m_private(rsa.private_data()),
1,517✔
459
            m_blinder(
1,517✔
460
               m_public->reducer_mod_n(),
1,517✔
461
               rng,
462
               [this](const BigInt& k) { return m_public->public_op(k); },
3,045✔
463
               [this](const BigInt& k) { return inverse_mod_rsa_public_modulus(k, m_public->get_n()); }),
3,045✔
464
            m_blinding_bits(64),
1,517✔
465
            m_max_d1_bits(m_private->p_bits() + m_blinding_bits),
1,517✔
466
            m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {}
1,517✔
467

468
      void raw_op(std::span<uint8_t> out, std::span<const uint8_t> input) {
6,800✔
469
         if(input.size() > public_modulus_bytes()) {
6,800✔
470
            throw Decoding_Error("RSA input is too long for this key");
×
471
         }
472
         const BigInt input_bn(input.data(), input.size());
6,800✔
473
         if(input_bn >= m_public->get_n()) {
6,800✔
474
            throw Decoding_Error("RSA input is too large for this key");
20✔
475
         }
476
         // TODO: This should be a function on blinder
477
         // BigInt Blinder::run_blinded_function(std::function<BigInt, BigInt> fn, const BigInt& input);
478

479
         const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
13,579✔
480
         BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
20,337✔
481
         BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(), "output size check");
6,779✔
482
         recovered.serialize_to(out);
6,779✔
483
      }
13,558✔
484

485
   private:
486
      BigInt rsa_private_op(const BigInt& m) const {
6,779✔
487
         /*
488
         All normal implementations generate p/q of the same bitlength,
489
         so this should rarely occur in practice
490
         */
491
         if(m_private->primes_imbalanced()) {
6,779✔
492
            return monty_exp(m_public->monty_n(), m, m_private->get_d(), m_public->get_n().bits()).value();
783✔
493
         }
494

495
         static constexpr size_t powm_window = 4;
5,996✔
496

497
         // Compute this in main thread to avoid racing on the rng
498
         const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
5,996✔
499

500
#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
501
   #define BOTAN_RSA_USE_ASYNC
502
#endif
503

504
#if defined(BOTAN_RSA_USE_ASYNC)
505
         /*
506
         * Precompute m.sig_words in the main thread before calling async. Otherwise
507
         * the two threads race (during Modular_Reducer::reduce) and while the output
508
         * is correct in both threads, helgrind warns.
509
         */
510
         m.sig_words();
5,996✔
511

512
         auto future_j1 = Thread_Pool::global_instance().run([this, &m, &d1_mask]() {
5,996✔
513
#endif
514
            const BigInt masked_d1 = m_private->get_d1() + (d1_mask * (m_private->get_p() - 1));
11,992✔
515
            auto powm_d1_p = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_p(), m), powm_window);
5,996✔
516
            auto j1 = monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
5,996✔
517

518
#if defined(BOTAN_RSA_USE_ASYNC)
519
            return j1;
5,996✔
520
         });
17,988✔
521
#endif
522

523
         const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
5,996✔
524
         const BigInt masked_d2 = m_private->get_d2() + (d2_mask * (m_private->get_q() - 1));
11,992✔
525
         auto powm_d2_q = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_q(), m), powm_window);
5,996✔
526
         const auto j2 = monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits).value();
5,996✔
527

528
#if defined(BOTAN_RSA_USE_ASYNC)
529
         auto j1 = future_j1.get();
5,996✔
530
#endif
531

532
         /*
533
         * To recover the final value from the CRT representation (j1,j2)
534
         * we use Garner's algorithm:
535
         * c = q^-1 mod p (this is precomputed)
536
         * h = c*(j1-j2) mod p
537
         * m = j2 + h*q
538
         */
539

540
         const auto j2_p = Montgomery_Int::from_wide_int(m_private->monty_p(), j2);
5,996✔
541

542
         /**
543
         * This doesn't quite match up with the "Smooth-CRT" proposal; there we
544
         * would multiply by c * R2 so would have the effect of both multiplying
545
         * by c and immediately converting from Montgomery to standard form.
546
         */
547
         j1 = (j1 - j2_p) * m_private->get_c_monty();
5,996✔
548
         return j1.value() * m_private->get_q() + j2;
11,992✔
549
      }
35,976✔
550

551
      std::shared_ptr<const RSA_Public_Data> m_public;
552
      std::shared_ptr<const RSA_Private_Data> m_private;
553

554
      // XXX could the blinder starting pair be shared?
555
      Blinder m_blinder;
556
      const size_t m_blinding_bits;
557
      const size_t m_max_d1_bits;
558
      const size_t m_max_d2_bits;
559
};
560

561
class RSA_Signature_Operation final : public PK_Ops::Signature,
×
562
                                      private RSA_Private_Operation {
563
   public:
564
      void update(std::span<const uint8_t> msg) override { m_emsa->update(msg.data(), msg.size()); }
1,626✔
565

566
      std::vector<uint8_t> sign(RandomNumberGenerator& rng) override {
1,625✔
567
         const size_t max_input_bits = public_modulus_bits() - 1;
1,625✔
568
         const auto msg = m_emsa->raw_data();
1,625✔
569
         const auto padded = m_emsa->encoding_of(msg, max_input_bits, rng);
1,625✔
570

571
         std::vector<uint8_t> out(public_modulus_bytes());
1,624✔
572
         raw_op(out, padded);
1,624✔
573
         return out;
1,624✔
574
      }
3,247✔
575

576
      size_t signature_length() const override { return public_modulus_bytes(); }
333✔
577

578
      AlgorithmIdentifier algorithm_identifier() const override;
579

580
      std::string hash_function() const override { return m_emsa->hash_function(); }
125✔
581

582
      RSA_Signature_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
1,226✔
583
            RSA_Private_Operation(rsa, rng), m_emsa(EMSA::create_or_throw(padding)) {}
1,226✔
584

585
   private:
586
      std::unique_ptr<EMSA> m_emsa;
587
};
588

589
AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier() const {
80✔
590
   const std::string emsa_name = m_emsa->name();
80✔
591

592
   try {
80✔
593
      const std::string full_name = "RSA/" + emsa_name;
80✔
594
      const OID oid = OID::from_string(full_name);
80✔
595
      return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM);
58✔
596
   } catch(Lookup_Error&) {}
80✔
597

598
   if(emsa_name.starts_with("PSS(")) {
22✔
599
      auto parameters = PSS_Params::from_emsa_name(m_emsa->name()).serialize();
22✔
600
      return AlgorithmIdentifier("RSA/PSS", parameters);
21✔
601
   }
21✔
602

603
   throw Invalid_Argument(fmt("Signatures using RSA/{} are not supported", emsa_name));
2✔
604
}
79✔
605

606
class RSA_Decryption_Operation final : public PK_Ops::Decryption_with_EME,
607
                                       private RSA_Private_Operation {
608
   public:
609
      RSA_Decryption_Operation(const RSA_PrivateKey& rsa, std::string_view eme, RandomNumberGenerator& rng) :
280✔
610
            PK_Ops::Decryption_with_EME(eme), RSA_Private_Operation(rsa, rng) {}
280✔
611

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

614
      secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input) override {
5,165✔
615
         secure_vector<uint8_t> out(public_modulus_bytes());
5,165✔
616
         raw_op(out, input);
5,165✔
617
         return out;
5,144✔
618
      }
21✔
619
};
620

621
class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KDF,
622
                                           private RSA_Private_Operation {
623
   public:
624
      RSA_KEM_Decryption_Operation(const RSA_PrivateKey& key, std::string_view kdf, RandomNumberGenerator& rng) :
11✔
625
            PK_Ops::KEM_Decryption_with_KDF(kdf), RSA_Private_Operation(key, rng) {}
11✔
626

627
      size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
11✔
628

629
      size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
10✔
630

631
      void raw_kem_decrypt(std::span<uint8_t> out_shared_key, std::span<const uint8_t> encapsulated_key) override {
11✔
632
         raw_op(out_shared_key, encapsulated_key);
11✔
633
      }
11✔
634
};
635

636
/**
637
* RSA public (encrypt/verify) operation
638
*/
639
class RSA_Public_Operation {
×
640
   public:
641
      explicit RSA_Public_Operation(const RSA_PublicKey& rsa) : m_public(rsa.public_data()) {}
14,847✔
642

643
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
26,767✔
644

645
   protected:
646
      BigInt public_op(const BigInt& m) const {
27,162✔
647
         if(m >= m_public->get_n()) {
27,162✔
648
            throw Decoding_Error("RSA public op - input is too large");
56✔
649
         }
650

651
         return m_public->public_op(m);
27,106✔
652
      }
653

654
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
27,461✔
655

656
      const BigInt& get_n() const { return m_public->get_n(); }
11✔
657

658
   private:
659
      std::shared_ptr<const RSA_Public_Data> m_public;
660
};
661

662
class RSA_Encryption_Operation final : public PK_Ops::Encryption_with_EME,
×
663
                                       private RSA_Public_Operation {
664
   public:
665
      RSA_Encryption_Operation(const RSA_PublicKey& rsa, std::string_view eme) :
260✔
666
            PK_Ops::Encryption_with_EME(eme), RSA_Public_Operation(rsa) {}
260✔
667

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

670
      size_t max_ptext_input_bits() const override { return public_modulus_bits() - 1; }
516✔
671

672
      std::vector<uint8_t> raw_encrypt(std::span<const uint8_t> input, RandomNumberGenerator& /*rng*/) override {
328✔
673
         BigInt input_bn(input);
328✔
674
         return public_op(input_bn).serialize(public_modulus_bytes());
656✔
675
      }
328✔
676
};
677

678
class RSA_Verify_Operation final : public PK_Ops::Verification,
×
679
                                   private RSA_Public_Operation {
680
   public:
681
      void update(std::span<const uint8_t> msg) override { m_emsa->update(msg.data(), msg.size()); }
26,890✔
682

683
      bool is_valid_signature(std::span<const uint8_t> sig) override {
26,888✔
684
         const auto msg = m_emsa->raw_data();
26,888✔
685
         const auto message_repr = recover_message_repr(sig.data(), sig.size());
26,888✔
686
         return m_emsa->verify(message_repr, msg, public_modulus_bits() - 1);
26,767✔
687
      }
53,489✔
688

689
      RSA_Verify_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
14,847✔
690
            RSA_Public_Operation(rsa), m_emsa(EMSA::create_or_throw(padding)) {}
14,847✔
691

692
      std::string hash_function() const override { return m_emsa->hash_function(); }
12,677✔
693

694
   private:
695
      std::vector<uint8_t> recover_message_repr(const uint8_t input[], size_t input_len) {
26,888✔
696
         if(input_len > public_modulus_bytes()) {
26,888✔
697
            throw Decoding_Error("RSA signature too large to be valid for this key");
65✔
698
         }
699
         BigInt input_bn(input, input_len);
26,823✔
700
         return public_op(input_bn).serialize();
80,357✔
701
      }
26,767✔
702

703
      std::unique_ptr<EMSA> m_emsa;
704
};
705

706
class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KDF,
×
707
                                           private RSA_Public_Operation {
708
   public:
709
      RSA_KEM_Encryption_Operation(const RSA_PublicKey& key, std::string_view kdf) :
11✔
710
            PK_Ops::KEM_Encryption_with_KDF(kdf), RSA_Public_Operation(key) {}
11✔
711

712
   private:
713
      size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
11✔
714

715
      size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
44✔
716

717
      void raw_kem_encrypt(std::span<uint8_t> out_encapsulated_key,
11✔
718
                           std::span<uint8_t> raw_shared_key,
719
                           RandomNumberGenerator& rng) override {
720
         const BigInt r = BigInt::random_integer(rng, 1, get_n());
11✔
721
         const BigInt c = public_op(r);
11✔
722

723
         c.serialize_to(out_encapsulated_key);
11✔
724
         r.serialize_to(raw_shared_key);
11✔
725
      }
22✔
726
};
727

728
}  // namespace
729

730
std::unique_ptr<PK_Ops::Encryption> RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
824✔
731
                                                                        std::string_view params,
732
                                                                        std::string_view provider) const {
733
   if(provider == "base" || provider.empty()) {
1,013✔
734
      return std::make_unique<RSA_Encryption_Operation>(*this, params);
260✔
735
   }
736
   throw Provider_Not_Found(algo_name(), provider);
1,128✔
737
}
738

739
std::unique_ptr<PK_Ops::KEM_Encryption> RSA_PublicKey::create_kem_encryption_op(std::string_view params,
11✔
740
                                                                                std::string_view provider) const {
741
   if(provider == "base" || provider.empty()) {
11✔
742
      return std::make_unique<RSA_KEM_Encryption_Operation>(*this, params);
11✔
743
   }
744
   throw Provider_Not_Found(algo_name(), provider);
×
745
}
746

747
std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_verification_op(std::string_view params,
4,644✔
748
                                                                            std::string_view provider) const {
749
   if(provider == "base" || provider.empty()) {
5,546✔
750
      return std::make_unique<RSA_Verify_Operation>(*this, params);
1,944✔
751
   }
752

753
   throw Provider_Not_Found(algo_name(), provider);
5,400✔
754
}
755

756
namespace {
757

758
std::string parse_rsa_signature_algorithm(const AlgorithmIdentifier& alg_id) {
12,906✔
759
   const auto sig_info = split_on(alg_id.oid().to_formatted_string(), '/');
12,906✔
760

761
   if(sig_info.empty() || sig_info.size() != 2 || sig_info[0] != "RSA") {
12,906✔
762
      throw Decoding_Error("Unknown AlgorithmIdentifier for RSA X.509 signatures");
1✔
763
   }
764

765
   std::string padding = sig_info[1];
12,905✔
766

767
   if(padding == "PSS") {
12,905✔
768
      // "MUST contain RSASSA-PSS-params"
769
      if(alg_id.parameters().empty()) {
534✔
770
         throw Decoding_Error("PSS params must be provided");
×
771
      }
772

773
      PSS_Params pss_params(alg_id.parameters());
536✔
774

775
      // hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
776
      const std::string hash_algo = pss_params.hash_function();
534✔
777
      if(hash_algo != "SHA-1" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384" &&
534✔
778
         hash_algo != "SHA-512") {
10✔
779
         throw Decoding_Error("Unacceptable hash for PSS signatures");
×
780
      }
781

782
      if(pss_params.mgf_function() != "MGF1") {
534✔
783
         throw Decoding_Error("Unacceptable MGF for PSS signatures");
×
784
      }
785

786
      // For MGF1, it is strongly RECOMMENDED that the underlying hash
787
      // function be the same as the one identified by hashAlgorithm
788
      //
789
      // Must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
790
      if(pss_params.hash_algid() != pss_params.mgf_hash_algid()) {
534✔
791
         throw Decoding_Error("Unacceptable MGF hash for PSS signatures");
2✔
792
      }
793

794
      if(pss_params.trailer_field() != 1) {
532✔
795
         throw Decoding_Error("Unacceptable trailer field for PSS signatures");
×
796
      }
797

798
      padding += fmt("({},MGF1,{})", hash_algo, pss_params.salt_length());
1,066✔
799
   }
534✔
800

801
   return padding;
12,903✔
802
}
12,906✔
803

804
}  // namespace
805

806
std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_x509_verification_op(const AlgorithmIdentifier& alg_id,
12,906✔
807
                                                                                 std::string_view provider) const {
808
   if(provider == "base" || provider.empty()) {
12,906✔
809
      return std::make_unique<RSA_Verify_Operation>(*this, parse_rsa_signature_algorithm(alg_id));
12,906✔
810
   }
811

812
   throw Provider_Not_Found(algo_name(), provider);
×
813
}
814

815
std::unique_ptr<PK_Ops::Decryption> RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
919✔
816
                                                                         std::string_view params,
817
                                                                         std::string_view provider) const {
818
   if(provider == "base" || provider.empty()) {
1,133✔
819
      return std::make_unique<RSA_Decryption_Operation>(*this, params, rng);
280✔
820
   }
821

822
   throw Provider_Not_Found(algo_name(), provider);
1,278✔
823
}
824

825
std::unique_ptr<PK_Ops::KEM_Decryption> RSA_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
11✔
826
                                                                                 std::string_view params,
827
                                                                                 std::string_view provider) const {
828
   if(provider == "base" || provider.empty()) {
11✔
829
      return std::make_unique<RSA_KEM_Decryption_Operation>(*this, params, rng);
11✔
830
   }
831

832
   throw Provider_Not_Found(algo_name(), provider);
×
833
}
834

835
std::unique_ptr<PK_Ops::Signature> RSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
2,222✔
836
                                                                       std::string_view params,
837
                                                                       std::string_view provider) const {
838
   if(provider == "base" || provider.empty()) {
2,556✔
839
      return std::make_unique<RSA_Signature_Operation>(*this, params, rng);
1,226✔
840
   }
841

842
   throw Provider_Not_Found(algo_name(), provider);
1,992✔
843
}
844

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