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