Coverage Report

Created: 2021-05-04 09:02

/src/botan/src/lib/pubkey/rsa/rsa.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* RSA
3
* (C) 1999-2010,2015,2016,2018,2019 Jack Lloyd
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7
8
#include <botan/rsa.h>
9
#include <botan/internal/pk_ops_impl.h>
10
#include <botan/internal/keypair.h>
11
#include <botan/internal/blinding.h>
12
#include <botan/reducer.h>
13
#include <botan/internal/workfactor.h>
14
#include <botan/der_enc.h>
15
#include <botan/ber_dec.h>
16
#include <botan/internal/monty.h>
17
#include <botan/internal/divide.h>
18
#include <botan/internal/monty_exp.h>
19
20
#if defined(BOTAN_HAS_OPENSSL)
21
  #include <botan/internal/openssl.h>
22
#endif
23
24
#if defined(BOTAN_HAS_THREAD_UTILS)
25
  #include <botan/internal/thread_pool.h>
26
#endif
27
28
namespace Botan {
29
30
class RSA_Public_Data final
31
   {
32
   public:
33
      RSA_Public_Data(BigInt&& n, BigInt&& e) :
34
         m_n(n),
35
         m_e(e),
36
         m_monty_n(std::make_shared<Montgomery_Params>(m_n)),
37
         m_public_modulus_bits(m_n.bits()),
38
         m_public_modulus_bytes(m_n.bytes())
39
6.72k
         {}
40
41
      BigInt public_op(const BigInt& m) const
42
6.34k
         {
43
6.34k
         const size_t powm_window = 1;
44
6.34k
         auto powm_m_n = monty_precompute(m_monty_n, m, powm_window, false);
45
6.34k
         return monty_execute_vartime(*powm_m_n, m_e);
46
6.34k
         }
47
48
6.63k
      const BigInt& get_n() const { return m_n; }
49
0
      const BigInt& get_e() const { return m_e; }
50
6.34k
      size_t public_modulus_bits() const { return m_public_modulus_bits; }
51
0
      size_t public_modulus_bytes() const { return m_public_modulus_bytes; }
52
53
   private:
54
      BigInt m_n;
55
      BigInt m_e;
56
      std::shared_ptr<const Montgomery_Params> m_monty_n;
57
      size_t m_public_modulus_bits;
58
      size_t m_public_modulus_bytes;
59
   };
60
61
class RSA_Private_Data final
62
   {
63
   public:
64
      RSA_Private_Data(BigInt&& d, BigInt&& p, BigInt&& q,
65
                       BigInt&& d1, BigInt&& d2, BigInt&& c) :
66
         m_d(d),
67
         m_p(p),
68
         m_q(q),
69
         m_d1(d1),
70
         m_d2(d2),
71
         m_c(c),
72
         m_mod_p(m_p),
73
         m_mod_q(m_q),
74
         m_monty_p(std::make_shared<Montgomery_Params>(m_p, m_mod_p)),
75
         m_monty_q(std::make_shared<Montgomery_Params>(m_q, m_mod_q)),
76
         m_p_bits(m_p.bits()),
77
         m_q_bits(m_q.bits())
78
55
         {}
79
80
0
      const BigInt& get_d() const { return m_d; }
81
0
      const BigInt& get_p() const { return m_p; }
82
0
      const BigInt& get_q() const { return m_q; }
83
0
      const BigInt& get_d1() const { return m_d1; }
84
0
      const BigInt& get_d2() const { return m_d2; }
85
0
      const BigInt& get_c() const { return m_c; }
86
87
   //private:
88
      BigInt m_d;
89
      BigInt m_p;
90
      BigInt m_q;
91
      BigInt m_d1;
92
      BigInt m_d2;
93
      BigInt m_c;
94
95
      Modular_Reducer m_mod_p;
96
      Modular_Reducer m_mod_q;
97
      std::shared_ptr<const Montgomery_Params> m_monty_p;
98
      std::shared_ptr<const Montgomery_Params> m_monty_q;
99
      size_t m_p_bits;
100
      size_t m_q_bits;
101
   };
102
103
std::shared_ptr<const RSA_Public_Data> RSA_PublicKey::public_data() const
104
6.63k
   {
105
6.63k
   return m_public;
106
6.63k
   }
107
108
0
const BigInt& RSA_PublicKey::get_n() const { return m_public->get_n(); }
109
0
const BigInt& RSA_PublicKey::get_e() const { return m_public->get_e(); }
110
111
void RSA_PublicKey::init(BigInt&& n, BigInt&& e)
112
6.78k
   {
113
6.78k
   if(n.is_negative() || n.is_even() || e.is_negative() || e.is_even())
114
61
      throw Decoding_Error("Invalid RSA public key parameters");
115
6.72k
   m_public = std::make_shared<RSA_Public_Data>(std::move(n), std::move(e));
116
6.72k
   }
117
118
RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier&,
119
                             const std::vector<uint8_t>& key_bits)
