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

randombit / botan / 11087146043

28 Sep 2024 09:28PM UTC coverage: 92.003% (+0.7%) from 91.274%
11087146043

push

github

web-flow
Create terraform.yml

82959 of 90170 relevant lines covered (92.0%)

9376319.11 hits per line

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

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

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

29
namespace Botan {
30

31
class RSA_Public_Data final {
32
   public:
33
      RSA_Public_Data(BigInt&& n, BigInt&& e) :
15,073✔
34
            m_n(n),
15,073✔
35
            m_e(e),
15,073✔
36
            m_monty_n(std::make_shared<Montgomery_Params>(m_n)),
15,073✔
37
            m_public_modulus_bits(m_n.bits()),
15,073✔
38
            m_public_modulus_bytes(m_n.bytes()) {}
15,073✔
39

40
      BigInt public_op(const BigInt& m) const {
27,646✔
41
         const size_t powm_window = 1;
27,646✔
42
         auto powm_m_n = monty_precompute(m_monty_n, m, powm_window, false);
27,646✔
43
         return monty_execute_vartime(*powm_m_n, m_e);
27,646✔
44
      }
27,646✔
45

46
      const BigInt& get_n() const { return m_n; }
29,034✔
47

48
      const BigInt& get_e() const { return m_e; }
5✔
49

50
      size_t public_modulus_bits() const { return m_public_modulus_bits; }
21,059✔
51

52
      size_t public_modulus_bytes() const { return m_public_modulus_bytes; }
36,378✔
53

54
   private:
55
      BigInt m_n;
56
      BigInt m_e;
57
      std::shared_ptr<const Montgomery_Params> m_monty_n;
58
      size_t m_public_modulus_bits;
59
      size_t m_public_modulus_bytes;
60
};
61

62
class RSA_Private_Data final {
63
   public:
64
      RSA_Private_Data(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) :
2,591✔
65
            m_d(d),
2,591✔
66
            m_p(p),
2,591✔
67
            m_q(q),
2,591✔
68
            m_d1(d1),
2,591✔
69
            m_d2(d2),
2,591✔
70
            m_c(c),
2,591✔
71
            m_mod_p(m_p),
2,591✔
72
            m_mod_q(m_q),
2,591✔
73
            m_monty_p(std::make_shared<Montgomery_Params>(m_p, m_mod_p)),
2,591✔
74
            m_monty_q(std::make_shared<Montgomery_Params>(m_q, m_mod_q)),
2,591✔
75
            m_p_bits(m_p.bits()),
2,591✔
76
            m_q_bits(m_q.bits()) {}
2,591✔
77

78
      const BigInt& get_d() const { return m_d; }
1✔
79

80
      const BigInt& get_p() const { return m_p; }
4,986✔
81

82
      const BigInt& get_q() const { return m_q; }
9,971✔
83

84
      const BigInt& get_d1() const { return m_d1; }
4,985✔
85

86
      const BigInt& get_d2() const { return m_d2; }
4,985✔
87

88
      const BigInt& get_c() const { return m_c; }
×
89

90
      const Modular_Reducer& mod_p() const { return m_mod_p; }
9,970✔
91

92
      const Modular_Reducer& mod_q() const { return m_mod_q; }
4,985✔
93

94
      const std::shared_ptr<const Montgomery_Params>& monty_p() const { return m_monty_p; }
4,985✔
95

96
      const std::shared_ptr<const Montgomery_Params>& monty_q() const { return m_monty_q; }
4,985✔
97

98
      size_t p_bits() const { return m_p_bits; }
1,335✔
99

100
      size_t q_bits() const { return m_q_bits; }
1,335✔
101

102
   private:
103
      BigInt m_d;
104
      BigInt m_p;
105
      BigInt m_q;
106
      BigInt m_d1;
107
      BigInt m_d2;
108
      BigInt m_c;
109

110
      Modular_Reducer m_mod_p;
111
      Modular_Reducer m_mod_q;
112
      std::shared_ptr<const Montgomery_Params> m_monty_p;
113
      std::shared_ptr<const Montgomery_Params> m_monty_q;
114
      size_t m_p_bits;
115
      size_t m_q_bits;
116
};
117

118
std::shared_ptr<const RSA_Public_Data> RSA_PublicKey::public_data() const {
13,442✔
119
   return m_public;
13,442✔
120
}
121

122
const BigInt& RSA_PublicKey::get_int_field(std::string_view field) const {
8✔
123
   if(field == "n") {
11✔
124
      return m_public->get_n();
3✔
125
   } else if(field == "e") {
5✔
126
      return m_public->get_e();
3✔
127
   } else {
128
      return Public_Key::get_int_field(field);
2✔
129
   }
130
}
131

132
std::unique_ptr<Private_Key> RSA_PublicKey::generate_another(RandomNumberGenerator& rng) const {
2✔
133
   return std::make_unique<RSA_PrivateKey>(rng, m_public->public_modulus_bits(), m_public->get_e().to_u32bit());
2✔
134
}
135

136
const BigInt& RSA_PublicKey::get_n() const {
537✔
137
   return m_public->get_n();
537✔
138
}
139

140
const BigInt& RSA_PublicKey::get_e() const {
508✔
141
   return m_public->get_e();
508✔
142
}
143

144
void RSA_PublicKey::init(BigInt&& n, BigInt&& e) {
15,895✔
145
   if(n.is_negative() || n.is_even() || n.bits() < 5 /* n >= 3*5 */ || e.is_negative() || e.is_even()) {
47,058✔
146
      throw Decoding_Error("Invalid RSA public key parameters");
822✔
147
   }
148
   m_public = std::make_shared<RSA_Public_Data>(std::move(n), std::move(e));
15,073✔
149
}
15,073✔
150

151
RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
12,812✔
152
   BigInt n, e;
12,812✔
153
   BER_Decoder(key_bits).start_sequence().decode(n).decode(e).end_cons();
13,683✔
154

155
   init(std::move(n), std::move(e));
12,778✔
156
}
25,624✔
157

