Botan 3.12.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& /*unused*/, std::span<const uint8_t> key_bits) {
167 BigInt n;
168 BigInt e;
170
171 init(std::move(n), std::move(e));
172}
173
178
179RSA_PublicKey::RSA_PublicKey(const BigInt& modulus, const BigInt& exponent) {
180 BigInt n = modulus;
181 BigInt e = exponent;
182 init(std::move(n), std::move(e));
183}
184
186 return m_public->public_modulus_bits();
187}
188
192
196
197std::vector<uint8_t> RSA_PublicKey::raw_public_key_bits() const {
198 throw Not_Implemented("an RSA public key does not provide a raw binary representation.");
199}
200
201std::vector<uint8_t> RSA_PublicKey::public_key_bits() const {
202 std::vector<uint8_t> output;
203 DER_Encoder der(output);
205
206 return output;
207}
208
209/*
210* Check RSA Public Parameters
211*/
212bool RSA_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*strong*/) const {
213 if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
214 return false;
215 }
216 return true;
217}
218
219std::shared_ptr<const RSA_Private_Data> RSA_PrivateKey::private_data() const {
220 return m_private;
221}
222
224 return DER_Encoder()
226 .encode(static_cast<size_t>(0))
227 .encode(get_n())
228 .encode(get_e())
229 .encode(get_d())
230 .encode(get_p())
231 .encode(get_q())
232 .encode(get_d1())
233 .encode(get_d2())
234 .encode(get_c())
235 .end_cons()
236 .get_contents();
237}
238
240 return m_private->get_p();
241}
242
244 return m_private->get_q();
245}
246
248 return m_private->get_d();
249}
250
252 return m_private->get_c();
253}
254
256 return m_private->get_d1();
257}
258
260 return m_private->get_d2();
261}
262
263void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) {
264 if(d < 2 || p < 3 || q < 3 || p == q) {
265 throw Decoding_Error("Invalid RSA private key parameters");
266 }
267 if(p * q != get_n()) {
268 throw Decoding_Error("Invalid RSA private key: p * q != n");
269 }
270 m_private = std::make_shared<RSA_Private_Data>(
271 std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
272}
273
274RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
275 BigInt n;
276 BigInt e;
277 BigInt d;
278 BigInt p;
279 BigInt q;
280 BigInt d1;
281 BigInt d2;
282 BigInt c;
283
286 .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
287 .decode(n)
288 .decode(e)
289 .decode(d)
290 .decode(p)
291 .decode(q)
292 .decode(d1)
293 .decode(d2)
294 .decode(c)
295 .end_cons()
296 .verify_end();
297
298 RSA_PublicKey::init(std::move(n), std::move(e));
299
300 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
301}
302
304 const BigInt& prime1, const BigInt& prime2, const BigInt& exp, const BigInt& d_exp, const BigInt& mod) {
305 BigInt p = prime1;
306 BigInt q = prime2;
307 BigInt n = mod;
308 if(n.is_zero()) {
309 n = p * q;
310 }
311
312 BigInt e = exp;
313
314 BigInt d = d_exp;
315
316 const BigInt p_minus_1 = p - 1;
317 const BigInt q_minus_1 = q - 1;
318
319 if(d.is_zero()) {
320 const BigInt phi_n = lcm(p_minus_1, q_minus_1);
321 d = compute_rsa_secret_exponent(e, phi_n, p, q);
322 }
323
324 BigInt d1 = ct_modulo(d, p_minus_1);
325 BigInt d2 = ct_modulo(d, q_minus_1);
327
328 RSA_PublicKey::init(std::move(n), std::move(e));
329
330 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
331}
332
333/*
334* Create a RSA private key
335*/
337 constexpr size_t MIN_RSA_BITS = 1024;
338 constexpr size_t MAX_RSA_BITS = 16384;
339 constexpr size_t MOD_RSA_BITS = 8;
340
341 if(bits < MIN_RSA_BITS) {
342 throw Invalid_Argument(fmt("Cannot create an RSA key of {} bits: must be at least {} bits", bits, MIN_RSA_BITS));
343 } else if(bits > MAX_RSA_BITS) {
344 throw Invalid_Argument(
345 fmt("Cannot create an RSA key of {} bits: must be no more than {} bits", bits, MAX_RSA_BITS));
346 } else if(bits % MOD_RSA_BITS != 0) {
347 throw Invalid_Argument(
348 fmt("Cannot create an RSA key of {} bits: must be a multiple of {} bits", bits, MOD_RSA_BITS));
349 }
350
351 if(exp < 3 || exp % 2 == 0) {
352 throw Invalid_Argument("Invalid RSA encryption exponent");
353 }
354
355 const size_t p_bits = (bits + 1) / 2;
356 const size_t q_bits = bits - p_bits;
357
358 BigInt p;
359 BigInt q;
360 BigInt n;
361 BigInt e = BigInt::from_u64(exp);
362
363 for(size_t attempt = 0;; ++attempt) {
364 if(attempt > 10) {
365 throw Internal_Error("RNG failure during RSA key generation");
366 }
367
368 // TODO could generate primes in thread pool
369 p = generate_rsa_prime(rng, rng, p_bits, e);
370 q = generate_rsa_prime(rng, rng, q_bits, e);
371
372 const BigInt diff = p - q;
373 if(diff.bits() < (bits / 2) - 100) {
374 continue;
375 }
376
377 n = p * q;
378
379 if(n.bits() != bits) {
380 continue;
381 }
382
383 break;
384 }
385
386 const BigInt p_minus_1 = p - 1;
387 const BigInt q_minus_1 = q - 1;
388
389 const BigInt phi_n = lcm(p_minus_1, q_minus_1);
390 // This is guaranteed because p,q == 3 mod 4
392
393 BigInt d = compute_rsa_secret_exponent(e, phi_n, p, q);
394 BigInt d1 = ct_modulo(d, p_minus_1);
395 BigInt d2 = ct_modulo(d, q_minus_1);
397
398 RSA_PublicKey::init(std::move(n), std::move(e));
399
400 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
401}
402
403const BigInt& RSA_PrivateKey::get_int_field(std::string_view field) const {
404 if(field == "p") {
405 return m_private->get_p();
406 } else if(field == "q") {
407 return m_private->get_q();
408 } else if(field == "d") {
409 return m_private->get_d();
410 } else if(field == "c") {
411 return m_private->get_c();
412 } else if(field == "d1") {
413 return m_private->get_d1();
414 } else if(field == "d2") {
415 return m_private->get_d2();
416 } else {
417 return RSA_PublicKey::get_int_field(field);
418 }
419}
420
421std::unique_ptr<Public_Key> RSA_PrivateKey::public_key() const {
422 return std::make_unique<RSA_PublicKey>(get_n(), get_e());
423}
424
425/*
426* Check Private RSA Parameters
427*/
429 if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
430 return false;
431 }
432
433 if(get_d() < 2 || get_p() < 3 || get_q() < 3) {
434 return false;
435 }
436
437 if(get_p() * get_q() != get_n()) {
438 return false;
439 }
440
441 if(get_p() == get_q()) {
442 return false;
443 }
444
445 if(get_d1() != ct_modulo(get_d(), get_p() - 1)) {
446 return false;
447 }
448 if(get_d2() != ct_modulo(get_d(), get_q() - 1)) {
449 return false;
450 }
452 return false;
453 }
454
455 const size_t prob = (strong) ? 128 : 12;
456
457 if(!is_prime(get_p(), rng, prob)) {
458 return false;
459 }
460 if(!is_prime(get_q(), rng, prob)) {
461 return false;
462 }
463
464 if(strong) {
465 if(ct_modulo(get_e() * get_d(), lcm(get_p() - 1, get_q() - 1)) != 1) {
466 return false;
467 }
468
469#if defined(BOTAN_HAS_PSS) && defined(BOTAN_HAS_SHA_256)
470 const std::string padding = "PSS(SHA-256)";
471#else
472 const std::string padding = "Raw";
473#endif
474
475 return KeyPair::signature_consistency_check(rng, *this, padding);
476 }
477
478 return true;
479}
480
481namespace {
482
483/*
484* To recover the final value from the CRT representation (j1,j2)
485* we use Garner's algorithm:
486* c = q^-1 mod p (this is precomputed)
487* h = c*(j1-j2) mod p
488* r = h*q + j2
489*/
490BigInt crt_recombine(const Montgomery_Int& j1,
491 const Montgomery_Int& j2_p,
492 const BigInt& j2,
493 const Montgomery_Int& c_monty,
494 const BigInt& p,
495 const BigInt& q) {
496 // We skip CRT entirely if the primes are not balanced (same bitlength) so q is also of this size
497 const size_t p_words = p.sig_words();
498 BOTAN_ASSERT_NOMSG(p_words == q.sig_words());
499
500 const size_t n_words = 2 * p_words;
501
502 // Ensure sufficient storage
503 BOTAN_ASSERT_NOMSG(j1.repr().size() >= p_words);
504 BOTAN_ASSERT_NOMSG(j2_p.repr().size() >= p_words);
505 BOTAN_ASSERT_NOMSG(j2.size() >= p_words);
506
507 /*
508 * Compute h = (j1 - j2) * c mod p
509 *
510 * This doesn't quite match up with the "Smooth-CRT" proposal; there we would
511 * multiply by a precomputed c * R2, which would have the effect of both
512 * multiplying by c and immediately converting from Montgomery to standard form.
513 */
514 secure_vector<word> ws(2 * p_words);
515
516 const Montgomery_Int h_monty = (j1 - j2_p).mul(c_monty, ws);
517
518 const BigInt h = h_monty.value();
519 // Montgomery_Int always returns values sized to the modulus
520 BOTAN_ASSERT_NOMSG(h.size() >= p_words);
521 BOTAN_DEBUG_ASSERT(h.sig_words() <= p_words);
522
523 // Compute r = h * q
524 secure_vector<word> r(2 * p_words);
525
526 bigint_mul(r.data(), r.size(), h._data(), h.size(), p_words, q._data(), q.size(), p_words, ws.data(), ws.size());
527
528 // r += j2
529 const word carry = bigint_add2(r.data(), n_words, j2._data(), p_words);
530 BOTAN_ASSERT_NOMSG(carry == 0); // should not be possible since it would imply r > the public modulus
531
532 return BigInt::_from_words(r);
533}
534
535/**
536* RSA private (decrypt/sign) operation
537*/
538class RSA_Private_Operation {
539 protected:
540 size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
541
542 size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
543
544 explicit RSA_Private_Operation(const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
545 m_public(rsa.public_data()),
546 m_private(rsa.private_data()),
547 m_blinder(
548 m_public->reducer_mod_n(),
549 rng,
550 [this](const BigInt& k) { return m_public->public_op(k); },
551 [this](const BigInt& k) { return inverse_mod_rsa_public_modulus(k, m_public->get_n()); }),
552 m_blinding_bits(64),
553 m_max_d1_bits(m_private->p_bits() + m_blinding_bits),
554 m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {}
555
556 void raw_op(std::span<uint8_t> out, std::span<const uint8_t> input) {
557 if(input.size() > public_modulus_bytes()) {
558 throw Decoding_Error("RSA input is too long for this key");
559 }
560 const BigInt input_bn(input.data(), input.size());
561 if(input_bn.is_zero() || input_bn >= m_public->get_n()) {
562 throw Decoding_Error("RSA input is not in the valid range");
563 }
564 // TODO: This should be a function on blinder
565 // BigInt Blinder::run_blinded_function(std::function<BigInt, BigInt> fn, const BigInt& input);
566
567 const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
568 BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
569 BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(), "output size check");
570 recovered.serialize_to(out);
571 }
572
573 private:
574 BigInt rsa_private_op(const BigInt& m) const {
575 /*
576 All normal implementations generate p/q of the same bitlength,
577 so this should rarely occur in practice
578 */
579 if(m_private->primes_imbalanced()) {
580 return monty_exp(m_public->monty_n(), m, m_private->get_d(), m_public->get_n().bits()).value();
581 }
582
583 static constexpr size_t powm_window = 4;
584
585 // Compute this in main thread to avoid racing on the rng
586 const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
587
588#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
589 #define BOTAN_RSA_USE_ASYNC
590#endif
591
592#if defined(BOTAN_RSA_USE_ASYNC)
593 /*
594 * Precompute m.sig_words in the main thread before calling async. Otherwise
595 * the two threads race (during Barrett_Reduction::reduce) and while the output
596 * is correct in both threads, helgrind warns.
597 */
598 m.sig_words();
599
600 auto future_j1 = Thread_Pool::global_instance().run([this, &m, &d1_mask]() {
601#endif
602 const BigInt masked_d1 = m_private->blinded_d1(d1_mask);
603 auto powm_d1_p = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_p(), m), powm_window);
604 auto j1 = monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
605
606#if defined(BOTAN_RSA_USE_ASYNC)
607 return j1;
608 });
609#endif
610
611 const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
612 const BigInt masked_d2 = m_private->blinded_d2(d2_mask);
613 auto powm_d2_q = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_q(), m), powm_window);
614 const auto j2 = monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits).value();
615
616#if defined(BOTAN_RSA_USE_ASYNC)
617 auto j1 = future_j1.get();
618#endif
619
620 // Reduce j2 modulo p
621 const auto j2_p = Montgomery_Int::from_wide_int(m_private->monty_p(), j2);
622
623 return crt_recombine(j1, j2_p, j2, m_private->get_c_monty(), m_private->get_p(), m_private->get_q());
624 }
625
626 std::shared_ptr<const RSA_Public_Data> m_public;
627 std::shared_ptr<const RSA_Private_Data> m_private;
628
629 // XXX could the blinder starting pair be shared?
630 Blinder m_blinder;
631 const size_t m_blinding_bits;
632 const size_t m_max_d1_bits;
633 const size_t m_max_d2_bits;
634};
635
636class RSA_Signature_Operation final : public PK_Ops::Signature,
637 private RSA_Private_Operation {
638 public:
639 void update(std::span<const uint8_t> msg) override { m_padding->update(msg.data(), msg.size()); }
640
641 std::vector<uint8_t> sign(RandomNumberGenerator& rng) override {
642 const size_t max_input_bits = public_modulus_bits() - 1;
643 const auto msg = m_padding->raw_data();
644 const auto padded = m_padding->encoding_of(msg, max_input_bits, rng);
645
646 std::vector<uint8_t> out(public_modulus_bytes());
647 raw_op(out, padded);
648 return out;
649 }
650
651 size_t signature_length() const override { return public_modulus_bytes(); }
652
653 AlgorithmIdentifier algorithm_identifier() const override;
654
655 std::string hash_function() const override { return m_padding->hash_function(); }
656
657 RSA_Signature_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
658 RSA_Private_Operation(rsa, rng), m_padding(SignaturePaddingScheme::create_or_throw(padding)) {}
659
660 private:
661 std::unique_ptr<SignaturePaddingScheme> m_padding;
662};
663
664AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier() const {
665 const std::string padding_name = m_padding->name();
666
667 try {
668 const std::string full_name = "RSA/" + padding_name;
669 const OID oid = OID::from_string(full_name);
670 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM);
671 } catch(Lookup_Error&) {}
672
673 if(padding_name.starts_with("PSS(")) {
674 auto parameters = PSS_Params::from_padding_name(m_padding->name()).serialize();
675 return AlgorithmIdentifier("RSA/PSS", parameters);
676 }
677
678 throw Invalid_Argument(fmt("Signatures using RSA/{} are not supported", padding_name));
679}
680
681class RSA_Decryption_Operation final : public PK_Ops::Decryption_with_Padding,
682 private RSA_Private_Operation {
683 public:
684 RSA_Decryption_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
685 PK_Ops::Decryption_with_Padding(padding), RSA_Private_Operation(rsa, rng) {}
686
687 size_t plaintext_length(size_t /*ctext_len*/) const override { return public_modulus_bytes(); }
688
689 secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input) override {
690 secure_vector<uint8_t> out(public_modulus_bytes());
691 raw_op(out, input);
692 return out;
693 }
694};
695
696class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KDF,
697 private RSA_Private_Operation {
698 public:
699 RSA_KEM_Decryption_Operation(const RSA_PrivateKey& key, std::string_view kdf, RandomNumberGenerator& rng) :
700 PK_Ops::KEM_Decryption_with_KDF(kdf), RSA_Private_Operation(key, rng) {}
701
702 size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
703
704 size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
705
706 void raw_kem_decrypt(std::span<uint8_t> out_shared_key, std::span<const uint8_t> encapsulated_key) override {
707 raw_op(out_shared_key, encapsulated_key);
708 }
709};
710
711/**
712* RSA public (encrypt/verify) operation
713*/
714class RSA_Public_Operation {
715 public:
716 explicit RSA_Public_Operation(const RSA_PublicKey& rsa) : m_public(rsa.public_data()) {}
717
718 size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
719
720 protected:
721 BigInt public_op(const BigInt& m) const {
722 if(m >= m_public->get_n()) {
723 throw Decoding_Error("RSA public op - input is too large");
724 }
725
726 return m_public->public_op(m);
727 }
728
729 size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
730
731 const BigInt& get_n() const { return m_public->get_n(); }
732
733 private:
734 std::shared_ptr<const RSA_Public_Data> m_public;
735};
736
737class RSA_Encryption_Operation final : public PK_Ops::Encryption_with_Padding,
738 private RSA_Public_Operation {
739 public:
740 RSA_Encryption_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
741 PK_Ops::Encryption_with_Padding(padding), RSA_Public_Operation(rsa) {}
742
743 size_t ciphertext_length(size_t /*ptext_len*/) const override { return public_modulus_bytes(); }
744
745 size_t max_ptext_input_bits() const override { return public_modulus_bits() - 1; }
746
747 std::vector<uint8_t> raw_encrypt(std::span<const uint8_t> input, RandomNumberGenerator& /*rng*/) override {
748 const BigInt input_bn(input);
749 return public_op(input_bn).serialize(public_modulus_bytes());
750 }
751};
752
753class RSA_Verify_Operation final : public PK_Ops::Verification,
754 private RSA_Public_Operation {
755 public:
756 void update(std::span<const uint8_t> msg) override { m_padding->update(msg.data(), msg.size()); }
757
758 bool is_valid_signature(std::span<const uint8_t> sig) override {
759 const auto msg = m_padding->raw_data();
760 const auto message_repr = recover_message_repr(sig.data(), sig.size());
761 return m_padding->verify(message_repr, msg, public_modulus_bits() - 1);
762 }
763
764 RSA_Verify_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
765 RSA_Public_Operation(rsa), m_padding(SignaturePaddingScheme::create_or_throw(padding)) {}
766
767 std::string hash_function() const override { return m_padding->hash_function(); }
768
769 private:
770 std::vector<uint8_t> recover_message_repr(const uint8_t input[], size_t input_len) {
771 if(input_len > public_modulus_bytes()) {
772 throw Decoding_Error("RSA signature too large to be valid for this key");
773 }
774 const BigInt input_bn(input, input_len);
775 return public_op(input_bn).serialize();
776 }
777
778 std::unique_ptr<SignaturePaddingScheme> m_padding;
779};
780
781class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KDF,
782 private RSA_Public_Operation {
783 public:
784 RSA_KEM_Encryption_Operation(const RSA_PublicKey& key, std::string_view kdf) :
785 PK_Ops::KEM_Encryption_with_KDF(kdf), RSA_Public_Operation(key) {}
786
787 private:
788 size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
789
790 size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
791
792 void raw_kem_encrypt(std::span<uint8_t> out_encapsulated_key,
793 std::span<uint8_t> raw_shared_key,
794 RandomNumberGenerator& rng) override {
795 const BigInt r = BigInt::random_integer(rng, BigInt::one(), get_n());
796 const BigInt c = public_op(r);
797
798 c.serialize_to(out_encapsulated_key);
799 r.serialize_to(raw_shared_key);
800 }
801};
802
803} // namespace
804
805std::unique_ptr<PK_Ops::Encryption> RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
806 std::string_view params,
807 std::string_view provider) const {
808 if(provider == "base" || provider.empty()) {
809 return std::make_unique<RSA_Encryption_Operation>(*this, params);
810 }
811 throw Provider_Not_Found(algo_name(), provider);
812}
813
814std::unique_ptr<PK_Ops::KEM_Encryption> RSA_PublicKey::create_kem_encryption_op(std::string_view params,
815 std::string_view provider) const {
816 if(provider == "base" || provider.empty()) {
817 return std::make_unique<RSA_KEM_Encryption_Operation>(*this, params);
818 }
819 throw Provider_Not_Found(algo_name(), provider);
820}
821
822std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_verification_op(std::string_view params,
823 std::string_view provider) const {
824 if(provider == "base" || provider.empty()) {
825 return std::make_unique<RSA_Verify_Operation>(*this, params);
826 }
827
828 throw Provider_Not_Found(algo_name(), provider);
829}
830
831namespace {
832
833std::string parse_rsa_signature_algorithm(const AlgorithmIdentifier& alg_id) {
834 const auto sig_info = split_on(alg_id.oid().to_formatted_string(), '/');
835
836 if(sig_info.empty() || sig_info.size() != 2 || sig_info[0] != "RSA") {
837 throw Decoding_Error("Unknown AlgorithmIdentifier for RSA X.509 signatures");
838 }
839
840 std::string padding = sig_info[1];
841
842 if(padding != "PSS") {
843 if(!alg_id.parameters_are_null_or_empty()) {
844 throw Decoding_Error("Non-PSS RSA signature algorithm OID has unexpected parameters");
845 }
846 }
847
848 if(padding == "PSS") {
849 // "MUST contain RSASSA-PSS-params"
850 if(alg_id.parameters().empty()) {
851 throw Decoding_Error("PSS params must be provided");
852 }
853
854 const PSS_Params pss_params(alg_id.parameters());
855
856 // hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
857 // We also support SHA-3 (is also supported by e.g. OpenSSL and bouncycastle)
858 const std::string hash_algo = pss_params.hash_function();
859 if(hash_algo != "SHA-1" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384" &&
860 hash_algo != "SHA-512" && hash_algo != "SHA-3(224)" && hash_algo != "SHA-3(256)" &&
861 hash_algo != "SHA-3(384)" && hash_algo != "SHA-3(512)") {
862 throw Decoding_Error("Unacceptable hash for PSS signatures");
863 }
864
865 if(pss_params.mgf_function() != "MGF1") {
866 throw Decoding_Error("Unacceptable MGF for PSS signatures");
867 }
868
869 // For MGF1, it is strongly RECOMMENDED that the underlying hash
870 // function be the same as the one identified by hashAlgorithm
871 if(pss_params.hash_algid() != pss_params.mgf_hash_algid()) {
872 throw Decoding_Error("Unacceptable MGF hash for PSS signatures");
873 }
874
875 if(pss_params.trailer_field() != 1) {
876 throw Decoding_Error("Unacceptable trailer field for PSS signatures");
877 }
878
879 padding += fmt("({},MGF1,{})", hash_algo, pss_params.salt_length());
880 }
881
882 return padding;
883}
884
885} // namespace
886
887std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_x509_verification_op(const AlgorithmIdentifier& alg_id,
888 std::string_view provider) const {
889 if(provider == "base" || provider.empty()) {
890 return std::make_unique<RSA_Verify_Operation>(*this, parse_rsa_signature_algorithm(alg_id));
891 }
892
893 throw Provider_Not_Found(algo_name(), provider);
894}
895
896std::unique_ptr<PK_Ops::Decryption> RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
897 std::string_view params,
898 std::string_view provider) const {
899 if(provider == "base" || provider.empty()) {
900 return std::make_unique<RSA_Decryption_Operation>(*this, params, rng);
901 }
902
903 throw Provider_Not_Found(algo_name(), provider);
904}
905
906std::unique_ptr<PK_Ops::KEM_Decryption> RSA_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
907 std::string_view params,
908 std::string_view provider) const {
909 if(provider == "base" || provider.empty()) {
910 return std::make_unique<RSA_KEM_Decryption_Operation>(*this, params, rng);
911 }
912
913 throw Provider_Not_Found(algo_name(), provider);
914}
915
916std::unique_ptr<PK_Ops::Signature> RSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
917 std::string_view params,
918 std::string_view provider) const {
919 if(provider == "base" || provider.empty()) {
920 return std::make_unique<RSA_Signature_Operation>(*this, params, rng);
921 }
922
923 throw Provider_Not_Found(algo_name(), provider);
924}
925
926} // 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:421
const std::vector< uint8_t > & parameters() const
Definition asn1_obj.h:409
const OID & oid() const
Definition asn1_obj.h:407
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:35
BER_Decoder & decode(bool &out)
Definition ber_dec.h:220
BER_Decoder & verify_end()
Definition ber_dec.cpp:381
BER_Decoder & end_cons()
Definition ber_dec.cpp:524
BER_Decoder start_sequence()
Definition ber_dec.h:160
BER_Decoder & decode_and_check(const T &expected, std::string_view error_msg)
Definition ber_dec.h:314
size_t sig_words() const
Definition bigint.h:648
size_t size() const
Definition bigint.h:642
static BigInt _from_words(secure_vector< word > &words)
Definition bigint.h:988
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:969
bool is_zero() const
Definition bigint.h:484
secure_vector< uint8_t > get_contents()
Definition der_enc.cpp:134
DER_Encoder & start_sequence()
Definition der_enc.h:67
DER_Encoder & end_cons()
Definition der_enc.cpp:173
DER_Encoder & encode(bool b)
Definition der_enc.cpp:245
static Montgomery_Int from_wide_int(const Montgomery_Params &params, const BigInt &x)
Definition monty.cpp:208
const secure_vector< word > & repr() const
Definition monty.h:143
BigInt value() const
Definition monty.cpp:246
std::string to_formatted_string() const
Definition asn1_oid.cpp:139
virtual void update(std::span< const uint8_t > input)=0
const BigInt & get_q() const
Definition rsa.cpp:243
const BigInt & get_int_field(std::string_view field) const override
Definition rsa.cpp:403
std::shared_ptr< const RSA_Private_Data > private_data() const
Definition rsa.cpp:219
std::unique_ptr< PK_Ops::Decryption > create_decryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:896
const BigInt & get_c() const
Definition rsa.cpp:251
std::unique_ptr< PK_Ops::Signature > create_signature_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:916
RSA_PrivateKey(const AlgorithmIdentifier &alg_id, std::span< const uint8_t > key_bits)
Definition rsa.cpp:274
const BigInt & get_p() const
Definition rsa.cpp:239
const BigInt & get_d2() const
Definition rsa.cpp:259
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition rsa.cpp:428
const BigInt & get_d() const
Definition rsa.cpp:247
secure_vector< uint8_t > private_key_bits() const override
Definition rsa.cpp:223
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:906
std::unique_ptr< Public_Key > public_key() const override
Definition rsa.cpp:421
const BigInt & get_d1() const
Definition rsa.cpp:255
std::unique_ptr< PK_Ops::Encryption > create_encryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:805
void init(BigInt &&n, BigInt &&e)
Definition rsa.cpp:156
size_t key_length() const override
Definition rsa.cpp:185
std::unique_ptr< PK_Ops::Verification > create_verification_op(std::string_view params, std::string_view provider) const override
Definition rsa.cpp:822
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:887
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:212
const BigInt & get_n() const
Definition rsa.cpp:148
size_t estimated_strength() const override
Definition rsa.cpp:189
std::unique_ptr< PK_Ops::KEM_Encryption > create_kem_encryption_op(std::string_view params, std::string_view provider) const override
Definition rsa.cpp:814
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:197
AlgorithmIdentifier algorithm_identifier() const override
Definition rsa.cpp:193
std::vector< uint8_t > public_key_bits() const override
Definition rsa.cpp:201
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:174
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:110
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:192
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:228
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:68
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
Definition types.h:119
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