120
6.85k
   {
121
6.85k
   BigInt n, e;
122
6.85k
   BER_Decoder(key_bits)
123
6.85k
      .start_sequence()
124
6.85k
      .decode(n)
125
6.85k
      .decode(e)
126
6.85k
      .end_cons();
127
128
6.85k
   init(std::move(n), std::move(e));
129
6.85k
   }
Unexecuted instantiation: Botan::RSA_PublicKey::RSA_PublicKey(Botan::AlgorithmIdentifier const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&)
Botan::RSA_PublicKey::RSA_PublicKey(Botan::AlgorithmIdentifier const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&)
Line
Count
Source
120
6.85k
   {
121
6.85k
   BigInt n, e;
122
6.85k
   BER_Decoder(key_bits)
123
6.85k
      .start_sequence()
124
6.85k
      .decode(n)
125
6.85k
      .decode(e)
126
6.85k
      .end_cons();
127
128
6.85k
   init(std::move(n), std::move(e));
129
6.85k
   }
130
131
RSA_PublicKey::RSA_PublicKey(const BigInt& modulus, const BigInt& exponent)
132
0
   {
133
0
   BigInt n = modulus;
134
0
   BigInt e = exponent;
135
0
   init(std::move(n), std::move(e));
136
0
   }
Unexecuted instantiation: Botan::RSA_PublicKey::RSA_PublicKey(Botan::BigInt const&, Botan::BigInt const&)
Unexecuted instantiation: Botan::RSA_PublicKey::RSA_PublicKey(Botan::BigInt const&, Botan::BigInt const&)
137
138
size_t RSA_PublicKey::key_length() const
139
0
   {
140
0
   return m_public->public_modulus_bits();
141
0
   }
142
143
size_t RSA_PublicKey::estimated_strength() const
144
0
   {
145
0
   return if_work_factor(key_length());
146
0
   }
147
148
AlgorithmIdentifier RSA_PublicKey::algorithm_identifier() const
149
0
   {
150
0
   return AlgorithmIdentifier(get_oid(), AlgorithmIdentifier::USE_NULL_PARAM);
151
0
   }
152
153
std::vector<uint8_t> RSA_PublicKey::public_key_bits() const
154
0
   {
155
0
   std::vector<uint8_t> output;
156
0
   DER_Encoder der(output);
157
0
   der.start_sequence()
158
0
         .encode(get_n())
159
0
         .encode(get_e())
160
0
      .end_cons();
161
162
0
   return output;
163
0
   }
164
165
/*
166
* Check RSA Public Parameters
167
*/
168
bool RSA_PublicKey::check_key(RandomNumberGenerator&, bool) const
169
0
   {
170
0
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even())
171
0
      return false;
172
0
   return true;
173
0
   }
174
175
std::shared_ptr<const RSA_Private_Data> RSA_PrivateKey::private_data() const
176
0
   {
177
0
   return m_private;
178
0
   }