158
bool RSA_PublicKey::supports_operation(PublicKeyOperation op) const {
1,106✔
159
   return op == PublicKeyOperation::Signature || op == PublicKeyOperation::Encryption ||
1,106✔
160
          op == PublicKeyOperation::KeyEncapsulation;
1,106✔
161
}
162

163
RSA_PublicKey::RSA_PublicKey(const BigInt& modulus, const BigInt& exponent) {
523✔
164
   BigInt n = modulus;
523✔
165
   BigInt e = exponent;
523✔
166
   init(std::move(n), std::move(e));
523✔
167
}
1,046✔
168

169
size_t RSA_PublicKey::key_length() const {
4,766✔
170
   return m_public->public_modulus_bits();
4,766✔
171
}
172

173
size_t RSA_PublicKey::estimated_strength() const {
3,451✔
174
   return if_work_factor(key_length());
3,451✔
175
}
176

177
AlgorithmIdentifier RSA_PublicKey::algorithm_identifier() const {
684✔
178
   return AlgorithmIdentifier(object_identifier(), AlgorithmIdentifier::USE_NULL_PARAM);
684✔
179
}
180

181
std::vector<uint8_t> RSA_PublicKey::public_key_bits() const {
346✔
182
   std::vector<uint8_t> output;
346✔
183
   DER_Encoder der(output);
346✔
184
   der.start_sequence().encode(get_n()).encode(get_e()).end_cons();
346✔
185

186
   return output;
346✔
187
}
346✔
188

189
/*
190
* Check RSA Public Parameters
191
*/
192
bool RSA_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*strong*/) const {
9✔
193
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
27✔
194
      return false;
×
195
   }
196
   return true;
197
}
198

199
std::shared_ptr<const RSA_Private_Data> RSA_PrivateKey::private_data() const {
1,335✔
200
   return m_private;
1,335✔
201
}
202

203
secure_vector<uint8_t> RSA_PrivateKey::private_key_bits() const {
99✔
204
   return DER_Encoder()
198✔
205
      .start_sequence()
99✔
206
      .encode(static_cast<size_t>(0))
99✔
207
      .encode(get_n())
99✔
208
      .encode(get_e())
99✔
209
      .encode(get_d())
99✔
210
      .encode(get_p())
99✔
211
      .encode(get_q())
99✔
212
      .encode(get_d1())
99✔
213
      .encode(get_d2())
99✔
214
      .encode(get_c())
99✔
215
      .end_cons()
99✔
216
      .get_contents();
198✔
217
}
218

219
const BigInt& RSA_PrivateKey::get_p() const {
175✔
220
   return m_private->get_p();
175✔
221
}
222

