Botan 3.7.1
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/reducer.h>
15#include <botan/internal/blinding.h>
16#include <botan/internal/divide.h>
17#include <botan/internal/emsa.h>
18#include <botan/internal/fmt.h>
19#include <botan/internal/keypair.h>
20#include <botan/internal/mod_inv.h>
21#include <botan/internal/monty.h>
22#include <botan/internal/monty_exp.h>
23#include <botan/internal/parsing.h>
24#include <botan/internal/pk_ops_impl.h>
25#include <botan/internal/workfactor.h>
26
27#if defined(BOTAN_HAS_THREAD_UTILS)
28 #include <botan/internal/thread_pool.h>
29#endif
30
31namespace Botan {
32
33class RSA_Public_Data final {
34 public:
35 RSA_Public_Data(BigInt&& n, BigInt&& e) :
36 m_n(std::move(n)),
37 m_e(std::move(e)),
38 m_mod_n(Modular_Reducer::for_public_modulus(m_n)),
39 m_monty_n(std::make_shared<Montgomery_Params>(m_n, m_mod_n)),
40 m_public_modulus_bits(m_n.bits()),
41 m_public_modulus_bytes(m_n.bytes()) {}
42
43 BigInt public_op(const BigInt& m) const {
44 const size_t powm_window = 1;
45 auto powm_m_n = monty_precompute(m_monty_n, m, powm_window, false);
46 return monty_execute_vartime(*powm_m_n, m_e).value();
47 }
48
49 const BigInt& get_n() const { return m_n; }
50
51 const BigInt& get_e() const { return m_e; }
52
53 size_t public_modulus_bits() const { return m_public_modulus_bits; }
54
55 size_t public_modulus_bytes() const { return m_public_modulus_bytes; }
56
57 const std::shared_ptr<const Montgomery_Params>& monty_n() const { return m_monty_n; }
58
59 const Modular_Reducer& reducer_mod_n() const { return m_mod_n; }
60
61 private:
62 BigInt m_n;
63 BigInt m_e;
64 Modular_Reducer m_mod_n;
65 std::shared_ptr<const Montgomery_Params> m_monty_n;
66 size_t m_public_modulus_bits;
67 size_t m_public_modulus_bytes;
68};
69
70class RSA_Private_Data final {
71 public:
72 RSA_Private_Data(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) :
73 m_d(std::move(d)),
74 m_p(std::move(p)),
75 m_q(std::move(q)),
76 m_d1(std::move(d1)),
77 m_d2(std::move(d2)),
78 m_c(std::move(c)),
79 m_monty_p(std::make_shared<Montgomery_Params>(m_p)),
80 m_monty_q(std::make_shared<Montgomery_Params>(m_q)),
81 m_c_monty(m_monty_p, m_c),
82 m_p_bits(m_p.bits()),
83 m_q_bits(m_q.bits()) {}
84
85 const BigInt& get_d() const { return m_d; }
86
87 const BigInt& get_p() const { return m_p; }
88
89 const BigInt& get_q() const { return m_q; }
90
91 const BigInt& get_d1() const { return m_d1; }
92
93 const BigInt& get_d2() const { return m_d2; }
94
95 const BigInt& get_c() const { return m_c; }
96
97 const Montgomery_Int& get_c_monty() const { return m_c_monty; }
98
99 const std::shared_ptr<const Montgomery_Params>& monty_p() const { return m_monty_p; }
100
101 const std::shared_ptr<const Montgomery_Params>& monty_q() const { return m_monty_q; }
102
103 size_t p_bits() const { return m_p_bits; }
104
105 size_t q_bits() const { return m_q_bits; }
106
107 bool primes_imbalanced() const { return p_bits() != q_bits(); }
108
109 private:
110 BigInt m_d;
111 BigInt m_p;
112 BigInt m_q;
113 BigInt m_d1;
114 BigInt m_d2;
115 BigInt m_c;
116
117 std::shared_ptr<const Montgomery_Params> m_monty_p;
118 std::shared_ptr<const Montgomery_Params> m_monty_q;
119 Montgomery_Int m_c_monty;
120 size_t m_p_bits;
121 size_t m_q_bits;
122};
123
124std::shared_ptr<const RSA_Public_Data> RSA_PublicKey::public_data() const {
125 return m_public;
126}
127
128const BigInt& RSA_PublicKey::get_int_field(std::string_view field) const {
129 if(field == "n") {
130 return m_public->get_n();
131 } else if(field == "e") {
132 return m_public->get_e();
133 } else {
134 return Public_Key::get_int_field(field);
135 }
136}
137
138std::unique_ptr<Private_Key> RSA_PublicKey::generate_another(RandomNumberGenerator& rng) const {
139 return std::make_unique<RSA_PrivateKey>(rng, m_public->public_modulus_bits(), m_public->get_e().to_u32bit());
140}
141
143 return m_public->get_n();
144}
145
147 return m_public->get_e();
148}
149
151 if(n.is_negative() || n.is_even() || n.bits() < 5 /* n >= 3*5 */ || e.is_negative() || e.is_even()) {
152 throw Decoding_Error("Invalid RSA public key parameters");
153 }
154 m_public = std::make_shared<RSA_Public_Data>(std::move(n), std::move(e));
155}
156
157RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
158 BigInt n, e;
159 BER_Decoder(key_bits).start_sequence().decode(n).decode(e).end_cons();
160
161 init(std::move(n), std::move(e));
162}
163
168
169RSA_PublicKey::RSA_PublicKey(const BigInt& modulus, const BigInt& exponent) {
170 BigInt n = modulus;
171 BigInt e = exponent;
172 init(std::move(n), std::move(e));
173}
174
176 return m_public->public_modulus_bits();
177}
178
182
186
187std::vector<uint8_t> RSA_PublicKey::raw_public_key_bits() const {
188 throw Not_Implemented("an RSA public key does not provide a raw binary representation.");
189}
190
191std::vector<uint8_t> RSA_PublicKey::public_key_bits() const {
192 std::vector<uint8_t> output;
193 DER_Encoder der(output);
195
196 return output;
197}
198
199/*
200* Check RSA Public Parameters
201*/
202bool RSA_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*strong*/) const {
203 if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
204 return false;
205 }
206 return true;
207}
208
209std::shared_ptr<const RSA_Private_Data> RSA_PrivateKey::private_data() const {
210 return m_private;
211}
212
214 return DER_Encoder()
216 .encode(static_cast<size_t>(0))
217 .encode(get_n())
218 .encode(get_e())
219 .encode(get_d())
220 .encode(get_p())
221 .encode(get_q())
222 .encode(get_d1())
223 .encode(get_d2())
224 .encode(get_c())
225 .end_cons()
226 .get_contents();
227}
228
230 return m_private->get_p();
231}
232
234 return m_private->get_q();
235}
236
238 return m_private->get_d();
239}
240
242 return m_private->get_c();
243}
244
246 return m_private->get_d1();
247}
248
250 return m_private->get_d2();
251}
252
253void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigInt&& d2, BigInt&& c) {
254 m_private = std::make_shared<RSA_Private_Data>(
255 std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
256}
257
258RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span<const uint8_t> key_bits) {
259 BigInt n, e, d, p, q, d1, d2, c;
260
261 BER_Decoder(key_bits)
263 .decode_and_check<size_t>(0, "Unknown PKCS #1 key format version")
264 .decode(n)
265 .decode(e)
266 .decode(d)
267 .decode(p)
268 .decode(q)
269 .decode(d1)
270 .decode(d2)
271 .decode(c)
272 .end_cons();
273
274 RSA_PublicKey::init(std::move(n), std::move(e));
275
276 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
277}
278
280 const BigInt& prime1, const BigInt& prime2, const BigInt& exp, const BigInt& d_exp, const BigInt& mod) {
281 BigInt p = prime1;
282 BigInt q = prime2;
283 BigInt n = mod;
284 if(n.is_zero()) {
285 n = p * q;
286 }
287
288 BigInt e = exp;
289
290 BigInt d = d_exp;
291
292 const BigInt p_minus_1 = p - 1;
293 const BigInt q_minus_1 = q - 1;
294
295 if(d.is_zero()) {
296 const BigInt phi_n = lcm(p_minus_1, q_minus_1);
297 d = compute_rsa_secret_exponent(e, phi_n, p, q);
298 }
299
300 BigInt d1 = ct_modulo(d, p_minus_1);
301 BigInt d2 = ct_modulo(d, q_minus_1);
303
304 RSA_PublicKey::init(std::move(n), std::move(e));
305
306 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
307}
308
309/*
310* Create a RSA private key
311*/
313 if(bits < 1024) {
314 throw Invalid_Argument(fmt("Cannot create an RSA key only {} bits long", bits));
315 }
316
317 if(exp < 3 || exp % 2 == 0) {
318 throw Invalid_Argument("Invalid RSA encryption exponent");
319 }
320
321 const size_t p_bits = (bits + 1) / 2;
322 const size_t q_bits = bits - p_bits;
323
324 BigInt p, q, n;
325 BigInt e = BigInt::from_u64(exp);
326
327 for(size_t attempt = 0;; ++attempt) {
328 if(attempt > 10) {
329 throw Internal_Error("RNG failure during RSA key generation");
330 }
331
332 // TODO could generate primes in thread pool
333 p = generate_rsa_prime(rng, rng, p_bits, e);
334 q = generate_rsa_prime(rng, rng, q_bits, e);
335
336 const BigInt diff = p - q;
337 if(diff.bits() < (bits / 2) - 100) {
338 continue;
339 }
340
341 n = p * q;
342
343 if(n.bits() != bits) {
344 continue;
345 }
346
347 break;
348 }
349
350 const BigInt p_minus_1 = p - 1;
351 const BigInt q_minus_1 = q - 1;
352
353 const BigInt phi_n = lcm(p_minus_1, q_minus_1);
354 // This is guaranteed because p,q == 3 mod 4
356
357 BigInt d = compute_rsa_secret_exponent(e, phi_n, p, q);
358 BigInt d1 = ct_modulo(d, p_minus_1);
359 BigInt d2 = ct_modulo(d, q_minus_1);
361
362 RSA_PublicKey::init(std::move(n), std::move(e));
363
364 RSA_PrivateKey::init(std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c));
365}
366
367const BigInt& RSA_PrivateKey::get_int_field(std::string_view field) const {
368 if(field == "p") {
369 return m_private->get_p();
370 } else if(field == "q") {
371 return m_private->get_q();
372 } else if(field == "d") {
373 return m_private->get_d();
374 } else if(field == "c") {
375 return m_private->get_c();
376 } else if(field == "d1") {
377 return m_private->get_d1();
378 } else if(field == "d2") {
379 return m_private->get_d2();
380 } else {
381 return RSA_PublicKey::get_int_field(field);
382 }
383}
384
385std::unique_ptr<Public_Key> RSA_PrivateKey::public_key() const {
386 return std::make_unique<RSA_PublicKey>(get_n(), get_e());
387}
388
389/*
390* Check Private RSA Parameters
391*/
393 if(get_n() < 35 || get_n().is_even() || get_e() < 3 || get_e().is_even()) {
394 return false;
395 }
396
397 if(get_d() < 2 || get_p() < 3 || get_q() < 3) {
398 return false;
399 }
400
401 if(get_p() * get_q() != get_n()) {
402 return false;
403 }
404
405 if(get_p() == get_q()) {
406 return false;
407 }
408
409 if(get_d1() != ct_modulo(get_d(), get_p() - 1)) {
410 return false;
411 }
412 if(get_d2() != ct_modulo(get_d(), get_q() - 1)) {
413 return false;
414 }
416 return false;
417 }
418
419 const size_t prob = (strong) ? 128 : 12;
420
421 if(!is_prime(get_p(), rng, prob)) {
422 return false;
423 }
424 if(!is_prime(get_q(), rng, prob)) {
425 return false;
426 }
427
428 if(strong) {
429 if(ct_modulo(get_e() * get_d(), lcm(get_p() - 1, get_q() - 1)) != 1) {
430 return false;
431 }
432
433#if defined(BOTAN_HAS_PSS) && defined(BOTAN_HAS_SHA_256)
434 const std::string padding = "PSS(SHA-256)";
435#else
436 const std::string padding = "Raw";
437#endif
438
439 return KeyPair::signature_consistency_check(rng, *this, padding);
440 }
441
442 return true;
443}
444
445namespace {
446
447/**
448* RSA private (decrypt/sign) operation
449*/
450class RSA_Private_Operation {
451 protected:
452 size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
453
454 size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
455
456 explicit RSA_Private_Operation(const RSA_PrivateKey& rsa, RandomNumberGenerator& rng) :
457 m_public(rsa.public_data()),
458 m_private(rsa.private_data()),
459 m_blinder(
460 m_public->reducer_mod_n(),
461 rng,
462 [this](const BigInt& k) { return m_public->public_op(k); },
463 [this](const BigInt& k) { return inverse_mod_rsa_public_modulus(k, m_public->get_n()); }),
464 m_blinding_bits(64),
465 m_max_d1_bits(m_private->p_bits() + m_blinding_bits),
466 m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {}
467
468 void raw_op(std::span<uint8_t> out, std::span<const uint8_t> input) {
469 if(input.size() > public_modulus_bytes()) {
470 throw Decoding_Error("RSA input is too long for this key");
471 }
472 const BigInt input_bn(input.data(), input.size());
473 if(input_bn >= m_public->get_n()) {
474 throw Decoding_Error("RSA input is too large for this key");
475 }
476 // TODO: This should be a function on blinder
477 // BigInt Blinder::run_blinded_function(std::function<BigInt, BigInt> fn, const BigInt& input);
478
479 const BigInt recovered = m_blinder.unblind(rsa_private_op(m_blinder.blind(input_bn)));
480 BOTAN_ASSERT(input_bn == m_public->public_op(recovered), "RSA consistency check");
481 BOTAN_ASSERT(m_public->public_modulus_bytes() == out.size(), "output size check");
482 recovered.serialize_to(out);
483 }
484
485 private:
486 BigInt rsa_private_op(const BigInt& m) const {
487 /*
488 All normal implementations generate p/q of the same bitlength,
489 so this should rarely occur in practice
490 */
491 if(m_private->primes_imbalanced()) {
492 return monty_exp(m_public->monty_n(), m, m_private->get_d(), m_public->get_n().bits()).value();
493 }
494
495 static constexpr size_t powm_window = 4;
496
497 // Compute this in main thread to avoid racing on the rng
498 const BigInt d1_mask(m_blinder.rng(), m_blinding_bits);
499
500#if defined(BOTAN_HAS_THREAD_UTILS) && !defined(BOTAN_HAS_VALGRIND)
501 #define BOTAN_RSA_USE_ASYNC
502#endif
503
504#if defined(BOTAN_RSA_USE_ASYNC)
505 /*
506 * Precompute m.sig_words in the main thread before calling async. Otherwise
507 * the two threads race (during Modular_Reducer::reduce) and while the output
508 * is correct in both threads, helgrind warns.
509 */
510 m.sig_words();
511
512 auto future_j1 = Thread_Pool::global_instance().run([this, &m, &d1_mask]() {
513#endif
514 const BigInt masked_d1 = m_private->get_d1() + (d1_mask * (m_private->get_p() - 1));
515 auto powm_d1_p = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_p(), m), powm_window);
516 auto j1 = monty_execute(*powm_d1_p, masked_d1, m_max_d1_bits);
517
518#if defined(BOTAN_RSA_USE_ASYNC)
519 return j1;
520 });
521#endif
522
523 const BigInt d2_mask(m_blinder.rng(), m_blinding_bits);
524 const BigInt masked_d2 = m_private->get_d2() + (d2_mask * (m_private->get_q() - 1));
525 auto powm_d2_q = monty_precompute(Montgomery_Int::from_wide_int(m_private->monty_q(), m), powm_window);
526 const auto j2 = monty_execute(*powm_d2_q, masked_d2, m_max_d2_bits).value();
527
528#if defined(BOTAN_RSA_USE_ASYNC)
529 auto j1 = future_j1.get();
530#endif
531
532 /*
533 * To recover the final value from the CRT representation (j1,j2)
534 * we use Garner's algorithm:
535 * c = q^-1 mod p (this is precomputed)
536 * h = c*(j1-j2) mod p
537 * m = j2 + h*q
538 */
539
540 const auto j2_p = Montgomery_Int::from_wide_int(m_private->monty_p(), j2);
541
542 /**
543 * This doesn't quite match up with the "Smooth-CRT" proposal; there we
544 * would multiply by c * R2 so would have the effect of both multiplying
545 * by c and immediately converting from Montgomery to standard form.
546 */
547 j1 = (j1 - j2_p) * m_private->get_c_monty();
548 return j1.value() * m_private->get_q() + j2;
549 }
550
551 std::shared_ptr<const RSA_Public_Data> m_public;
552 std::shared_ptr<const RSA_Private_Data> m_private;
553
554 // XXX could the blinder starting pair be shared?
555 Blinder m_blinder;
556 const size_t m_blinding_bits;
557 const size_t m_max_d1_bits;
558 const size_t m_max_d2_bits;
559};
560
561class RSA_Signature_Operation final : public PK_Ops::Signature,
562 private RSA_Private_Operation {
563 public:
564 void update(std::span<const uint8_t> msg) override { m_emsa->update(msg.data(), msg.size()); }
565
566 std::vector<uint8_t> sign(RandomNumberGenerator& rng) override {
567 const size_t max_input_bits = public_modulus_bits() - 1;
568 const auto msg = m_emsa->raw_data();
569 const auto padded = m_emsa->encoding_of(msg, max_input_bits, rng);
570
571 std::vector<uint8_t> out(public_modulus_bytes());
572 raw_op(out, padded);
573 return out;
574 }
575
576 size_t signature_length() const override { return public_modulus_bytes(); }
577
578 AlgorithmIdentifier algorithm_identifier() const override;
579
580 std::string hash_function() const override { return m_emsa->hash_function(); }
581
582 RSA_Signature_Operation(const RSA_PrivateKey& rsa, std::string_view padding, RandomNumberGenerator& rng) :
583 RSA_Private_Operation(rsa, rng), m_emsa(EMSA::create_or_throw(padding)) {}
584
585 private:
586 std::unique_ptr<EMSA> m_emsa;
587};
588
589AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier() const {
590 const std::string emsa_name = m_emsa->name();
591
592 try {
593 const std::string full_name = "RSA/" + emsa_name;
594 const OID oid = OID::from_string(full_name);
595 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM);
596 } catch(Lookup_Error&) {}
597
598 if(emsa_name.starts_with("PSS(")) {
599 auto parameters = PSS_Params::from_emsa_name(m_emsa->name()).serialize();
600 return AlgorithmIdentifier("RSA/PSS", parameters);
601 }
602
603 throw Invalid_Argument(fmt("Signatures using RSA/{} are not supported", emsa_name));
604}
605
606class RSA_Decryption_Operation final : public PK_Ops::Decryption_with_EME,
607 private RSA_Private_Operation {
608 public:
609 RSA_Decryption_Operation(const RSA_PrivateKey& rsa, std::string_view eme, RandomNumberGenerator& rng) :
610 PK_Ops::Decryption_with_EME(eme), RSA_Private_Operation(rsa, rng) {}
611
612 size_t plaintext_length(size_t /*ctext_len*/) const override { return public_modulus_bytes(); }
613
614 secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input) override {
615 secure_vector<uint8_t> out(public_modulus_bytes());
616 raw_op(out, input);
617 return out;
618 }
619};
620
621class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KDF,
622 private RSA_Private_Operation {
623 public:
624 RSA_KEM_Decryption_Operation(const RSA_PrivateKey& key, std::string_view kdf, RandomNumberGenerator& rng) :
625 PK_Ops::KEM_Decryption_with_KDF(kdf), RSA_Private_Operation(key, rng) {}
626
627 size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
628
629 size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
630
631 void raw_kem_decrypt(std::span<uint8_t> out_shared_key, std::span<const uint8_t> encapsulated_key) override {
632 raw_op(out_shared_key, encapsulated_key);
633 }
634};
635
636/**
637* RSA public (encrypt/verify) operation
638*/
639class RSA_Public_Operation {
640 public:
641 explicit RSA_Public_Operation(const RSA_PublicKey& rsa) : m_public(rsa.public_data()) {}
642
643 size_t public_modulus_bits() const { return m_public->public_modulus_bits(); }
644
645 protected:
646 BigInt public_op(const BigInt& m) const {
647 if(m >= m_public->get_n()) {
648 throw Decoding_Error("RSA public op - input is too large");
649 }
650
651 return m_public->public_op(m);
652 }
653
654 size_t public_modulus_bytes() const { return m_public->public_modulus_bytes(); }
655
656 const BigInt& get_n() const { return m_public->get_n(); }
657
658 private:
659 std::shared_ptr<const RSA_Public_Data> m_public;
660};
661
662class RSA_Encryption_Operation final : public PK_Ops::Encryption_with_EME,
663 private RSA_Public_Operation {
664 public:
665 RSA_Encryption_Operation(const RSA_PublicKey& rsa, std::string_view eme) :
666 PK_Ops::Encryption_with_EME(eme), RSA_Public_Operation(rsa) {}
667
668 size_t ciphertext_length(size_t /*ptext_len*/) const override { return public_modulus_bytes(); }
669
670 size_t max_ptext_input_bits() const override { return public_modulus_bits() - 1; }
671
672 std::vector<uint8_t> raw_encrypt(std::span<const uint8_t> input, RandomNumberGenerator& /*rng*/) override {
673 BigInt input_bn(input);
674 return public_op(input_bn).serialize(public_modulus_bytes());
675 }
676};
677
678class RSA_Verify_Operation final : public PK_Ops::Verification,
679 private RSA_Public_Operation {
680 public:
681 void update(std::span<const uint8_t> msg) override { m_emsa->update(msg.data(), msg.size()); }
682
683 bool is_valid_signature(std::span<const uint8_t> sig) override {
684 const auto msg = m_emsa->raw_data();
685 const auto message_repr = recover_message_repr(sig.data(), sig.size());
686 return m_emsa->verify(message_repr, msg, public_modulus_bits() - 1);
687 }
688
689 RSA_Verify_Operation(const RSA_PublicKey& rsa, std::string_view padding) :
690 RSA_Public_Operation(rsa), m_emsa(EMSA::create_or_throw(padding)) {}
691
692 std::string hash_function() const override { return m_emsa->hash_function(); }
693
694 private:
695 std::vector<uint8_t> recover_message_repr(const uint8_t input[], size_t input_len) {
696 if(input_len > public_modulus_bytes()) {
697 throw Decoding_Error("RSA signature too large to be valid for this key");
698 }
699 BigInt input_bn(input, input_len);
700 return public_op(input_bn).serialize();
701 }
702
703 std::unique_ptr<EMSA> m_emsa;
704};
705
706class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KDF,
707 private RSA_Public_Operation {
708 public:
709 RSA_KEM_Encryption_Operation(const RSA_PublicKey& key, std::string_view kdf) :
710 PK_Ops::KEM_Encryption_with_KDF(kdf), RSA_Public_Operation(key) {}
711
712 private:
713 size_t raw_kem_shared_key_length() const override { return public_modulus_bytes(); }
714
715 size_t encapsulated_key_length() const override { return public_modulus_bytes(); }
716
717 void raw_kem_encrypt(std::span<uint8_t> out_encapsulated_key,
718 std::span<uint8_t> raw_shared_key,
719 RandomNumberGenerator& rng) override {
720 const BigInt r = BigInt::random_integer(rng, 1, get_n());
721 const BigInt c = public_op(r);
722
723 c.serialize_to(out_encapsulated_key);
724 r.serialize_to(raw_shared_key);
725 }
726};
727
728} // namespace
729
730std::unique_ptr<PK_Ops::Encryption> RSA_PublicKey::create_encryption_op(RandomNumberGenerator& /*rng*/,
731 std::string_view params,
732 std::string_view provider) const {
733 if(provider == "base" || provider.empty()) {
734 return std::make_unique<RSA_Encryption_Operation>(*this, params);
735 }
736 throw Provider_Not_Found(algo_name(), provider);
737}
738
739std::unique_ptr<PK_Ops::KEM_Encryption> RSA_PublicKey::create_kem_encryption_op(std::string_view params,
740 std::string_view provider) const {
741 if(provider == "base" || provider.empty()) {
742 return std::make_unique<RSA_KEM_Encryption_Operation>(*this, params);
743 }
744 throw Provider_Not_Found(algo_name(), provider);
745}
746
747std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_verification_op(std::string_view params,
748 std::string_view provider) const {
749 if(provider == "base" || provider.empty()) {
750 return std::make_unique<RSA_Verify_Operation>(*this, params);
751 }
752
753 throw Provider_Not_Found(algo_name(), provider);
754}
755
756namespace {
757
758std::string parse_rsa_signature_algorithm(const AlgorithmIdentifier& alg_id) {
759 const auto sig_info = split_on(alg_id.oid().to_formatted_string(), '/');
760
761 if(sig_info.empty() || sig_info.size() != 2 || sig_info[0] != "RSA") {
762 throw Decoding_Error("Unknown AlgorithmIdentifier for RSA X.509 signatures");
763 }
764
765 std::string padding = sig_info[1];
766
767 if(padding == "PSS") {
768 // "MUST contain RSASSA-PSS-params"
769 if(alg_id.parameters().empty()) {
770 throw Decoding_Error("PSS params must be provided");
771 }
772
773 PSS_Params pss_params(alg_id.parameters());
774
775 // hash_algo must be SHA1, SHA2-224, SHA2-256, SHA2-384 or SHA2-512
776 // We also support SHA-3 (is also supported by e.g. OpenSSL and bouncycastle)
777 const std::string hash_algo = pss_params.hash_function();
778 if(hash_algo != "SHA-1" && hash_algo != "SHA-224" && hash_algo != "SHA-256" && hash_algo != "SHA-384" &&
779 hash_algo != "SHA-512" && hash_algo != "SHA-3(224)" && hash_algo != "SHA-3(256)" &&
780 hash_algo != "SHA-3(384)" && hash_algo != "SHA-3(512)") {
781 throw Decoding_Error("Unacceptable hash for PSS signatures");
782 }
783
784 if(pss_params.mgf_function() != "MGF1") {
785 throw Decoding_Error("Unacceptable MGF for PSS signatures");
786 }
787
788 // For MGF1, it is strongly RECOMMENDED that the underlying hash
789 // function be the same as the one identified by hashAlgorithm
790 if(pss_params.hash_algid() != pss_params.mgf_hash_algid()) {
791 throw Decoding_Error("Unacceptable MGF hash for PSS signatures");
792 }
793
794 if(pss_params.trailer_field() != 1) {
795 throw Decoding_Error("Unacceptable trailer field for PSS signatures");
796 }
797
798 padding += fmt("({},MGF1,{})", hash_algo, pss_params.salt_length());
799 }
800
801 return padding;
802}
803
804} // namespace
805
806std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_x509_verification_op(const AlgorithmIdentifier& alg_id,
807 std::string_view provider) const {
808 if(provider == "base" || provider.empty()) {
809 return std::make_unique<RSA_Verify_Operation>(*this, parse_rsa_signature_algorithm(alg_id));
810 }
811
812 throw Provider_Not_Found(algo_name(), provider);
813}
814
815std::unique_ptr<PK_Ops::Decryption> RSA_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
816 std::string_view params,
817 std::string_view provider) const {
818 if(provider == "base" || provider.empty()) {
819 return std::make_unique<RSA_Decryption_Operation>(*this, params, rng);
820 }
821
822 throw Provider_Not_Found(algo_name(), provider);
823}
824
825std::unique_ptr<PK_Ops::KEM_Decryption> RSA_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
826 std::string_view params,
827 std::string_view provider) const {
828 if(provider == "base" || provider.empty()) {
829 return std::make_unique<RSA_KEM_Decryption_Operation>(*this, params, rng);
830 }
831
832 throw Provider_Not_Found(algo_name(), provider);
833}
834
835std::unique_ptr<PK_Ops::Signature> RSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,
836 std::string_view params,
837 std::string_view provider) const {
838 if(provider == "base" || provider.empty()) {
839 return std::make_unique<RSA_Signature_Operation>(*this, params, rng);
840 }
841
842 throw Provider_Not_Found(algo_name(), provider);
843}
844
845} // namespace Botan
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:98
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:50
const std::vector< uint8_t > & parameters() const
Definition asn1_obj.h:474
const OID & oid() const
Definition asn1_obj.h:472
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
BER_Decoder & decode(bool &out)
Definition ber_dec.h:186
BER_Decoder & end_cons()
Definition ber_dec.cpp:309
BER_Decoder start_sequence()
Definition ber_dec.h:123
BER_Decoder & decode_and_check(const T &expected, std::string_view error_msg)
Definition ber_dec.h:272
size_t bits() const
Definition bigint.cpp:295
static BigInt from_u64(uint64_t n)
Definition bigint.cpp:28
bool is_zero() const
Definition bigint.h:458
secure_vector< uint8_t > get_contents()
Definition der_enc.cpp:132
DER_Encoder & start_sequence()
Definition der_enc.h:64
DER_Encoder & end_cons()
Definition der_enc.cpp:171
DER_Encoder & encode(bool b)
Definition der_enc.cpp:250
BigInt value() const
Definition monty.cpp:335
static Montgomery_Int from_wide_int(const std::shared_ptr< const Montgomery_Params > &params, const BigInt &x)
Definition monty.cpp:262
std::string to_formatted_string() const
Definition asn1_oid.cpp:139
const BigInt & get_q() const
Definition rsa.cpp:233
const BigInt & get_int_field(std::string_view field) const override
Definition rsa.cpp:367
std::shared_ptr< const RSA_Private_Data > private_data() const
Definition rsa.cpp:209
std::unique_ptr< PK_Ops::Decryption > create_decryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:815
const BigInt & get_c() const
Definition rsa.cpp:241
std::unique_ptr< PK_Ops::Signature > create_signature_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:835
RSA_PrivateKey(const AlgorithmIdentifier &alg_id, std::span< const uint8_t > key_bits)
Definition rsa.cpp:258
const BigInt & get_p() const
Definition rsa.cpp:229
const BigInt & get_d2() const
Definition rsa.cpp:249
bool check_key(RandomNumberGenerator &rng, bool) const override
Definition rsa.cpp:392
const BigInt & get_d() const
Definition rsa.cpp:237
secure_vector< uint8_t > private_key_bits() const override
Definition rsa.cpp:213
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:825
std::unique_ptr< Public_Key > public_key() const override
Definition rsa.cpp:385
const BigInt & get_d1() const
Definition rsa.cpp:245
std::unique_ptr< PK_Ops::Encryption > create_encryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition rsa.cpp:730
void init(BigInt &&n, BigInt &&e)
Definition rsa.cpp:150
size_t key_length() const override
Definition rsa.cpp:175
std::unique_ptr< PK_Ops::Verification > create_verification_op(std::string_view params, std::string_view provider) const override
Definition rsa.cpp:747
std::unique_ptr< PK_Ops::Verification > create_x509_verification_op(const AlgorithmIdentifier &alg_id, std::string_view provider) const override
Definition rsa.cpp:806
const BigInt & get_int_field(std::string_view field) const override
Definition rsa.cpp:128
const BigInt & get_n() const
Definition rsa.cpp:142
size_t estimated_strength() const override
Definition rsa.cpp:179
std::unique_ptr< PK_Ops::KEM_Encryption > create_kem_encryption_op(std::string_view params, std::string_view provider) const override
Definition rsa.cpp:739
std::unique_ptr< Private_Key > generate_another(RandomNumberGenerator &rng) const override
Definition rsa.cpp:138
std::vector< uint8_t > raw_public_key_bits() const override
Definition rsa.cpp:187
AlgorithmIdentifier algorithm_identifier() const override
Definition rsa.cpp:183
std::vector< uint8_t > public_key_bits() const override
Definition rsa.cpp:191
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:124
const BigInt & get_e() const
Definition rsa.cpp:146
bool supports_operation(PublicKeyOperation op) const override
Definition rsa.cpp:164
bool check_key(RandomNumberGenerator &rng, bool) const override
Definition rsa.cpp:202
auto run(F &&f, Args &&... args) -> std::future< typename std::invoke_result< F, Args... >::type >
Definition thread_pool.h:66
static Thread_Pool & global_instance()
int(* init)(CTX *)
int(* update)(CTX *, const void *, CC_LONG len)
int(* final)(unsigned char *, CTX *)
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:280
PublicKeyOperation
Definition pk_keys.h:45
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:270
std::vector< std::string > split_on(std::string_view str, char delim)
Definition parsing.cpp:111
size_t low_zero_bits(const BigInt &n)
Definition numthry.cpp:167
Montgomery_Int monty_execute_vartime(const Montgomery_Exponentation_State &precomputed_state, const BigInt &k)
bool is_prime(const BigInt &n, RandomNumberGenerator &rng, size_t prob, bool is_random)
Definition numthry.cpp:355
BigInt ct_modulo(const BigInt &x, const BigInt &y)
Definition divide.cpp:181
BigInt compute_rsa_secret_exponent(const BigInt &e, const BigInt &phi_n, const BigInt &p, const BigInt &q)
Definition mod_inv.cpp:330
Montgomery_Int monty_exp(const std::shared_ptr< const Montgomery_Params > &params_p, const BigInt &g, const BigInt &k, size_t max_k_bits)
Definition monty_exp.h:48
BigInt generate_rsa_prime(RandomNumberGenerator &keygen_rng, RandomNumberGenerator &prime_test_rng, size_t bits, const BigInt &coprime, size_t prob)
Definition make_prm.cpp:211
Montgomery_Int monty_execute(const Montgomery_Exponentation_State &precomputed_state, const BigInt &k, size_t max_k_bits)
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:61
BigInt inverse_mod_rsa_public_modulus(const BigInt &x, const BigInt &n)
Definition mod_inv.cpp:295
size_t if_work_factor(size_t bits)
std::shared_ptr< const Montgomery_Exponentation_State > monty_precompute(const Montgomery_Int &g, size_t window_bits, bool const_time)