179
180
secure_vector<uint8_t> RSA_PrivateKey::private_key_bits() const
181
0
   {
182
0
   return DER_Encoder()
183
0
      .start_sequence()
184
0
         .encode(static_cast<size_t>(0))
185
0
         .encode(get_n())
186
0
         .encode(get_e())
187
0
         .encode(get_d())
188
0
         .encode(get_p())
189
0
         .encode(get_q())
190
0
         .encode(get_d1())
191
0
         .encode(get_d2())
192
0
         .encode(get_c())
193
0
      .end_cons()
194
0
   .get_contents();
195
0
   }
196
197
0
const BigInt& RSA_PrivateKey::get_p() const { return m_private->get_p(); }
198
0
const BigInt& RSA_PrivateKey::get_q() const { return m_private->get_q(); }
199
0
const BigInt& RSA_PrivateKey::get_d() const { return m_private->get_d(); }
200
0
const BigInt& RSA_PrivateKey::get_c() const { return m_private->get_c(); }
201
0
const BigInt& RSA_PrivateKey::get_d1() const { return m_private->get_d1(); }
202
0
const BigInt& RSA_PrivateKey::get_d2() const { return m_private->get_d2(); }
203
204
void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q,
205
                          BigInt&& d1, BigInt&& d2, BigInt&& c)
206
55
   {
207
55
   m_private = std::make_shared<RSA_Private_Data>(
208
55
      std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
209
55
   }
210
211
RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier&,
212
                               const secure_vector<uint8_t>& key_bits)
213
71
   {
214
71
   BigInt n, e, d, p, q, d1, d2, c;
215
216
71
   BER_Decoder(key_bits)
217
71
      .start_sequence()
218
71
         .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
219
71
         .decode(n)
220
71
         .decode(e)
221
71
         .decode(d)
222
71
         .decode(p)
223
71
         .decode(q)
224
71
         .decode(d1)
225
71
         .decode(d2)
226
71
         .decode(c)
227
71
      .end_cons();
228
229
71
   RSA_PublicKey::init(std::move(n), std::move(e));
230
231
71
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q),
232
71
                        std::move(d1), std::move(d2), std::move(c));
233
71
   }
Unexecuted instantiation: Botan::RSA_PrivateKey::RSA_PrivateKey(Botan::AlgorithmIdentifier const&, std::__1::vector<unsigned char, Botan::secure_allocator<unsigned char> > const&)
Botan::RSA_PrivateKey::RSA_PrivateKey(Botan::AlgorithmIdentifier const&, std::__1::vector<unsigned char, Botan::secure_allocator<unsigned char> > const&)
Line
Count
Source
213
71
   {
214
71
   BigInt n, e, d, p, q, d1, d2, c;
215
216
71
   BER_Decoder(key_bits)
217
71
      .start_sequence()
218
71
         .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
219
71
         .decode(n)
220
71
         .decode(e)
221
71
         .decode(d)
222
71
         .decode(p)
223
71
         .decode(q)
224
71
         .decode(d1)
225
71
         .decode(d2)
226
71
         .decode(c)
227
71
      .end_cons();
228
229
71
   RSA_PublicKey::init(std::move(n), std::move(e));
230
231
71
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q),
232
71
                        std::move(d1), std::move(d2), std::move(c));
233
71
   }
234
235
RSA_PrivateKey::RSA_PrivateKey(const BigInt& prime1,
236
                               const BigInt& prime2,
237
                               const BigInt& exp,
238
                               const BigInt& d_exp,
239
                               const BigInt& mod)
240
0
   {
241
0
   BigInt p = prime1;
242
0
   BigInt q = prime2;
243
0
   BigInt n = mod;
244
0
   if(n.is_zero())
245
0
      n = p * q;
246
247
0
   BigInt e = exp;
248
249
0
   BigInt d = d_exp;
250
251
0
   const BigInt p_minus_1 = p - 1;
252
0
   const BigInt q_minus_1 = q - 1;
253
254
0
   if(d.is_zero())
255
0
      {
256
0
      const BigInt phi_n = lcm(p_minus_1, q_minus_1);
257
0
      d = inverse_mod(e, phi_n);
258
0
      }
259
260
0
   BigInt d1 = ct_modulo(d, p_minus_1);
261
0
   BigInt d2 = ct_modulo(d, q_minus_1);
262
0
   BigInt c = inverse_mod(q, p);
263
264
0
   RSA_PublicKey::init(std::move(n), std::move(e));
265
266
0
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q),
267
0
                        std::move(d1), std::move(d2), std::move(c));