223
const BigInt& RSA_PrivateKey::get_q() const {
174✔
224
   return m_private->get_q();
174✔
225
}
226

227
const BigInt& RSA_PrivateKey::get_d() const {
142✔
228
   return m_private->get_d();
142✔
229
}
230

231
const BigInt& RSA_PrivateKey::get_c() const {
112✔
232
   return m_private->get_c();
112✔
233
}
234

235
const BigInt& RSA_PrivateKey::get_d1() const {
112✔
236
   return m_private->get_d1();
112✔
237
}
238

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

243
void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) {
2,591✔
244
   m_private = std::make_shared<RSA_Private_Data>(
7,773✔
245
      std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
2,591✔
246
}
2,591✔
247

248
RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
2,121✔
249
   BigInt n, e, d, p, q, d1, d2, c;
2,121✔
250

251
   BER_Decoder(key_bits)
2,144✔
252
      .start_sequence()
4,235✔
253
      .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
4,225✔
254
      .decode(n)
2,111✔
255
      .decode(e)
2,110✔
256
      .decode(d)
2,109✔
257
      .decode(p)
2,109✔
258
      .decode(q)
2,109✔
259
      .decode(d1)
2,108✔
260
      .decode(d2)
2,107✔
261
      .decode(c)
2,103✔
262
      .end_cons();
2,103✔
263

264
   RSA_PublicKey::init(std::move(n), std::move(e));
2,100✔
265

266
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
2,098✔
267
}
16,968✔
268

269
RSA_PrivateKey::RSA_PrivateKey(
428✔
270
   const BigInt& prime1, const BigInt& prime2, const BigInt& exp, const BigInt& d_exp, const BigInt& mod) {
428✔
271
   BigInt p = prime1;
428✔
272
   BigInt q = prime2;
428✔
273
   BigInt n = mod;
428✔
274
   if(n.is_zero()) {
856✔
275
      n = p * q;
427✔
276
   }
277

278
   BigInt e = exp;
428✔
279

280
   BigInt d = d_exp;
428✔
281

282
   const BigInt p_minus_1 = p - 1;
428✔
283
   const BigInt q_minus_1 = q - 1;
428✔
284

285
   if(d.is_zero()) {
856✔
286
      const BigInt phi_n = lcm(p_minus_1, q_minus_1);
427✔
287
      d = inverse_mod(e, phi_n);
427✔
288
   }
427✔
289

290
   BigInt d1 = ct_modulo(d, p_minus_1);
428✔
291
   BigInt d2 = ct_modulo(d, q_minus_1);
428✔
292
   BigInt c = inverse_mod(q, p);
428✔
293

294
   RSA_PublicKey::init(std::move(n), std::move(e));
428✔
295

296
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
428✔
297
}
4,280✔
298

299
/*
300
* Create a RSA private key
301
*/
302
RSA_PrivateKey::RSA_PrivateKey(RandomNumberGenerator& rng, size_t bits, size_t exp) {
66✔
303
   if(bits < 1024) {
66✔
304
      throw Invalid_Argument(fmt("Cannot create an RSA key only {} bits long", bits));
×
305
   }
306

307
   if(exp < 3 || exp % 2 == 0) {
66✔
308
      throw Invalid_Argument("Invalid RSA encryption exponent");
×
309
   }
310

311
   const size_t p_bits = (bits + 1) / 2;
66✔
312
   const size_t q_bits = bits - p_bits;
66✔
313

314
   BigInt p, q, n;
66✔
315
   BigInt e = BigInt::from_u64(exp);
66✔
316

317
   for(size_t attempt = 0;; ++attempt) {
11✔
318
      if(attempt > 10) {
77✔
319
         throw Internal_Error("RNG failure during RSA key generation");
1✔
320
      }
321

322
      // TODO could generate primes in thread pool
323
      p = generate_rsa_prime(rng, rng, p_bits, e);
76✔
324
      q = generate_rsa_prime(rng, rng, q_bits, e);
76✔
325

326
      const BigInt diff = p - q;
76✔
327
      if(diff.bits() < (bits / 2) - 100) {
76✔
328
         continue;
11✔
329
      }
330

331
      n = p * q;
65✔
332

333
      if(n.bits() != bits) {
65✔
334
         continue;
×
335
      }
336

337
      break;
65✔
338
   }
11✔
339

340
   const BigInt p_minus_1 = p - 1;
65✔
341
   const BigInt q_minus_1 = q - 1;
65✔
342

343
   const BigInt phi_n = lcm(p_minus_1, q_minus_1);
65✔
344
   // This is guaranteed because p,q == 3 mod 4
345
   BOTAN_DEBUG_ASSERT(low_zero_bits(phi_n) == 1);
65✔
346

347
   BigInt d = inverse_mod(e, phi_n);
65✔
348
   BigInt d1 = ct_modulo(d, p_minus_1);
65✔
349
   BigInt d2 = ct_modulo(d, q_minus_1);
65✔
350
   BigInt c = inverse_mod(q, p);
65✔
351

352
   RSA_PublicKey::init(std::move(n), std::move(e));
65✔
353

354
   RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
65✔
355
}
719✔
356

