Botan 3.13.0
Crypto and TLS for C&
rsa.cpp
Go to the documentation of this file.
1/*
2* RSA
3* (C) 1999-2010,2015,2016,2018,2019,2023 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/rsa.h>
9
10#include <botan/ber_dec.h>
11#include <botan/der_enc.h>
12#include <botan/numthry.h>
13#include <botan/pss_params.h>
14#include <botan/internal/barrett.h>
15#include <botan/internal/blinding.h>
16#include <botan/internal/divide.h>
17#include <botan/internal/fmt.h>
18#include <botan/internal/keypair.h>
19#include <botan/internal/mod_inv.h>
20#include <botan/internal/monty.h>
21#include <botan/internal/monty_exp.h>
22#include <botan/internal/mp_core.h>
23#include <botan/internal/parsing.h>
24#include <botan/internal/pk_ops_impl.h>
25#include <botan/internal/sig_padding.h>
26#include <botan/internal/target_info.h>
27#include <botan/internal/workfactor.h>
28
29#if defined(BOTAN_HAS_THREAD_UTILS)
30 #include <botan/internal/thread_pool.h>
31#endif
32
33namespace Botan {
34
35class RSA_Public_Data final {
36 public:
37 RSA_Public_Data(BigInt&& n, BigInt&& e) :
38 m_n(std::move(n)),
39 m_e(std::move(e)),
40 m_mod_n(Barrett_Reduction::for_public_modulus(m_n)),
41 m_monty_n(m_n, m_mod_n),
42 m_public_modulus_bits(m_n.bits()),
43 m_public_modulus_bytes(m_n.bytes()) {}
44
45 BigInt public_op(const BigInt& m) const {
46 const size_t powm_window = 1;
47 auto powm_m_n = monty_precompute(m_monty_n, m, powm_window, false);
48 return monty_execute_vartime(*powm_m_n, m_e).value();
49 }
50
51 const BigInt& get_n() const { return m_n; }
52
53 const BigInt& get_e() const { return m_e; }
54
55 size_t public_modulus_bits() const { return m_public_modulus_bits; }
56
57 size_t public_modulus_bytes() const { return m_public_modulus_bytes; }
58
59 const Montgomery_Params& monty_n() const { return m_monty_n; }
60
61 const Barrett_Reduction& reducer_mod_n() const { return m_mod_n; }
62
63 private:
64 BigInt m_n;
65 BigInt m_e;
66 Barrett_Reduction m_mod_n;
67 const Montgomery_Params m_monty_n;
68 size_t m_public_modulus_bits;
69 size_t m_public_modulus_bytes;
70};
71
72class RSA_Private_Data final {
73 public:
74 RSA_Private_Data(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) :
75 m_d(std::move(d)),
76 m_p(std::move(p)),
77 m_q(std::move(q)),
78 m_d1(std::move(d1)),
79 m_d2(std::move(d2)),
80 m_c(std::move(c)),
81 m_monty_p(m_p),
82 m_monty_q(m_q),
83 m_c_monty(m_monty_p, m_c),
84 m_p_bits(m_p.bits()),
85 m_q_bits(m_q.bits()) {}
86
87 const BigInt& get_d() const { return m_d; }
88
89 const BigInt& get_p() const { return m_p; }
90
91 const BigInt& get_q() const { return m_q; }
92
93 const BigInt& get_d1() const { return m_d1; }
94
95 const BigInt& get_d2() const { return m_d2; }
96
97 BigInt blinded_d1(const BigInt& m) const { return m_d1 + m * (m_p - 1); }
98
99 BigInt blinded_d2(const BigInt& m) const { return m_d2 + m * (m_q - 1); }
100
101 const BigInt& get_c() const { return m_c; }
102
103 const Montgomery_Int& get_c_monty() const { return m_c_monty; }
104
105 const Montgomery_Params& monty_p() const { return m_monty_p; }
106
107 const Montgomery_Params& monty_q() const { return m_monty_q; }
108
109 size_t p_bits() const { return m_p_bits; }
110
111 size_t q_bits() const { return m_q_bits; }
112
113 bool primes_imbalanced() const { return p_bits() != q_bits(); }
114
115 private:
116 BigInt m_d;
117 BigInt m_p;
118 BigInt m_q;
119 BigInt m_d1;
120 BigInt m_d2;
121 BigInt m_c;
122
123 const Montgomery_Params m_monty_p;
124 const Montgomery_Params m_monty_q;
125 Montgomery_Int m_c_monty;
126 size_t m_p_bits;
127 size_t m_q_bits;
128};
129
130std::shared_ptr<const RSA_Public_Data> RSA_PublicKey::public_data() const {
131 return m_public;
132}
133
134const BigInt& RSA_PublicKey::get_int_field(std::string_view field) const {
135 if(field == "n") {
136 return m_public->get_n();
137 } else if(field == "e") {
138 return m_public->get_e();
139 } else {
140 return Public_Key::get_int_field(field);
141 }
142}
143
144std::unique_ptr<Private_Key> RSA_PublicKey::generate_another(RandomNumberGenerator& rng) const {
145 return std::make_unique<RSA_PrivateKey>(rng, m_public->public_modulus_bits(), 65537);
146}
147
149 return m_public->get_n();
150}
151
153 return m_public->get_e();
154}
155
157 if(n.signum() <= 0 || n.is_even() || n.bits() < 384 || n.bits() > 16384) {
158 throw Decoding_Error("Invalid RSA public key modulus");
159 }
160 if(e.is_even() || e <= 1 || e >= n || e.bits() > 256) {
161 throw Decoding_Error("Invalid RSA public key exponent");
162 }
163 m_public = std::make_shared<RSA_Public_Data>(std::move(n), std::move(e));
164}
165
166RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) {
167 // RFC 4055 Section 1.2 has that parameters MUST be NULL, but historical
168 // reasons make that difficult to enforce, so absent is also accepted.
169 //
170 // This only checks rsaEncryption; PSS/OAEP key identifiers have their own parameter encoding
171 if(alg_id.oid().registered_name() == "RSA" && !alg_id.parameters_are_null_or_empty()) {
172 throw Decoding_Error("Unexpected parameters for RSA public key");
173 }
174
175 BigInt n;
176 BigInt e;
178
179 init(std::move(n), std::move(e));
180}
181
186
187RSA_PublicKey::RSA_PublicKey(const BigInt& modulus, const BigInt& exponent) {
188 BigInt n = modulus;
189 BigInt e = exponent;
190 init(std::move(n), std::move(e));
191}
192
194 return m_public->public_modulus_bits();
195}
196
200
204
205std::vector<uint8_t> RSA_PublicKey::raw_public_key_bits() const {
206 throw Not_Implemented("an RSA public key does not provide a raw binary representation.");
207}
208
209std::vector<uint8_t> RSA_PublicKey::public_key_bits() const {
210 std::vector<uint8_t> output;
211 DER_Encoder der(output);
213
214 return output;
215}
216
217/*
218* Check RSA Public Parameters
219*/
220bool RSA_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*strong*/) const {
221 if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
222 return false;
223 }
224 return true;
225}
226
227std::shared_ptr<const RSA_Private_Data> RSA_PrivateKey::private_data() const {
228 return m_private;
229}
230
232 return DER_Encoder()
234 .encode(static_cast<size_t>(0))
235 .encode(get_n())
236 .encode(get_e())
237 .encode(get_d())
238 .encode(get_p())
239 .encode(get_q())
240 .encode(get_d1())
241 .encode(get_d2())
242 .encode(get_c())
243 .end_cons()
244 .get_contents();
245}
246
248 return m_private->get_p();
249}
250
252 return m_private->get_q();
253}
254
256 return m_private->get_d();
257}
258
260 return m_private->get_c();
261}
262
264 return m_private->get_d1();
265}
266
268 return m_private->get_d2();
269}
270
271void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) {
272 if(d < 2 || p < 3 || q < 3 || p == q) {
273 throw Decoding_Error("Invalid RSA private key parameters");
274 }
275 if(p * q != get_n()) {
276 throw Decoding_Error("Invalid RSA private key: p * q != n");
277 }
278 m_private = std::make_shared<RSA_Private_Data>(
279 std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
280}
281
282RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) {
283 if(alg_id.oid().registered_name() == "RSA" && !alg_id.parameters_are_null_or_empty()) {
284 throw Decoding_Error("Unexpected parameters for RSA private key");
285 }
286
287 BigInt n;
288 BigInt e;
289 BigInt d;
290 BigInt p;
291 BigInt q;
292 BigInt d1;
293 BigInt d2;
294 BigInt c;
295
298 .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
299 .decode(n)
300 .decode(e)
301 .decode(d)
302 .decode(p)
303 .decode(q)
304 .decode(d1)
305 .decode(d2)
306 .decode(c)
307 .end_cons()
308 .verify_end();
309
310 RSA_PublicKey::init(std::move(n), std::move(e));
311
312 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
313}
314
316 const BigInt& prime1, const BigInt& prime2, const BigInt& exp, const BigInt& d_exp, const BigInt& mod) {
317 BigInt p = prime1;
318 BigInt q = prime2;
319 BigInt n = mod;
320 if(n.is_zero()) {
321 n = p * q;
322 }
323
324 BigInt e = exp;
325
326 BigInt d = d_exp;
327
328 const BigInt p_minus_1 = p - 1;
329 const BigInt q_minus_1 = q - 1;
330
331 if(d.is_zero()) {
332 const BigInt phi_n = lcm(p_minus_1, q_minus_1);
333 d = compute_rsa_secret_exponent(e, phi_n, p, q);
334 }
335
336 BigInt d1 = ct_modulo(d, p_minus_1);
337 BigInt d2 = ct_modulo(d, q_minus_1);
339
340 RSA_PublicKey::init(std::move(n), std::move(e));
341
342 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
343}
344
345/*
346* Create a RSA private key
347*/
349 constexpr size_t MIN_RSA_BITS = 1024;
350 constexpr size_t MAX_RSA_BITS = 16384;
351 constexpr size_t MOD_RSA_BITS = 8;
352
353 if(bits < MIN_RSA_BITS) {
354 throw Invalid_Argument(fmt("Cannot create an RSA key of {} bits: must be at least {} bits", bits, MIN_RSA_BITS));
355 } else if(bits > MAX_RSA_BITS) {
356 throw Invalid_Argument(
357 fmt("Cannot create an RSA key of {} bits: must be no more than {} bits", bits, MAX_RSA_BITS));
358 } else if(bits % MOD_RSA_BITS != 0) {
359 throw Invalid_Argument(
360 fmt("Cannot create an RSA key of {} bits: must be a multiple of {} bits", bits, MOD_RSA_BITS));
361 }
362
363 if(exp < 3 || exp % 2 == 0) {
364 throw Invalid_Argument("Invalid RSA encryption exponent");
365 }
366
367 const size_t p_bits = (bits + 1) / 2;
368 const size_t q_bits = bits - p_bits;
369
370 BigInt p;
371 BigInt q;
372 BigInt n;
373 BigInt e = BigInt::from_u64(exp);
374
375 for(size_t attempt = 0;; ++attempt) {
376 if(attempt > 10) {
377 throw Internal_Error("RNG failure during RSA key generation");
378 }
379
380 // TODO could generate primes in thread pool
381 p = generate_rsa_prime(rng, rng, p_bits, e);
382 q = generate_rsa_prime(rng, rng, q_bits, e);
383
384 const BigInt diff = p - q;
385 if(diff.bits() < (bits / 2) - 100) {
386 continue;
387 }
388
389 n = p * q;
390
391 if(n.bits() != bits) {
392 continue;
393 }
394
395 break;
396 }
397
398 const BigInt p_minus_1 = p - 1;
399 const BigInt q_minus_1 = q - 1;
400
401 const BigInt phi_n = lcm(p_minus_1, q_minus_1);
402 // This is guaranteed because p,q == 3 mod 4
404
405 BigInt d = compute_rsa_secret_exponent(e, phi_n, p, q);
406 BigInt d1 = ct_modulo(d, p_minus_1);
407 BigInt d2 = ct_modulo(d, q_minus_1);
409
410 RSA_PublicKey::init(std::move(n), std::move(e));
411
412 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
413}
414
415const BigInt& RSA_PrivateKey::get_int_field(std::string_view field) const {
416 if(field == "p") {
417 return m_private->get_p();
418 } else if(field == "q") {
419 return m_private->get_q();
420 } else if(field == "d") {
421 return m_private->get_d();
422 } else if(field == "c") {
423 return m_private->get_c();
424 } else if(field == "d1") {
425 return m_private->get_d1();
426 } else if(field == "d2") {
427 return m_private->get_d2();
428 } else {
429 return RSA_PublicKey::get_int_field(field);
430 }
431}
432
433std::unique_ptr<Public_Key> RSA_PrivateKey::public_key() const {
434 return std::make_unique<RSA_PublicKey>(get_n(), get_e());
435}
436
437/*
438* Check Private RSA Parameters
439*/
441 if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
442 return false;
443 }
444
445 if(get_d() < 2 || get_p() < 3 || get_q() < 3) {
446 return false;
447 }
448
449 if(get_p() * get_q() != get_n()) {
450 return false;
451 }
452
453 if(get_p() == get_q()) {
454 return false;
455 }
456
457 if(get_d1() != ct_modulo(get_d(), get_p() - 1)) {
458 return false;
459 }
460 if(get_d2() != ct_modulo(get_d(), get_q() - 1)) {
461 return false;
462 }
464 return false;
465 }
466
467 const size_t prob = (strong) ? 128 : 12;
468
469 if(!is_prime(get_p(), rng, prob)) {
470 return false;
471 }
472 if(!is_prime(get_q(), rng, prob)) {
473 return false;
474 }
475
476 if(strong) {
477 if(ct_modulo(get_e() * get_d(), lcm(get_p() - 1, get_q() - 1)) != 1) {
478 return false;
479 }
480
481#if defined(BOTAN_HAS_PSS) && defined(BOTAN_HAS_SHA_256)
482 const std::string padding = "PSS(SHA-256)";
483#else
484 const std::string padding = "Raw";
485#endif
486
487 return KeyPair::signature_consistency_check(rng, *this, padding);
488 }
489
490 return true;
491}
492
493namespace {
494
495/*
496* To recover the final value from the CRT representation (j1,j2)
497* we use Garner's algorithm:
498* c = q^-1 mod p (this is precomputed)
499* h = c*(j1-j2) mod p
500* r = h*q + j2
501*/
502BigInt crt_recombine(const Montgomery_Int& j1,
503 const Montgomery_Int& j2_p,
504 const BigInt& j2,
505 const Montgomery_Int& c_monty,
506 const BigInt& p,
507 const BigInt& q) {
508 // We skip CRT entirely if the primes are not balanced (same bitlength) so q is also of this size
509 const size_t p_words = p.sig_words();
510 BOTAN_ASSERT_NOMSG(p_words == q.sig_words());
511
512 const size_t n_words = 2 * p_words;
513
514 // Ensure sufficient storage
515 BOTAN_ASSERT_NOMSG(j1.repr().size() >= p_words);
516 BOTAN_ASSERT_NOMSG(j2_p.repr().size() >= p_words);
517 BOTAN_ASSERT_NOMSG(j2.size() >= p_words);
518
519 /*
520 * Compute h = (j1 - j2) * c mod p
521 *
522 * This doesn't quite match up with the "Smooth-CRT" proposal; there we would
523 * multiply by a precomputed c * R2, which would have the effect of both
524 * multiplying by c and immediately converting from Montgomery to standard form.
525 */
526 secure_vector<word> ws(2 * p_words);
527
528 const Montgomery_Int h_monty = (j1 - j2_p).mul(c_monty, ws);
529
530 const BigInt h = h_monty.value();
531 // Montgomery_Int always returns values sized to the modulus
532 BOTAN_ASSERT_NOMSG(h.size() >= p_words);
533 BOTAN_DEBUG_ASSERT(h.sig_words() <= p_words);
534
535 // Compute r = h * q
536 secure_vector<word> r(2 * p_words);
537
538 bigint_mul(r.data(), r.size(), h._data(), h.size(), p_words, q._data(), q.size(), p_words, ws.data(), ws.size());
539
540 // r += j2
541 const word carry = bigint_add2(r.data(), n_words, j2._data(), p_words);
542 BOTAN_ASSERT_NOMSG(carry == 0); // should not be possible since it would imply r > the public modulus
543
544 return BigInt::_from_words(r);
545}
546
547/**
548* RSA private (decrypt/sign) operation
549*/
550class RSA_Private_Operation {
551 protected:
552 size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
553
554 size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
555
556 explicit RSA_Private_Operation(const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
557 m_public(rsa.public_data()),
558 m_private(rsa.private_data()),
559 m_blinder(
560 m_public->reducer_mod_n(),
561 rng,
562 [this](const BigInt& k) { return m_public->public_op(k); },
563 [this](const BigInt& k) { return inverse_mod_rsa_public_modulus(k, m_public->get_n()); }),
564 m_blinding_bits(64),
565 m_max_d1_bits(m_private->p_bits() + m_blinding_bits),
566 m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {}
567
568 void raw_op(std::span<uint8_t> out, std::span<const uint8_t> input) {
569 // These early exits are fine because the invalidity is based only
570 // on public information, namely the ciphertext and the public modulus
571 if(input.size() > public_modulus_bytes()) {
572 throw Decoding_Error("RSA input is too long for this key");
573 }
574 const BigInt input_bn(input.data(), input.size());
575 if(input_bn.is_zero() || input_bn >= m_public->get_n()) {
576 throw Decoding_Error("RSA input is not in the valid range");
577 }
578
579 // TODO: This should be a function on blinder
580 // BigInt Blinder::run_blinded_function(std::function<BigInt, BigInt> fn, const BigInt& input);
581
582 const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
583 BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
584 BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(), "output size check");
585 recovered.serialize_to(out);
586 }
587
588 private:
589 BigInt rsa_private_op(const BigInt& m) const {
590 /*
591 All normal implementations generate p/q of the same bitlength,
592 so this should rarely occur in practice
593 */
594 if(m_private->primes_imbalanced()) {
595 return monty_exp(m_public->monty_n(), m, m_private->get_d(), m_public->get_n().bits()).value();
596 }
597
598 static constexpr size_t powm_window = 4;
599
600 // Compute this in main thread to avoid racing on the rng
601 const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
602
603#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
604 #define BOTAN_RSA_USE_ASYNC
605#endif
606
607#if defined(BOTAN_RSA_USE_ASYNC)
608 /*
609 * Precompute m.sig_words in the main thread before calling async. Otherwise
610 * the two threads race (during Barrett_Reduction::reduce) and while the output
611 * is correct in both threads, helgrind warns.
612 */
613 m.sig_words();
614
615 auto future_j1 = Thread_Pool::global_instance().run([this, &m, &d1_mask]() {
616#endif
617 const BigInt masked_d1 = m_private->blinded_d1(d1_mask);
618 auto powm_d1_p = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_p(), m), powm_window);
619 auto j1 = monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
620
621#if defined(BOTAN_RSA_USE_ASYNC)
622 return j1;
623 });
624#endif
625
626 const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
627 const BigInt masked_d2 = m_private->blinded_d2(d2_mask);
628 auto powm_d2_q = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_q(), m), powm_window);
629 const auto j2 = monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits).value();
630
631#if defined(BOTAN_RSA_USE_ASYNC)
632 auto j1 = future_j1.get();
633#endif
634
635 // Reduce j2 modulo p
636 const auto j2_p = Montgomery_Int::from_wide_int(m_private->monty_p(), j2);
637
638 return crt_recombine(j1, j2_p, j2, m_private->get_c_monty(), m_private->get_p(), m_private->get_q());
639 }
640
641 std::shared_ptr<const RSA_Public_Data> m_public;
642 std::shared_ptr<const RSA_Private_Data> m_private;
643
644 // XXX could the blinder starting pair be shared?
645 Blinder m_blinder;
646 const size_t m_blinding_bits;
647 const size_t m_max_d1_bits;
648 const size_t m_max_d2_bits;
649};
650
651class RSA_Signature_Operation final : public PK_Ops::Signature,
652 private RSA_Private_Operation {
653 public:
654 void update(std::span<const uint8_t> msg) override { m_padding->update(msg.data(), msg.size()); }
655
656 std::vector<uint8_t> sign(RandomNumberGenerator& rng) override {
657 const size_t max_input_bits = public_modulus_bits() - 1;
658 const auto msg = m_padding->raw_data();
659 const auto padded = m_padding->encoding_of(msg, max_input_bits, rng);
660
661 std::vector<uint8_t> out(public_modulus_bytes());
662 raw_op(out, padded);
663 return out;
664 }
665
666 size_t signature_length() const override { return public_modulus_bytes(); }
667
668 AlgorithmIdentifier algorithm_identifier() const override;
669
670 std::string hash_function() const override { return m_padding->hash_function(); }
671
672 RSA_Signature_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
673 RSA_Private_Operation(rsa, rng), m_padding(SignaturePaddingScheme::create_or_throw(padding)) {}
674
675 private:
676 std::unique_ptr<SignaturePaddingScheme> m_padding;
677};
678
679AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier() const {
680 const std::string padding_name = m_padding->name();
681
682 try {
683 const std::string full_name = "RSA/" + padding_name;
684 const OID oid = OID::from_string(full_name);
685 // RFC 8017 Appendix A.2 specifies RSA signatures for most hashes use NULL parameter
686 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_NULL_PARAM);
687 } catch(Lookup_Error&) {}
688
689 if(padding_name.starts_with("PSS(")) {
690 auto parameters = PSS_Params::from_padding_name(m_padding->name()).serialize();
691 return AlgorithmIdentifier("RSA/PSS", parameters);
692 }
693
694 throw Invalid_Argument(fmt("Signatures using RSA/{} are not supported", padding_name));
695}
696
697class RSA_Decryption_Operation final : public PK_Ops::Decryption_with_Padding,
698 private RSA_Private_Operation {
699 public:
700 RSA_Decryption_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
701 PK_Ops::Decryption_with_Padding(padding), RSA_Private_Operation(rsa, rng) {}
702
703 size_t plaintext_length(size_t /*ctext_len*/) const override { return public_modulus_bytes(); }
704
705 size_t ciphertext_length(size_t /*ptext_len*/) const override { return public_modulus_bytes(); }
706
707 secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input) override {
708 /*
709 * RFC 8017 7.1.2 and 7.2.2
710 *
711 * If the length of the ciphertext C is not k octets, output
712 * "decryption error" and stop.
713 */
714 if(input.size() != public_modulus_bytes()) {
715 throw Decoding_Error("RSA ciphertext is an incorrect size for this public key");
716 }
717 secure_vector<uint8_t> out(public_modulus_bytes());
718 raw_op(out, input);
719 return out;
720 }
721};
722
723class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KDF,
724 private RSA_Private_Operation {
725 public:
726 RSA_KEM_Decryption_Operation(const RSA_PrivateKey& key, std::string_view kdf, RandomNumberGenerator& rng) :
727 PK_Ops::KEM_Decryption_with_KDF(kdf), RSA_Private_Operation(key, rng) {}
728
729 size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
730
731 size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
732
733 void raw_kem_decrypt(std::span<uint8_t> out_shared_key, std::span<const uint8_t> encapsulated_key) override {
734 /*
735 * RFC 9690 Section 8
736 *
737 * The RSA-KEM algorithm provides a fixed-length ciphertext. The recipient MUST
738 * check that the received byte string is the expected length [...]
739 *
740 * This length check is based only on public information (the encapsulated key and
741 * the public modulus) so an early exit does not leak anything.
742 */
743 if(encapsulated_key.size() != public_modulus_bytes()) {
744 throw Decoding_Error("Invalid RSA-KEM ciphertext length");
745 }
746 raw_op(out_shared_key, encapsulated_key);
747 }
748};
749
750/**
751* RSA public (encrypt/verify) operation
752*/
753class RSA_Public_Operation {
754 public:
755 explicit RSA_Public_Operation(const RSA_PublicKey& rsa) : m_public(rsa.public_data()) {}
756
757 size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
758
759 protected:
760 BigInt public_op(const BigInt& m) const {
761 if(m >= m_public->get_n()) {
762 throw Decoding_Error("RSA public op - input is too large");
763 }
764
765 return m_public->public_op(m);
766 }
767
768 size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
769
770 const BigInt& get_n() const { return m_public->get_n(); }
771
772 private:
773 std::shared_ptr<const RSA_Public_Data> m_public;
774};
775
776class RSA_Encryption_Operation final : public PK_Ops::Encryption_with_Padding,
777 private RSA_Public_Operation {
778 public:
779 RSA_Encryption_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
780 PK_Ops::Encryption_with_Padding(padding), RSA_Public_Operation(rsa) {}
781
782 size_t ciphertext_length(size_t /*ptext_len*/) const override { return public_modulus_bytes(); }
783
784 size_t max_ptext_input_bits() const override { return public_modulus_bits() - 1; }
785
786 std::vector<uint8_t> raw_encrypt(std::span<const uint8_t> input, RandomNumberGenerator& /*rng*/) override {
787 const BigInt input_bn(input);
788 return public_op(input_bn).serialize(public_modulus_bytes());
789 }
790};
791
792class RSA_Verify_Operation final : public PK_Ops::Verification,
793 private RSA_Public_Operation {
794 public:
795 void update(std::span<const uint8_t> msg) override { m_padding->update(msg.data(), msg.size()); }
796
797 bool is_valid_signature(std::span<const uint8_t> sig) override {
798 const auto msg = m_padding->raw_data();
799 const auto message_repr = recover_message_repr(sig.data(), sig.size());
800 return m_padding->verify(message_repr, msg, public_modulus_bits() - 1);
801 }
802
803 RSA_Verify_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
804 RSA_Public_Operation(rsa), m_padding(SignaturePaddingScheme::create_or_throw(padding)) {}
805
806 std::string hash_function() const override { return m_padding->hash_function(); }
807
808 private:
809 std::vector<uint8_t> recover_message_repr(const uint8_t input[], size_t input_len) {
810 // RFC 8017 8.1.2 and 8.2.2 state
811 // If the length of the signature S is not k octets,
812 // output "invalid signature" and stop.
813 //
814 if(input_len != public_modulus_bytes()) {
815 throw Decoding_Error("RSA signature is an incorrect size for this public key");
816 }
817 const BigInt input_bn(input, input_len);
818 return public_op(input_bn).serialize();
819 }
820
821 std::unique_ptr<SignaturePaddingScheme> m_padding;
822};
823
824class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KDF,
825 private RSA_Public_Operation {
826 public:
827 RSA_KEM_Encryption_Operation(const RSA_PublicKey& key, std::string_view kdf) :
828 PK_Ops::KEM_Encryption_with_KDF(kdf), RSA_Public_Operation(key) {}
829
830 private:
831 size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
832
833 size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
834
835 void raw_kem_encrypt(std::span<uint8_t> out_encapsulated_key,
836 std::span<uint8_t> raw_shared_key,
837 RandomNumberGenerator& rng) override {
838 const BigInt r = BigInt::random_integer(rng, BigInt::one(), get_n());
839 const BigInt c = public_op(r);
840
841 c.serialize_to(out_encapsulated_key);
842 r.serialize_to(raw_shared_key);
843 }
844};
845
846} // namespace
847
848std::unique_ptr<PK_Ops::Encryption> RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
849 std::string_view params,
850 std::string_view provider) const {
851 if(provider == "base" || provider.empty()) {
852 return std::make_unique<RSA_Encryption_Operation>(*this, params);
853 }
854 throw Provider_Not_Found(algo_name(), provider);
855}
856
857std::unique_ptr<PK_Ops::KEM_Encryption> RSA_PublicKey::create_kem_encryption_op(std::string_view params,
858 std::string_view provider) const {
859 if(provider == "base" || provider.empty()) {
860 return std::make_unique<RSA_KEM_Encryption_Operation>(*this, params);
861 }
862 throw Provider_Not_Found(algo_name(), provider);
863}
864
865std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_verification_op(std::string_view params,
866 std::string_view provider) const {
867 if(provider == "base" || provider.empty()) {
868 return std::make_unique<RSA_Verify_Operation>(*this, params);
869 }
870
871 throw Provider_Not_Found(algo_name(), provider);
872}
873
874namespace {
875
876std::string parse_rsa_signature_algorithm(const AlgorithmIdentifier& alg_id) {
877 const auto oid_name = alg_id.oid().registered_name();
878 if(!oid_name) {
879 throw Decoding_Error("Unknown AlgorithmIdentifier for RSA X.509 signatures");
880 }
881
882 const auto sig_info = split_on(*oid_name, '/');
883
884 if(sig_info.empty() || sig_info.size() != 2 || sig_info[0] != "RSA") {
885 throw Decoding_Error("Unknown AlgorithmIdentifier for RSA X.509 signatures");
886 }
887
888 std::string padding = sig_info[1];
889
890 if(padding != "PSS") {
891 if(!alg_id.parameters_are_null_or_empty()) {
892 throw Decoding_Error("Non-PSS RSA signature algorithm OID has unexpected parameters");
893 }
894 }
895
896 if(padding == "PSS") {
897 // "MUST contain RSASSA-PSS-params"
898 if(alg_id.parameters().empty()) {
899 throw Decoding_Error("PSS params must be provided");
900 }
901
902 const PSS_Params pss_params(alg_id.parameters());
903
904 // hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
905 // We also support SHA-3 (is also supported by e.g. OpenSSL and bouncycastle)
906 const auto hash_algo = pss_params.hash_algid().oid().registered_name();
907 if(hash_algo != "SHA-1" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384" &&
908 hash_algo != "SHA-512" && hash_algo != "SHA-3(224)" && hash_algo != "SHA-3(256)" &&
909 hash_algo != "SHA-3(384)" && hash_algo != "SHA-3(512)") {
910 throw Decoding_Error("Unacceptable hash for PSS signatures");
911 }
912
913 if(pss_params.mgf_algid().oid().registered_name() != "MGF1") {
914 throw Decoding_Error("Unacceptable MGF for PSS signatures");
915 }
916
917 // For MGF1, it is strongly RECOMMENDED that the underlying hash
918 // function be the same as the one identified by hashAlgorithm
919 if(pss_params.hash_algid() != pss_params.mgf_hash_algid()) {
920 throw Decoding_Error("Unacceptable MGF hash for PSS signatures");
921 }
922
923 if(pss_params.trailer_field() != 1) {
924 throw Decoding_Error("Unacceptable trailer field for PSS signatures");
925 }
926
927 padding += fmt("({},MGF1,{})", *hash_algo, pss_params.salt_length());
928 }
929
930 return padding;
931}
932
933} // namespace
934
935std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_x509_verification_op(const AlgorithmIdentifier& alg_id,
936 std::string_view provider) const {
937 if(provider == "base" || provider.empty()) {
938 return std::make_unique<RSA_Verify_Operation>(*this, parse_rsa_signature_algorithm(alg_id));
939 }
940
941 throw Provider_Not_Found(algo_name(), provider);
942}
943
944std::unique_ptr<PK_Ops::Decryption> RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
945 std::string_view params,
946 std::string_view provider) const {
947 if(provider == "base" || provider.empty()) {
948 return std::make_unique<RSA_Decryption_Operation>(*this, params, rng);
949 }
950
951 throw Provider_Not_Found(algo_name(), provider);
952}
953
954std::unique_ptr<PK_Ops::KEM_Decryption> RSA_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
955 std::string_view params,
956 std::string_view provider) const {
957 if(provider == "base" || provider.empty()) {
958 return std::make_unique<RSA_KEM_Decryption_Operation>(*this, params, rng);
959 }
960
961 throw Provider_Not_Found(algo_name(), provider);
962}
963
964std::unique_ptr<PK_Ops::Signature> RSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
965 std::string_view params,
966 std::string_view provider) const {
967 if(provider == "base" || provider.empty()) {
968 return std::make_unique<RSA_Signature_Operation>(*this, params, rng);
969 }
970
971 throw Provider_Not_Found(algo_name(), provider);
972}
973
974} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:129
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:62
bool parameters_are_null_or_empty() const
Definition asn1_obj.h:720
const std::vector< uint8_t > & parameters() const
Definition asn1_obj.h:693
const OID & oid() const
Definition asn1_obj.h:688
virtual const BigInt & get_int_field(std::string_view field) const
Definition pk_keys.cpp:18
virtual OID object_identifier() const
Definition pk_keys.cpp:22
static Limits DER()
Definition ber_dec.h:42
BER_Decoder & decode(bool &out)
Definition ber_dec.h:358
BER_Decoder & verify_end()
Definition ber_dec.cpp:471
BER_Decoder & end_cons()
Definition ber_dec.cpp:630
BER_Decoder start_sequence()
Definition ber_dec.h:275
BER_Decoder & decode_and_check(const T &expected, std::string_view error_msg)
Definition ber_dec.h:701
size_t sig_words() const
Definition bigint.h:687
size_t size() const
Definition bigint.h:681
static BigInt _from_words(secure_vector< word > &words)
Definition bigint.h:1052
size_t bits() const
Definition bigint.cpp:307
static BigInt from_u64(uint64_t n)
Definition bigint.cpp:30
const word * _data() const
Definition bigint.h:1033
bool is_zero() const
Definition bigint.h:510
secure_vector< uint8_t > get_contents()
Definition der_enc.cpp:161
DER_Encoder & start_sequence()
Definition der_enc.h:86
DER_Encoder & end_cons()
Definition der_enc.cpp:208
DER_Encoder & encode(bool b)
Definition der_enc.cpp:313
static Montgomery_Int from_wide_int(const Montgomery_Params &params, const BigInt &x)
Definition monty.cpp:235
const secure_vector< word > & repr() const
Definition monty.h:143
BigInt value() const
Definition monty.cpp:273
std::optional< std::string > registered_name() const
Definition asn1_oid.cpp:149
virtual void update(std::span< const uint8_t > input)=0
const BigInt & get_q() const
Definition rsa.cpp:251
const BigInt & get_int_field(std::string_view field) const override
Definition rsa.cpp:415
std::shared_ptr< const RSA_Private_Data > private_data() const
Definition rsa.cpp:227
std::unique_ptr< PK_Ops::Decryption > create_decryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:944
const BigInt & get_c() const
Definition rsa.cpp:259
std::unique_ptr< PK_Ops::Signature > create_signature_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:964
RSA_PrivateKey(const AlgorithmIdentifier &alg_id, std::span< const uint8_t > key_bits)
Definition rsa.cpp:282
const BigInt & get_p() const
Definition rsa.cpp:247
const BigInt & get_d2() const
Definition rsa.cpp:267
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition rsa.cpp:440
const BigInt & get_d() const
Definition rsa.cpp:255
secure_vector< uint8_t > private_key_bits() const override
Definition rsa.cpp:231
std::unique_ptr< PK_Ops::KEM_Decryption > create_kem_decryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:954
std::unique_ptr< Public_Key > public_key() const override
Definition rsa.cpp:433
const BigInt & get_d1() const
Definition rsa.cpp:263
std::unique_ptr< PK_Ops::Encryption > create_encryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:848
void init(BigInt &&n, BigInt &&e)
Definition rsa.cpp:156
size_t key_length() const override
Definition rsa.cpp:193
std::unique_ptr< PK_Ops::Verification > create_verification_op(std::string_view params, std::string_view provider) const override
Definition rsa.cpp:865
std::string algo_name() const override
Definition rsa.h:41
std::unique_ptr< PK_Ops::Verification > create_x509_verification_op(const AlgorithmIdentifier &alg_id, std::string_view provider) const override
Definition rsa.cpp:935
const BigInt & get_int_field(std::string_view field) const override
Definition rsa.cpp:134
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition rsa.cpp:220
const BigInt & get_n() const
Definition rsa.cpp:148
size_t estimated_strength() const override
Definition rsa.cpp:197
std::unique_ptr< PK_Ops::KEM_Encryption > create_kem_encryption_op(std::string_view params, std::string_view provider) const override
Definition rsa.cpp:857
std::unique_ptr< Private_Key > generate_another(RandomNumberGenerator &rng) const override
Definition rsa.cpp:144
std::vector< uint8_t > raw_public_key_bits() const override
Definition rsa.cpp:205
AlgorithmIdentifier algorithm_identifier() const override
Definition rsa.cpp:201
std::vector< uint8_t > public_key_bits() const override
Definition rsa.cpp:209
std::shared_ptr< const RSA_Public_Data > m_public
Definition rsa.h:91
std::shared_ptr< const RSA_Public_Data > public_data() const
Definition rsa.cpp:130
const BigInt & get_e() const
Definition rsa.cpp:152
bool supports_operation(PublicKeyOperation op) const override
Definition rsa.cpp:182
auto run(F &&f, Args &&... args) -> std::future< std::invoke_result_t< F, Args... > >
Definition thread_pool.h:66
static Thread_Pool & global_instance()
bool signature_consistency_check(RandomNumberGenerator &rng, const Private_Key &private_key, const Public_Key &public_key, std::string_view padding)
Definition keypair.cpp:49
BigInt inverse_mod_secret_prime(const BigInt &x, const BigInt &p)
Definition mod_inv.cpp:282
constexpr auto bigint_add2(W x[], size_t x_size, const W y[], size_t y_size) -> W
Definition mp_core.h:94
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
BigInt lcm(const BigInt &a, const BigInt &b)
Definition numthry.cpp:296
std::shared_ptr< const Montgomery_Exponentiation_State > monty_precompute(const Montgomery_Int &g, size_t window_bits, bool const_time)
std::vector< std::string > split_on(std::string_view str, char delim)
Definition parsing.cpp:141
size_t low_zero_bits(const BigInt &n)
Definition numthry.cpp:194
void bigint_mul(word z[], size_t z_size, const word x[], size_t x_size, size_t x_sw, const word y[], size_t y_size, size_t y_sw, word workspace[], size_t ws_size)
Definition mp_karat.cpp:283
bool is_prime(const BigInt &n, RandomNumberGenerator &rng, size_t prob, bool is_random)
Definition numthry.cpp:381
BigInt ct_modulo(const BigInt &x, const BigInt &y)
Definition divide.cpp:198
Montgomery_Int monty_execute_vartime(const Montgomery_Exponentiation_State &precomputed_state, const BigInt &k)
BigInt compute_rsa_secret_exponent(const BigInt &e, const BigInt &phi_n, const BigInt &p, const BigInt &q)
Definition mod_inv.cpp:341
PublicKeyOperation
Definition pk_keys.h:46
BigInt generate_rsa_prime(RandomNumberGenerator &keygen_rng, RandomNumberGenerator &prime_test_rng, size_t bits, const BigInt &coprime, size_t prob)
Definition make_prm.cpp:248
void carry(int64_t &h0, int64_t &h1)
Montgomery_Int monty_execute(const Montgomery_Exponentiation_State &precomputed_state, const BigInt &k, size_t max_k_bits)
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
BigInt inverse_mod_rsa_public_modulus(const BigInt &x, const BigInt &n)
Definition mod_inv.cpp:306
size_t if_work_factor(size_t bits)
std::conditional_t< HasNative64BitRegisters, std::uint64_t, uint32_t > word
The native machine word, used as the limb type for multiprecision integers.
Definition types.h:131
Montgomery_Int monty_exp(const Montgomery_Params &params_p, const BigInt &g, const BigInt &k, size_t max_k_bits)
Definition monty_exp.h:46