268
0
   }
Unexecuted instantiation: Botan::RSA_PrivateKey::RSA_PrivateKey(Botan::BigInt const&, Botan::BigInt const&, Botan::BigInt const&, Botan::BigInt const&, Botan::BigInt const&)
Unexecuted instantiation: Botan::RSA_PrivateKey::RSA_PrivateKey(Botan::BigInt const&, Botan::BigInt const&, Botan::BigInt const&, Botan::BigInt const&, Botan::BigInt const&)
269
270
/*
271
* Create a RSA private key
272
*/
273
RSA_PrivateKey::RSA_PrivateKey(RandomNumberGenerator& rng,
274
                               size_t bits, size_t exp)
275
0
   {
276
0
   if(bits < 1024)
277
0
      throw Invalid_Argument(algo_name() + ": Can't make a key that is only " +
278
0
                             std::to_string(bits) + " bits long");
279
0
   if(exp < 3 || exp % 2 == 0)
280
0
      throw Invalid_Argument(algo_name() + ": Invalid encryption exponent");
281
282
0
   BigInt n, e, d, p, q, d1, d2, c;
283
284
0
   e = exp;
285
286
0
   const size_t p_bits = (bits + 1) / 2;
287
0
   const size_t q_bits = bits - p_bits;
288
289
0
   for(size_t attempt = 0; ; ++attempt)
290
0
      {
291
0
      if(attempt > 10)
292
0
         throw Internal_Error("RNG failure during RSA key generation");
293
294
      // TODO could generate primes in thread pool
295
0
      p = generate_rsa_prime(rng, rng, p_bits, e);
296
0
      q = generate_rsa_prime(rng, rng, q_bits, e);
297
298
0
      const BigInt diff = p - q;
299
0
      if(diff.bits() < (bits/2) - 100)
300
0
         continue;
301
302
0
      n = p * q;
303
304
0
      if(n.bits() != bits)
305
0
         continue;
306
307
0
      break;
308
0
      }
309
310
0
   const BigInt p_minus_1 = p - 1;
311
0
   const BigInt q_minus_1 = q - 1;
312
313
0
   const BigInt phi_n = lcm(p_minus_1, q_minus_1);
314
   // This is guaranteed because p,q == 3 mod 4
315
0
   BOTAN_DEBUG_ASSERT(low_zero_bits(phi_n) == 1);
316
0
   d = inverse_mod(e, phi_n);
317
0
   d1 = ct_modulo(d, p_minus_1);
318
0
   d2 = ct_modulo(d, q_minus_1);
319
0
   c = inverse_mod(q, p);
320
321
0
   RSA_PublicKey::init(std::move(n), std::move(e));
322
323
0
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q),
324
0
                        std::move(d1), std::move(d2), std::move(c));
325
0
   }
Unexecuted instantiation: Botan::RSA_PrivateKey::RSA_PrivateKey(Botan::RandomNumberGenerator&, unsigned long, unsigned long)
Unexecuted instantiation: Botan::RSA_PrivateKey::RSA_PrivateKey(Botan::RandomNumberGenerator&, unsigned long, unsigned long)
326
327
std::unique_ptr<Public_Key> RSA_PrivateKey::public_key() const
328
0
   {
329
0
   return std::make_unique<RSA_PublicKey>(get_n(), get_e());
330
0
   }
331
332
/*
333
* Check Private RSA Parameters
334
*/
335
bool RSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const
336
0
   {
337
0
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even())
338
0
      return false;
339
340
0
   if(get_d() < 2 || get_p() < 3 || get_q() < 3)
341
0
      return false;
342
343
0
   if(get_p() * get_q() != get_n())
344
0
      return false;
345
346
0
   if(get_p() == get_q())