357
const BigInt& RSA_PrivateKey::get_int_field(std::string_view field) const {
6✔
358
   if(field == "p") {
10✔
359
      return m_private->get_p();
1✔
360
   } else if(field == "q") {
8✔
361
      return m_private->get_q();
1✔
362
   } else if(field == "d") {
6✔
363
      return m_private->get_d();
1✔
364
   } else if(field == "c") {
5✔
365
      return m_private->get_c();
×
366
   } else if(field == "d1") {
3✔
367
      return m_private->get_d1();
×
368
   } else if(field == "d2") {
3✔
369
      return m_private->get_d2();
×
370
   } else {
371
      return RSA_PublicKey::get_int_field(field);
3✔
372
   }
373
}
374

375
std::unique_ptr<Public_Key> RSA_PrivateKey::public_key() const {
7✔
376
   return std::make_unique<RSA_PublicKey>(get_n(), get_e());
7✔
377
}
378

379
/*
380
* Check Private RSA Parameters
381
*/
382
bool RSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const {
11✔
383
   if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
33✔
384
      return false;
×
385
   }
386

387
   if(get_d() < 2 || get_p() < 3 || get_q() < 3) {
11✔
388
      return false;
×
389
   }
390

391
   if(get_p() * get_q() != get_n()) {
22✔
392
      return false;
393
   }
394

395
   if(get_p() == get_q()) {
11✔
396
      return false;
397
   }
398

399
   if(get_d1() != ct_modulo(get_d(), get_p() - 1)) {
33✔
400
      return false;
401
   }
402
   if(get_d2() != ct_modulo(get_d(), get_q() - 1)) {
33✔
403
      return false;
404
   }
405
   if(get_c() != inverse_mod(get_q(), get_p())) {
22✔
406
      return false;
407
   }
408

409
   const size_t prob = (strong) ? 128 : 12;
11✔
410

411
   if(!is_prime(get_p(), rng, prob)) {
11✔
412
      return false;
413
   }
414
   if(!is_prime(get_q(), rng, prob)) {
10✔
415
      return false;
416
   }
417

418
   if(strong) {
10✔
419
      if(ct_modulo(get_e() * get_d(), lcm(get_p() - 1, get_q() - 1)) != 1) {
56✔
420
         return false;
421
      }
422

423
      return KeyPair::signature_consistency_check(rng, *this, "EMSA4(SHA-256)");
8✔
424
   }
425

426
   return true;
427
}
428

