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