347
0
      return false;
348
349
0
   if(get_d1() != ct_modulo(get_d(), get_p() - 1))
350
0
      return false;
351
0
   if(get_d2() != ct_modulo(get_d(), get_q() - 1))
352
0
      return false;
353
0
   if(get_c() != inverse_mod(get_q(), get_p()))
354
0
      return false;
355
356
0
   const size_t prob = (strong) ? 128 : 12;
357
358
0
   if(!is_prime(get_p(), rng, prob))
359
0
      return false;
360
0
   if(!is_prime(get_q(), rng, prob))
361
0
      return false;
362
363
0
   if(strong)
364
0
      {
365
0
      if(ct_modulo(get_e() * get_d(), lcm(get_p() - 1, get_q() - 1)) != 1)
366
0
         return false;
367
368
0
      return KeyPair::signature_consistency_check(rng, *this, "EMSA4(SHA-256)");
369
0
      }
370
371
0
   return true;
372
0
   }
373
374
namespace {
375
376
/**
377
* RSA private (decrypt/sign) operation
378
*/
379
class RSA_Private_Operation
380
   {
381
   protected:
382
0
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
383
0
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
384
385
      explicit RSA_Private_Operation(const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
386
         m_public(rsa.public_data()),
387
         m_private(rsa.private_data()),
388
         m_blinder(m_public->get_n(), rng,
389
0
                   [this](const BigInt& k) { return m_public->public_op(k); },
390
0
                   [this](const BigInt& k) { return inverse_mod(k, m_public->get_n()); }),
391
         m_blinding_bits(64),
392
         m_max_d1_bits(m_private->m_p_bits + m_blinding_bits),
393
         m_max_d2_bits(m_private->m_q_bits + m_blinding_bits)
394
0
         {
395
0
         }
396
397
      secure_vector<uint8_t> raw_op(const uint8_t input[], size_t input_len)
398
0
         {
399
0
         const BigInt input_bn(input, input_len);
400
0
         if(input_bn >= m_public->get_n())
401
0
            throw Invalid_Argument("RSA private op - input is too large");
402
403
         // TODO: This should be a function on blinder
404
         // BigInt Blinder::run_blinded_function(std::function<BigInt, BigInt> fn, const BigInt& input);
405
406
0
         const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
407
0
         BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
408
0
         return BigInt::encode_1363(recovered, m_public->public_modulus_bytes());
409
0
         }
410
411
   private:
412
413
      BigInt rsa_private_op(const BigInt& m) const
414
0
         {
415
         /*
416
         TODO
417
         Consider using Montgomery reduction instead of Barrett, using
418
         the "Smooth RSA-CRT" method. https://eprint.iacr.org/2007/039.pdf
419
         */
420
421
0
         static constexpr size_t powm_window = 4;
422
423
         // Compute this in main thread to avoid racing on the rng
424
0
         const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
425
426
0
#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
427
0
   #define BOTAN_RSA_USE_ASYNC
428
0
#endif
429
430
0
#if defined(BOTAN_RSA_USE_ASYNC)
431
         /*
432
         * Precompute m.sig_words in the main thread before calling async. Otherwise
433
         * the two threads race (during Modular_Reducer::reduce) and while the output
434
         * is correct in both threads, helgrind warns.
435
         */
436
0
         m.sig_words();
437
438
0
         auto future_j1 = Thread_Pool::global_instance().run([this, &m, &d1_mask]() {
439
0
#endif
440
0
            const BigInt masked_d1 = m_private->get_d1() + (d1_mask * (m_private->get_p() - 1));
441
0
            auto powm_d1_p = monty_precompute(m_private->m_monty_p, m_private->m_mod_p.reduce(m), powm_window);
442
0
            BigInt j1 = monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
443
444
0
#if defined(BOTAN_RSA_USE_ASYNC)
445
0
         return j1;
446
0
         });
447
0
#endif
448
449
0
         const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
450
0
         const BigInt masked_d2 = m_private->get_d2() + (d2_mask * (m_private->get_q() - 1));
451
0
         auto powm_d2_q = monty_precompute(m_private->m_monty_q, m_private->m_mod_q.reduce(m), powm_window);
452
0
         const BigInt j2 = monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits);
453
454
0
#if defined(BOTAN_RSA_USE_ASYNC)
455
0
         BigInt j1 = future_j1.get();
456
0
#endif
457
458
         /*
459
         * To recover the final value from the CRT representation (j1,j2)
460
         * we use Garner's algorithm:
461
         * c = q^-1 mod p (this is precomputed)
462
         * h = c*(j1-j2) mod p
463
         * m = j2 + h*q
464
         *
465
         * We must avoid leaking if j1 >= j2 or not, as doing so allows deriving
466
         * information about the secret prime. Do this by first adding p to j1,
467
         * which should ensure the subtraction of j2 does not underflow. But
468
         * this may still underflow if p and q are imbalanced in size.
469
         */
470
471
0
         j1 = m_private->m_mod_p.multiply(m_private->m_mod_p.reduce((m_private->get_p() + j1) - j2), m_private->get_c());
472
0
         return j1*m_private->get_q() + j2;
473
0
         }
474
475
      std::shared_ptr<const RSA_Public_Data> m_public;
476
      std::shared_ptr<const RSA_Private_Data> m_private;
477
478
      // XXX could the blinder starting pair be shared?
479
      Blinder m_blinder;
480
      const size_t m_blinding_bits;
481
      const size_t m_max_d1_bits;
482
      const size_t m_max_d2_bits;
483
   };
484
485
class RSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA,
486
                                      private RSA_Private_Operation
487
   {
488
   public:
489
0
      size_t max_input_bits() const override { return public_modulus_bits() - 1; }
490
491
0
      size_t signature_length() const override { return public_modulus_bytes(); }
492
493
      RSA_Signature_Operation(const RSA_PrivateKey& rsa, const std::string& emsa, RandomNumberGenerator& rng) :
494
         PK_Ops::Signature_with_EMSA(emsa),
495
         RSA_Private_Operation(rsa, rng)
496
0
         {
497
0
         }
498
499
      secure_vector<uint8_t> raw_sign(const uint8_t input[], size_t input_len,
500
                                      RandomNumberGenerator&) override
501
0
         {
502
0
         return raw_op(input, input_len);
503
0
         }
504
   };
505
506
class RSA_Decryption_Operation final : public PK_Ops::Decryption_with_EME,
507
                                       private RSA_Private_Operation
508
   {
509
   public:
510
511
      RSA_Decryption_Operation(const RSA_PrivateKey& rsa, const std::string& eme, RandomNumberGenerator& rng) :
512
         PK_Ops::Decryption_with_EME(eme),
513
         RSA_Private_Operation(rsa, rng)
514
0
         {
515
0
         }
516
517
0
      size_t plaintext_length(size_t) const override { return public_modulus_bytes(); }
518
519
      secure_vector<uint8_t> raw_decrypt(const uint8_t input[], size_t input_len) override
520
0
         {
521
0
         return raw_op(input, input_len);
522
0
         }
523
   };
524
525
class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KDF,
526
                                           private RSA_Private_Operation
527
   {
528
   public:
529
530
      RSA_KEM_Decryption_Operation(const RSA_PrivateKey& key,
531
                                   const std::string& kdf,
532
                                   RandomNumberGenerator& rng) :
533
         PK_Ops::KEM_Decryption_with_KDF(kdf),
534
         RSA_Private_Operation(key, rng)
535
0
         {}
536
537
      secure_vector<uint8_t>
538
      raw_kem_decrypt(const uint8_t encap_key[], size_t len) override
539
0
         {
540
0
         return raw_op(encap_key, len);
541
0
         }
542
   };
543
544
/**
545
* RSA public (encrypt/verify) operation
546
*/
547
class RSA_Public_Operation
548
   {
549
   public:
550
      explicit RSA_Public_Operation(const RSA_PublicKey& rsa) :
551
         m_public(rsa.public_data())
552
6.63k
         {}
553
554
         size_t get_max_input_bits() const
555
6.34k
         {
556
6.34k
         const size_t n_bits = m_public->public_modulus_bits();
557
558
         /*
559
         Make Coverity happy that n_bits - 1 won't underflow
560
561
         5 bit minimum: smallest possible RSA key is 3*5
562
         */
563
6.34k
         BOTAN_ASSERT_NOMSG(n_bits >= 5);
564
6.34k
         return n_bits - 1;
565
6.34k
         }
566
567
   protected:
568
      BigInt public_op(const BigInt& m) const
569
6.63k
         {
570
6.63k
         if(m >= m_public->get_n())
571
295
            throw Invalid_Argument("RSA public op - input is too large");
572
573
6.34k
         return m_public->public_op(m);
574
6.34k
         }
575
576
0
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
577
578
0
      const BigInt& get_n() const { return m_public->get_n(); }
579
580
      std::shared_ptr<const RSA_Public_Data> m_public;
581
   };
582
583
class RSA_Encryption_Operation final : public PK_Ops::Encryption_with_EME,
584
                                       private RSA_Public_Operation
585
   {
586
   public:
587
588
      RSA_Encryption_Operation(const RSA_PublicKey& rsa, const std::string& eme) :
589
         PK_Ops::Encryption_with_EME(eme),
590
         RSA_Public_Operation(rsa)
591
0
         {
592
0
         }
593
594
0
      size_t ciphertext_length(size_t) const override { return public_modulus_bytes(); }
595
596
0
      size_t max_raw_input_bits() const override { return get_max_input_bits(); }
597
598
      secure_vector<uint8_t> raw_encrypt(const uint8_t input[], size_t input_len,
599
                                         RandomNumberGenerator&) override
600
0
         {
601
0
         BigInt input_bn(input, input_len);
602
0
         return BigInt::encode_1363(public_op(input_bn), public_modulus_bytes());
603
0
         }
604
   };
605
606
class RSA_Verify_Operation final : public PK_Ops::Verification_with_EMSA,
607
                                   private RSA_Public_Operation
608
   {
609
   public:
610
611
6.34k
      size_t max_input_bits() const override { return get_max_input_bits(); }
612
613
      RSA_Verify_Operation(const RSA_PublicKey& rsa, const std::string& emsa) :
614
         PK_Ops::Verification_with_EMSA(emsa),
615
         RSA_Public_Operation(rsa)
616
6.63k
         {
617
6.63k
         }
618
619
6.63k
      bool with_recovery() const override { return true; }
620
621
      secure_vector<uint8_t> verify_mr(const uint8_t input[], size_t input_len) override
622
6.63k
         {
623
6.63k
         BigInt input_bn(input, input_len);
624
6.63k
         return BigInt::encode_locked(public_op(input_bn));
625
6.63k
         }
626
   };
627
628
class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KDF,
629
                                           private RSA_Public_Operation
630
   {
631
   public:
632
633
      RSA_KEM_Encryption_Operation(const RSA_PublicKey& key,
634
                                   const std::string& kdf) :
635
         PK_Ops::KEM_Encryption_with_KDF(kdf),
636
0
         RSA_Public_Operation(key) {}
637
638
   private:
639
      void raw_kem_encrypt(secure_vector<uint8_t>& out_encapsulated_key,
640
                           secure_vector<uint8_t>& raw_shared_key,
641
                           Botan::RandomNumberGenerator& rng) override
642
0
         {
643
0
         const BigInt r = BigInt::random_integer(rng, 1, get_n());
644
0
         const BigInt c = public_op(r);
645
646
0
         out_encapsulated_key = BigInt::encode_locked(c);
647
0
         raw_shared_key = BigInt::encode_locked(r);
648
0
         }
649
   };
650
651
}
652
653
std::unique_ptr<PK_Ops::Encryption>
654
RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
655
                                    const std::string& params,