429
namespace {
430

431
/**
432
* RSA private (decrypt/sign) operation
433
*/
434
class RSA_Private_Operation {
435
   protected:
436
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
1,512✔
437

438
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
4,998✔
439

440
      explicit RSA_Private_Operation(const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
1,335✔
441
            m_public(rsa.public_data()),
1,335✔
442
            m_private(rsa.private_data()),
1,335✔
443
            m_blinder(
2,670✔
444
               m_public->get_n(),
1,335✔
445
               rng,
446
               [this](const BigInt& k) { return m_public->public_op(k); },
1,342✔
447
               [this](const BigInt& k) { return inverse_mod(k, m_public->get_n()); }),
1,342✔
448
            m_blinding_bits(64),
1,335✔
449
            m_max_d1_bits(m_private->p_bits() + m_blinding_bits),
1,335✔
450
            m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {}
1,335✔
451

452
      void raw_op(std::span<uint8_t> out, std::span<const uint8_t> input) {
4,998✔
453
         if(input.size() > public_modulus_bytes()) {
4,998✔
454
            throw Decoding_Error("RSA input is too long for this key");
×
455
         }
456
         const BigInt input_bn(input.data(), input.size());
4,998✔
457
         if(input_bn >= m_public->get_n()) {
4,998✔
458
            throw Decoding_Error("RSA input is too large for this key");
12✔
459
         }
460
         // TODO: This should be a function on blinder
461
         // BigInt Blinder::run_blinded_function(std::function<BigInt, BigInt> fn, const BigInt& input);
462

463
         const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
9,983✔
464
         BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
14,955✔
465
         BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(), "output size check");
4,985✔
466
         BigInt::encode_1363(out, recovered);
4,985✔
467
      }
9,970✔
468

469
      secure_vector<uint8_t> raw_op(const uint8_t input[], size_t input_len) {
4,987✔
470
         secure_vector<uint8_t> out(m_public->public_modulus_bytes());
4,987✔
471
         raw_op(out, {input, input_len});
4,987✔
472
         return out;
4,974✔
473
      }
13✔
474

475
   private:
476
      BigInt rsa_private_op(const BigInt& m) const {
4,985✔
477
         /*
478
         TODO
479
         Consider using Montgomery reduction instead of Barrett, using
480
         the "Smooth RSA-CRT" method. https://eprint.iacr.org/2007/039.pdf
481
         */
482

483
         static constexpr size_t powm_window = 4;
4,985✔
484

485
         // Compute this in main thread to avoid racing on the rng
486
         const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
4,985✔
487

488
#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
489
   #define BOTAN_RSA_USE_ASYNC
490
#endif
491

492
#if defined(BOTAN_RSA_USE_ASYNC)
493
         /*
494
         * Precompute m.sig_words in the main thread before calling async. Otherwise
495
         * the two threads race (during Modular_Reducer::reduce) and while the output
496
         * is correct in both threads, helgrind warns.
497
         */
498
         m.sig_words();
4,985✔
499

500
         auto future_j1 = Thread_Pool::global_instance().run([this, &m, &d1_mask]() {
4,985✔
501
#endif
502
            const BigInt masked_d1 = m_private->get_d1() + (d1_mask * (m_private->get_p() - 1));
9,970✔
503
            auto powm_d1_p = monty_precompute(m_private->monty_p(), m_private->mod_p().reduce(m), powm_window);
4,985✔
504
            BigInt j1 = monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
4,985✔
505

506
#if defined(BOTAN_RSA_USE_ASYNC)
507
            return j1;
4,985✔
508
         });
14,955✔
509
#endif
510

511
         const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
4,985✔
512
         const BigInt masked_d2 = m_private->get_d2() + (d2_mask * (m_private->get_q() - 1));
9,970✔
513
         auto powm_d2_q = monty_precompute(m_private->monty_q(), m_private->mod_q().reduce(m), powm_window);
4,985✔
514
         const BigInt j2 = monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits);
4,985✔
515

516
#if defined(BOTAN_RSA_USE_ASYNC)
517
         BigInt j1 = future_j1.get();
4,985✔
518
#endif
519

520
         /*
521
         * To recover the final value from the CRT representation (j1,j2)
522
         * we use Garner's algorithm:
523
         * c = q^-1 mod p (this is precomputed)
524
         * h = c*(j1-j2) mod p
525
         * m = j2 + h*q
526
         *
527
         * We must avoid leaking if j1 >= j2 or not, as doing so allows deriving
528
         * information about the secret prime. Do this by first adding p to j1,
529
         * which should ensure the subtraction of j2 does not underflow. But
530
         * this may still underflow if p and q are imbalanced in size.
531
         */
532

533
         j1 =
4,985✔
534
            m_private->mod_p().multiply(m_private->mod_p().reduce((m_private->get_p() + j1) - j2), m_private->get_c());
19,940✔
535
         return j1 * m_private->get_q() + j2;
9,970✔
536
      }
29,910✔
537

538
      std::shared_ptr<const RSA_Public_Data> m_public;
539
      std::shared_ptr<const RSA_Private_Data> m_private;
540

541
      // XXX could the blinder starting pair be shared?
542
      Blinder m_blinder;
543
      const size_t m_blinding_bits;
544
      const size_t m_max_d1_bits;
545
      const size_t m_max_d2_bits;
546
};
547