656
                                    const std::string& provider) const
657
0
   {
658
#if defined(BOTAN_HAS_OPENSSL)
659
   if(provider == "openssl" || provider.empty())
660
      {
661
      try
662
         {
663
         return make_openssl_rsa_enc_op(*this, params);
664
         }
665
      catch(Exception& e)
666
         {
667
         /*
668
         * If OpenSSL for some reason could not handle this (eg due to OAEP params),
669
         * throw if openssl was specifically requested but otherwise just fall back
670
         * to the normal version.
671
         */
672
         if(provider == "openssl")
673
            throw Lookup_Error("OpenSSL RSA provider rejected key:" + std::string(e.what()));
674
         }
675
      }
676
#endif
677
678
0
   if(provider == "base" || provider.empty())
679
0
      return std::make_unique<RSA_Encryption_Operation>(*this, params);
680
0
   throw Provider_Not_Found(algo_name(), provider);
681
0
   }
682
683
std::unique_ptr<PK_Ops::KEM_Encryption>
684
RSA_PublicKey::create_kem_encryption_op(RandomNumberGenerator& /*rng*/,
685
                                        const std::string& params,
686
                                        const std::string& provider) const
687
0
   {
688
0
   if(provider == "base" || provider.empty())
689
0
      return std::make_unique<RSA_KEM_Encryption_Operation>(*this, params);
690
0
   throw Provider_Not_Found(algo_name(), provider);
691
0
   }
692
693
std::unique_ptr<PK_Ops::Verification>
694
RSA_PublicKey::create_verification_op(const std::string& params,
695
                                      const std::string& provider) const
696
6.63k
   {
697
#if defined(BOTAN_HAS_OPENSSL)
698
   if(provider == "openssl" || provider.empty())
699
      {
700
      std::unique_ptr<PK_Ops::Verification> res = make_openssl_rsa_ver_op(*this, params);
701
      if(res)
702
         return res;
703
      }
704
#endif
705
706
6.63k
   if(provider == "base" || provider.empty())
707
6.63k
      return std::make_unique<RSA_Verify_Operation>(*this, params);
708
709
0
   throw Provider_Not_Found(algo_name(), provider);
710
0
   }
711
712
std::unique_ptr<PK_Ops::Decryption>
713
RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
714
                                     const std::string& params,
715
                                     const std::string& provider) const
716
0
   {
717
#if defined(BOTAN_HAS_OPENSSL)
718
   if(provider == "openssl" || provider.empty())
719
      {
720
      try
721
         {
722
         return make_openssl_rsa_dec_op(*this, params);
723
         }
724
      catch(Exception& e)
725
         {
726
         if(provider == "openssl")
727
            throw Lookup_Error("OpenSSL RSA provider rejected key:" + std::string(e.what()));
728
         }
729
      }
730
#endif
731
732
0
   if(provider == "base" || provider.empty())
733
0
      return std::make_unique<RSA_Decryption_Operation>(*this, params, rng);
734
735
0
   throw Provider_Not_Found(algo_name(), provider);
736
0
   }
737
738
std::unique_ptr<PK_Ops::KEM_Decryption>
739
RSA_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
740
                                         const std::string& params,
741
                                         const std::string& provider) const
742
0
   {
743
0
   if(provider == "base" || provider.empty())
744
0
      return std::make_unique<RSA_KEM_Decryption_Operation>(*this, params, rng);
745
746
0
   throw Provider_Not_Found(algo_name(), provider);
747
0
   }
748
749
std::unique_ptr<PK_Ops::Signature>
750
RSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
751
                                    const std::string& params,
752
                                    const std::string& provider) const
753
0
   {
754
#if defined(BOTAN_HAS_OPENSSL)
755
   if(provider == "openssl" || provider.empty())
756
      {
757
      std::unique_ptr<PK_Ops::Signature> res = make_openssl_rsa_sig_op(*this, params);
758
      if(res)
759
         return res;
760
      }
761
#endif
762
763
0
   if(provider == "base" || provider.empty())
764
0
      return std::make_unique<RSA_Signature_Operation>(*this, params, rng);
765
766
0
   throw Provider_Not_Found(algo_name(), provider);
767
0
   }
768
769
}