548
class RSA_Signature_Operation final : public PK_Ops::Signature,
×
549
                                      private RSA_Private_Operation {
550
   public:
551
      void update(const uint8_t msg[], size_t msg_len) override { m_emsa->update(msg, msg_len); }
1,513✔
552

553
      secure_vector<uint8_t> sign(RandomNumberGenerator& rng) override {
1,512✔
554
         const size_t max_input_bits = public_modulus_bits() - 1;
1,512✔
555
         const auto msg = m_emsa->raw_data();
1,512✔
556
         const auto padded = m_emsa->encoding_of(msg, max_input_bits, rng);
1,512✔
557
         return raw_op(padded.data(), padded.size());
1,511✔
558
      }
3,021✔
559

560
      size_t signature_length() const override { return public_modulus_bytes(); }
268✔
561

562
      AlgorithmIdentifier algorithm_identifier() const override;
563

564
      std::string hash_function() const override { return m_emsa->hash_function(); }
124✔
565

566
      RSA_Signature_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
1,111✔
567
            RSA_Private_Operation(rsa, rng), m_emsa(EMSA::create_or_throw(padding)) {}
1,111✔
568

569
   private:
570
      std::unique_ptr<EMSA> m_emsa;
571
};
572

573
AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier() const {
79✔
574
   const std::string emsa_name = m_emsa->name();
79✔
575

576
   try {
79✔
577
      const std::string full_name = "RSA/" + emsa_name;
79✔
578
      const OID oid = OID::from_string(full_name);
79✔
579
      return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM);
58✔
580
   } catch(Lookup_Error&) {}
137✔
581

582
   if(emsa_name.starts_with("EMSA4(")) {
21✔
583
      auto parameters = PSS_Params::from_emsa_name(m_emsa->name()).serialize();
42✔
584
      return AlgorithmIdentifier("RSA/EMSA4", parameters);
21✔
585
   }
21✔
586

587
   throw Not_Implemented("No algorithm identifier defined for RSA with " + emsa_name);
×
588
}
79✔
589

590
class RSA_Decryption_Operation final : public PK_Ops::Decryption_with_EME,
×
591
                                       private RSA_Private_Operation {
592
   public:
593
      RSA_Decryption_Operation(const RSA_PrivateKey& rsa, std::string_view eme, RandomNumberGenerator& rng) :
213✔
594
            PK_Ops::Decryption_with_EME(eme), RSA_Private_Operation(rsa, rng) {}
213✔
595

596
      size_t plaintext_length(size_t /*ctext_len*/) const override { return public_modulus_bytes(); }
125✔
597

598
      secure_vector<uint8_t> raw_decrypt(const uint8_t input[], size_t input_len) override {
3,476✔
599
         return raw_op(input, input_len);
3,476✔
600
      }
601
};
602

603
class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KDF,
×
604
                                           private RSA_Private_Operation {
605
   public:
606
      RSA_KEM_Decryption_Operation(const RSA_PrivateKey& key, std::string_view kdf, RandomNumberGenerator& rng) :
11✔
607
            PK_Ops::KEM_Decryption_with_KDF(kdf), RSA_Private_Operation(key, rng) {}
11✔
608

609
      size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
11✔
610

611
      size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
10✔
612

613
      void raw_kem_decrypt(std::span<uint8_t> out_shared_key, std::span<const uint8_t> encapsulated_key) override {
11✔
614
         raw_op(out_shared_key, encapsulated_key);
11✔
615
      }
11✔
616
};
617

618
/**
619
* RSA public (encrypt/verify) operation
620
*/
621
class RSA_Public_Operation {
×
622
   public:
623
      explicit RSA_Public_Operation(const RSA_PublicKey& rsa) : m_public(rsa.public_data()) {}
11,913✔
624

625
      size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
21,057✔
626

627
   protected:
628
      BigInt public_op(const BigInt& m) const {
21,345✔
629
         if(m >= m_public->get_n()) {
21,345✔
630
            throw Decoding_Error("RSA public op - input is too large");
26✔
631
         }
632

633
         return m_public->public_op(m);
21,319✔
634
      }
635

636
      size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
21,588✔
637

638
      const BigInt& get_n() const { return m_public->get_n(); }
11✔
639

640
   private:
641
      std::shared_ptr<const RSA_Public_Data> m_public;
642
};
643

644
class RSA_Encryption_Operation final : public PK_Ops::Encryption_with_EME,
×
645
                                       private RSA_Public_Operation {
646
   public:
647
      RSA_Encryption_Operation(const RSA_PublicKey& rsa, std::string_view eme) :
183✔
648
            PK_Ops::Encryption_with_EME(eme), RSA_Public_Operation(rsa) {}
183✔
649

650
      size_t ciphertext_length(size_t /*ptext_len*/) const override { return public_modulus_bytes(); }
125✔
651

652
      size_t max_ptext_input_bits() const override { return public_modulus_bits() - 1; }
374✔
653

654
      secure_vector<uint8_t> raw_encrypt(const uint8_t input[],
251✔
655
                                         size_t input_len,
656
                                         RandomNumberGenerator& /*rng*/) override {
657
         BigInt input_bn(input, input_len);
251✔
658
         return BigInt::encode_1363(public_op(input_bn), public_modulus_bytes());
502✔
659
      }
251✔
660
};
661

662
class RSA_Verify_Operation final : public PK_Ops::Verification,
×
663
                                   private RSA_Public_Operation {
664
   public:
665
      void update(const uint8_t msg[], size_t msg_len) override { m_emsa->update(msg, msg_len); }
21,159✔
666

667
      bool is_valid_signature(const uint8_t sig[], size_t sig_len) override {
21,157✔
668
         const auto msg = m_emsa->raw_data();
21,157✔
669
         const auto message_repr = recover_message_repr(sig, sig_len);
21,157✔
670
         return m_emsa->verify(message_repr, msg, public_modulus_bits() - 1);
21,057✔
671
      }
42,069✔
672

673
      RSA_Verify_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
11,913✔
674
            RSA_Public_Operation(rsa), m_emsa(EMSA::create_or_throw(padding)) {}
11,913✔
675

676
      std::string hash_function() const override { return m_emsa->hash_function(); }
9,921✔
677

678
   private:
679
      std::vector<uint8_t> recover_message_repr(const uint8_t input[], size_t input_len) {
21,157✔
680
         if(input_len > public_modulus_bytes()) {
21,157✔
681
            throw Decoding_Error("RSA signature too large to be valid for this key");
74✔
682
         }
683
         BigInt input_bn(input, input_len);
21,083✔
684
         return BigInt::encode(public_op(input_bn));
42,140✔
685
      }
21,057✔
686

687
      std::unique_ptr<EMSA> m_emsa;
688
};
689

690
class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KDF,
×
691
                                           private RSA_Public_Operation {
692
   public:
693
      RSA_KEM_Encryption_Operation(const RSA_PublicKey& key, std::string_view kdf) :
11✔
694
            PK_Ops::KEM_Encryption_with_KDF(kdf), RSA_Public_Operation(key) {}
11✔
695

696
   private:
697
      size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
11✔
698

699
      size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
44✔
700

701
      void raw_kem_encrypt(std::span<uint8_t> out_encapsulated_key,
11✔
702
                           std::span<uint8_t> raw_shared_key,
703
                           RandomNumberGenerator& rng) override {
704
         const BigInt r = BigInt::random_integer(rng, 1, get_n());
11✔
705
         const BigInt c = public_op(r);
11✔
706

707
         BigInt::encode_1363(out_encapsulated_key, c);
11✔
708
         BigInt::encode_1363(raw_shared_key, r);
11✔
709
      }
22✔
710
};
711

712
}  // namespace
713

714
std::unique_ptr<PK_Ops::Encryption> RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
552✔
715
                                                                        std::string_view params,
716
                                                                        std::string_view provider) const {
717
   if(provider == "base" || provider.empty()) {
676✔
718
      return std::make_unique<RSA_Encryption_Operation>(*this, params);
183✔
719
   }
720
   throw Provider_Not_Found(algo_name(), provider);
738✔
721
}
722

723
std::unique_ptr<PK_Ops::KEM_Encryption> RSA_PublicKey::create_kem_encryption_op(std::string_view params,
11✔
724
                                                                                std::string_view provider) const {
725
   if(provider == "base" || provider.empty()) {
11✔
726
      return std::make_unique<RSA_KEM_Encryption_Operation>(*this, params);
11✔
727
   }
728
   throw Provider_Not_Found(algo_name(), provider);
×
729
}
730

731
std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_verification_op(std::string_view params,
4,047✔
732
                                                                            std::string_view provider) const {
733
   if(provider == "base" || provider.empty()) {
4,819✔
734
      return std::make_unique<RSA_Verify_Operation>(*this, params);
1,737✔
735
   }
736

737
   throw Provider_Not_Found(algo_name(), provider);
4,620✔
738
}
739

740
namespace {
741

742
std::string parse_rsa_signature_algorithm(const AlgorithmIdentifier& alg_id) {
10,179✔
743
   const auto sig_info = split_on(alg_id.oid().to_formatted_string(), '/');
10,179✔
744

745
   if(sig_info.empty() || sig_info.size() != 2 || sig_info[0] != "RSA") {
10,179✔
746
      throw Decoding_Error("Unknown AlgorithmIdentifier for RSA X.509 signatures");
1✔
747
   }
748

749
   std::string padding = sig_info[1];
10,178✔
750

751
   if(padding == "EMSA4") {
10,178✔
752
      // "MUST contain RSASSA-PSS-params"
753
      if(alg_id.parameters().empty()) {
534✔
754
         throw Decoding_Error("PSS params must be provided");
×
755
      }
756

757
      PSS_Params pss_params(alg_id.parameters());
534✔
758

759
      // hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
760
      const std::string hash_algo = pss_params.hash_function();
534✔
761
      if(hash_algo != "SHA-1" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384" &&
534✔
762
         hash_algo != "SHA-512") {
10✔
763
         throw Decoding_Error("Unacceptable hash for PSS signatures");
×
764
      }
765

766
      if(pss_params.mgf_function() != "MGF1") {
534✔
767
         throw Decoding_Error("Unacceptable MGF for PSS signatures");
×
768
      }
769

770
      // For MGF1, it is strongly RECOMMENDED that the underlying hash
771
      // function be the same as the one identified by hashAlgorithm
772
      //
773
      // Must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
774
      if(pss_params.hash_algid() != pss_params.mgf_hash_algid()) {
534✔
775
         throw Decoding_Error("Unacceptable MGF hash for PSS signatures");
2✔
776
      }
777

778
      if(pss_params.trailer_field() != 1) {
532✔
779
         throw Decoding_Error("Unacceptable trailer field for PSS signatures");
×
780
      }
781

782
      padding += fmt("({},MGF1,{})", hash_algo, pss_params.salt_length());
1,588✔
783
   }
534✔
784

785
   return padding;
10,176✔
786
}
10,179✔
787

788
}  // namespace
789

790
std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_x509_verification_op(const AlgorithmIdentifier& alg_id,
10,179✔
791
                                                                                 std::string_view provider) const {
792
   if(provider == "base" || provider.empty()) {
10,179✔
793
      return std::make_unique<RSA_Verify_Operation>(*this, parse_rsa_signature_algorithm(alg_id));
10,711✔
794
   }
795

796
   throw Provider_Not_Found(algo_name(), provider);
×
797
}
798

799
std::unique_ptr<PK_Ops::Decryption> RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
657✔
800
                                                                         std::string_view params,
801
                                                                         std::string_view provider) const {
802
   if(provider == "base" || provider.empty()) {
806✔
803
      return std::make_unique<RSA_Decryption_Operation>(*this, params, rng);
213✔
804
   }
805

806
   throw Provider_Not_Found(algo_name(), provider);
888✔
807
}
808

809
std::unique_ptr<PK_Ops::KEM_Decryption> RSA_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
11✔
810
                                                                                 std::string_view params,
811
                                                                                 std::string_view provider) const {
812
   if(provider == "base" || provider.empty()) {
11✔
813
      return std::make_unique<RSA_KEM_Decryption_Operation>(*this, params, rng);
11✔
814
   }
815

816
   throw Provider_Not_Found(algo_name(), provider);
×
817
}
818

819
std::unique_ptr<PK_Ops::Signature> RSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
1,912✔
820
                                                                       std::string_view params,
821
                                                                       std::string_view provider) const {
822
   if(provider == "base" || provider.empty()) {
2,181✔
823
      return std::make_unique<RSA_Signature_Operation>(*this, params, rng);
1,111✔
824
   }
825

826
   throw Provider_Not_Found(algo_name(), provider);
1,602✔
827
}
828

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