• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 13190843806

07 Feb 2025 12:50AM UTC coverage: 91.233% (+0.006%) from 91.227%
13190843806

push

github

web-flow
Merge pull request #4639 from randombit/jack/cleanup-build-h

Remove most toggles from build.h

94196 of 103248 relevant lines covered (91.23%)

11436231.99 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.53
/src/tests/test_rsa.cpp
1
/*
2
* (C) 2014,2015 Jack Lloyd
3
*
4
* Botan is released under the Simplified BSD License (see license.txt)
5
*/
6

7
#include "test_rng.h"
8
#include "tests.h"
9

10
#if defined(BOTAN_HAS_RSA)
11
   #include "test_pubkey.h"
12
   #include <botan/rsa.h>
13
   #include <botan/internal/blinding.h>
14
   #include <botan/internal/fmt.h>
15
#endif
16

17
namespace Botan_Tests {
18

19
namespace {
20

21
#if defined(BOTAN_HAS_RSA)
22

23
std::unique_ptr<Botan::Private_Key> load_rsa_private_key(const VarMap& vars) {
563✔
24
   const BigInt p = vars.get_req_bn("P");
563✔
25
   const BigInt q = vars.get_req_bn("Q");
563✔
26
   const BigInt e = vars.get_req_bn("E");
563✔
27

28
   return std::make_unique<Botan::RSA_PrivateKey>(p, q, e);
563✔
29
}
1,689✔
30

31
std::unique_ptr<Botan::Public_Key> load_rsa_public_key(const VarMap& vars) {
572✔
32
   const BigInt n = vars.get_req_bn("N");
572✔
33
   const BigInt e = vars.get_req_bn("E");
572✔
34

35
   return std::make_unique<Botan::RSA_PublicKey>(n, e);
1,144✔
36
}
1,144✔
37

38
class RSA_ES_KAT_Tests final : public PK_Encryption_Decryption_Test {
39
   public:
40
      RSA_ES_KAT_Tests() : PK_Encryption_Decryption_Test("RSA", "pubkey/rsaes.vec", "E,P,Q,Msg,Ciphertext", "Nonce") {}
2✔
41

42
      std::unique_ptr<Botan::Private_Key> load_private_key(const VarMap& vars) override {
188✔
43
         return load_rsa_private_key(vars);
188✔
44
      }
45
};
46

47
class RSA_Decryption_KAT_Tests final : public PK_Decryption_Test {
48
   public:
49
      RSA_Decryption_KAT_Tests() : PK_Decryption_Test("RSA", "pubkey/rsa_decrypt.vec", "E,P,Q,Ciphertext,Msg") {}
2✔
50

51
      bool clear_between_callbacks() const override { return false; }
25✔
52

53
      std::unique_ptr<Botan::Private_Key> load_private_key(const VarMap& vars) override {
25✔
54
         return load_rsa_private_key(vars);
25✔
55
      }
56
};
57

58
class RSA_KEM_Tests final : public PK_KEM_Test {
59
   public:
60
      RSA_KEM_Tests() : PK_KEM_Test("RSA", "pubkey/rsa_kem.vec", "E,P,Q,R,C0,KDF,K") {}
2✔
61

62
      std::unique_ptr<Botan::Private_Key> load_private_key(const VarMap& vars) override {
10✔
63
         return load_rsa_private_key(vars);
10✔
64
      }
65
};
66

67
class RSA_Signature_KAT_Tests final : public PK_Signature_Generation_Test {
68
   public:
69
      RSA_Signature_KAT_Tests() :
1✔
70
            PK_Signature_Generation_Test("RSA", "pubkey/rsa_sig.vec", "E,P,Q,Msg,Signature", "Nonce") {}
2✔
71

72
      std::string default_padding(const VarMap& /*unused*/) const override { return "Raw"; }
×
73

74
      std::unique_ptr<Botan::Private_Key> load_private_key(const VarMap& vars) override {
172✔
75
         return load_rsa_private_key(vars);
172✔
76
      }
77
};
78

79
class RSA_PSS_KAT_Tests final : public PK_Signature_Generation_Test {
80
   public:
81
      RSA_PSS_KAT_Tests() :
1✔
82
            PK_Signature_Generation_Test("RSA", "pubkey/rsa_pss.vec", "P,Q,E,Hash,Nonce,Msg,Signature", "") {}
2✔
83

84
      std::string default_padding(const VarMap& vars) const override {
88✔
85
         const std::string hash_name = vars.get_req_str("Hash");
88✔
86
         const size_t salt_size = vars.get_req_bin("Nonce").size();
176✔
87
         return Botan::fmt("PSS({},MGF1,{})", hash_name, salt_size);
88✔
88
      }
88✔
89

90
      bool clear_between_callbacks() const override { return false; }
88✔
91

92
      std::unique_ptr<Botan::Private_Key> load_private_key(const VarMap& vars) override {
88✔
93
         return load_rsa_private_key(vars);
88✔
94
      }
95
};
96

97
class RSA_PSS_Raw_KAT_Tests final : public PK_Signature_Generation_Test {
98
   public:
99
      RSA_PSS_Raw_KAT_Tests() :
1✔
100
            PK_Signature_Generation_Test("RSA", "pubkey/rsa_pss_raw.vec", "P,Q,E,Hash,Nonce,Msg,Signature", "") {}
2✔
101

102
      std::string default_padding(const VarMap& vars) const override {
80✔
103
         const std::string hash_name = vars.get_req_str("Hash");
80✔
104
         const size_t salt_size = vars.get_req_bin("Nonce").size();
160✔
105
         return Botan::fmt("PSS_Raw({},MGF1,{})", hash_name, salt_size);
80✔
106
      }
80✔
107

108
      bool clear_between_callbacks() const override { return false; }
80✔
109

110
      std::unique_ptr<Botan::Private_Key> load_private_key(const VarMap& vars) override {
80✔
111
         return load_rsa_private_key(vars);
80✔
112
      }
113
};
114

115
class RSA_Signature_Verify_Tests final : public PK_Signature_Verification_Test {
116
   public:
117
      RSA_Signature_Verify_Tests() :
1✔
118
            PK_Signature_Verification_Test("RSA", "pubkey/rsa_verify.vec", "E,N,Msg,Signature") {}
2✔
119

120
      std::string default_padding(const VarMap& /*unused*/) const override { return "Raw"; }
×
121

122
      std::unique_ptr<Botan::Public_Key> load_public_key(const VarMap& vars) override {
206✔
123
         return load_rsa_public_key(vars);
206✔
124
      }
125
};
126

127
class RSA_Signature_Verify_Invalid_Tests final : public PK_Signature_NonVerification_Test {
128
   public:
129
      RSA_Signature_Verify_Invalid_Tests() :
1✔
130
            PK_Signature_NonVerification_Test("RSA", "pubkey/rsa_invalid.vec", "E,N,Msg,InvalidSignature") {}
2✔
131

132
      std::string default_padding(const VarMap& /*unused*/) const override { return "Raw"; }
×
133

134
      std::unique_ptr<Botan::Public_Key> load_public_key(const VarMap& vars) override {
366✔
135
         return load_rsa_public_key(vars);
366✔
136
      }
137
};
138

139
class RSA_Keygen_Tests final : public PK_Key_Generation_Test {
×
140
   public:
141
      std::vector<std::string> keygen_params() const override { return {"1024", "1280"}; }
1✔
142

143
      std::unique_ptr<Botan::Public_Key> public_key_from_raw(std::string_view /* keygen_params */,
×
144
                                                             std::string_view /* provider */,
145
                                                             std::span<const uint8_t> /* raw_pk */) const override {
146
         // RSA does not implement raw public key encoding
147
         return nullptr;
×
148
      }
149

150
      std::string algo_name() const override { return "RSA"; }
2✔
151
};
152

153
class RSA_Keygen_Stability_Tests final : public PK_Key_Generation_Stability_Test {
154
   public:
155
      RSA_Keygen_Stability_Tests() : PK_Key_Generation_Stability_Test("RSA", "pubkey/rsa_keygen.vec") {}
2✔
156
};
157

158
class RSA_Keygen_Bad_RNG_Test final : public Test {
×
159
   public:
160
      std::vector<Test::Result> run() override {
1✔
161
         Test::Result result("RSA keygen with bad RNG");
1✔
162

163
         /*
164
         We don't need to count requests here; actually this test
165
         is relying on the fact that the Request_Counting_RNG outputs
166
         repeating 808080...
167
         */
168
         Request_Counting_RNG rng;
2✔
169

170
         try {
1✔
171
            Botan::RSA_PrivateKey rsa(rng, 1024);
1✔
172
            result.test_failure("Generated a key with a bad RNG");
×
173
         } catch(Botan::Internal_Error& e) {
1✔
174
            result.test_success("Key generation with bad RNG failed");
1✔
175
            result.test_eq("Expected message", e.what(), "Internal error: RNG failure during RSA key generation");
1✔
176
         }
1✔
177

178
         return {result};
2✔
179
      }
2✔
180
};
181

182
class RSA_Blinding_Tests final : public Test {
×
183
   public:
184
      std::vector<Test::Result> run() override {
1✔
185
         Test::Result result("RSA blinding");
1✔
186

187
         /* This test makes only sense with the base provider, else skip it. */
188
         if(provider_filter({"base"}).empty()) {
1✔
189
            result.note_missing("base provider");
×
190
            return std::vector<Test::Result>{result};
×
191
         }
192

193
   #if defined(BOTAN_HAS_EMSA_RAW) || defined(BOTAN_HAS_EME_RAW)
194
         Botan::RSA_PrivateKey rsa(this->rng(), 1024);
1✔
195
         Botan::Null_RNG null_rng;
1✔
196
   #endif
197

198
   #if defined(BOTAN_HAS_EMSA_RAW)
199

200
         /*
201
         * The blinder chooses a new starting point Blinder::ReinitInterval
202
         * so sign several times that with a single key.
203
         *
204
         * Very small values (padding/hashing disabled, only low byte set on input)
205
         * are used as an additional test on the blinders.
206
         */
207

208
         Botan::PK_Signer signer(
1✔
209
            rsa, this->rng(), "Raw", Botan::Signature_Format::Standard, "base");  // don't try this at home
1✔
210
         Botan::PK_Verifier verifier(rsa, "Raw", Botan::Signature_Format::Standard, "base");
1✔
211

212
         for(size_t i = 1; i <= Botan::Blinder::ReinitInterval * 6; ++i) {
385✔
213
            std::vector<uint8_t> input(16);
384✔
214
            input[input.size() - 1] = static_cast<uint8_t>(i | 1);
384✔
215

216
            signer.update(input);
384✔
217

218
            // assert RNG is not called in this situation
219
            std::vector<uint8_t> signature = signer.signature(null_rng);
384✔
220

221
            result.test_eq("Signature verifies", verifier.verify_message(input, signature), true);
768✔
222
         }
768✔
223
   #endif
224

225
   #if defined(BOTAN_HAS_EME_RAW)
226

227
         /*
228
         * The blinder chooses a new starting point Blinder::ReinitInterval
229
         * so decrypt several times that with a single key.
230
         *
231
         * Very small values (padding/hashing disabled, only low byte set on input)
232
         * are used as an additional test on the blinders.
233
         */
234

235
         Botan::PK_Encryptor_EME encryptor(rsa, this->rng(), "Raw", "base");  // don't try this at home
1✔
236

237
         /*
238
         Test blinding reinit interval
239

240
         Seed Fixed_Output_RNG only with enough bytes for the initial
241
         blinder initialization plus the exponent blinding bits which
242
         is 2*64 bits per operation.
243
         */
244
         const size_t rng_bytes = rsa.get_n().bytes() + (2 * 8 * Botan::Blinder::ReinitInterval);
1✔
245

246
         Fixed_Output_RNG fixed_rng(this->rng(), rng_bytes);
1✔
247
         Botan::PK_Decryptor_EME decryptor(rsa, fixed_rng, "Raw", "base");
1✔
248

249
         for(size_t i = 1; i <= Botan::Blinder::ReinitInterval; ++i) {
65✔
250
            std::vector<uint8_t> input(16);
64✔
251
            input[input.size() - 1] = static_cast<uint8_t>(i);
64✔
252

253
            std::vector<uint8_t> ciphertext = encryptor.encrypt(input, null_rng);
64✔
254

255
            std::vector<uint8_t> plaintext = Botan::unlock(decryptor.decrypt(ciphertext));
64✔
256
            plaintext.insert(plaintext.begin(), input.size() - 1, 0);
64✔
257

258
            result.test_eq("Successful decryption", plaintext, input);
128✔
259
         }
192✔
260

261
         result.test_eq("RNG is no longer seeded", fixed_rng.is_seeded(), false);
1✔
262

263
         // one more decryption should trigger a blinder reinitialization
264
         result.test_throws("RSA blinding reinit",
2✔
265
                            "Test error Fixed output RNG ran out of bytes, test bug?",
266
                            [&decryptor, &encryptor, &null_rng]() {
1✔
267
                               std::vector<uint8_t> ciphertext =
1✔
268
                                  encryptor.encrypt(std::vector<uint8_t>(16, 5), null_rng);
1✔
269
                               decryptor.decrypt(ciphertext);
1✔
270
                            });
×
271

272
   #endif
273

274
         return std::vector<Test::Result>{result};
2✔
275
      }
2✔
276
};
277

278
class RSA_DecryptOrRandom_Tests : public Test {
×
279
   public:
280
      std::vector<Test::Result> run() override {
1✔
281
         const std::vector<std::string> padding_schemes = {
1✔
282
   #if defined(BOTAN_HAS_EME_PKCS1)
283
            "PKCS1v15",
284
   #endif
285
   #if defined(BOTAN_HAS_EME_OAEP)
286
            "OAEP(SHA-256)",
287
   #endif
288
         };
1✔
289

290
         constexpr size_t bits = 1024;
1✔
291

292
         auto private_key = Botan::RSA_PrivateKey(rng(), bits);
1✔
293

294
         std::vector<Test::Result> results;
1✔
295
         for(const auto& padding : padding_schemes) {
3✔
296
            Test::Result result("RSA decrypt_or_random " + padding);
2✔
297
            test_decrypt_or_random(result, padding, private_key, rng());
2✔
298
            results.push_back(result);
2✔
299
         }
2✔
300
         return results;
1✔
301
      }
1✔
302

303
   private:
304
      static void test_decrypt_or_random(Test::Result& result,
2✔
305
                                         std::string_view padding,
306
                                         Botan::Private_Key& private_key,
307
                                         Botan::RandomNumberGenerator& rng) {
308
         constexpr size_t trials = 100;
2✔
309
         constexpr size_t pt_len = 32;
2✔
310

311
         auto public_key = private_key.public_key();
2✔
312
         const auto msg = rng.random_vec(pt_len);
2✔
313

314
         Botan::PK_Encryptor_EME enc(*public_key, rng, padding);
2✔
315
         const auto ctext = enc.encrypt(msg, rng);
2✔
316

317
         Botan::PK_Decryptor_EME dec(private_key, rng, padding);
2✔
318

319
         const BigInt modulus = public_key->get_int_field("n");
2✔
320

321
         for(size_t i = 0; i != trials; ++i) {
202✔
322
            auto bad_ctext = (BigInt::from_bytes(mutate_vec(ctext, rng, false, 0)) % modulus).serialize();
800✔
323

324
            auto rec = dec.decrypt_or_random(bad_ctext.data(), bad_ctext.size(), pt_len, rng);
200✔
325

326
            result.test_eq("Returns a ciphertext of expected length", rec.size(), pt_len);
400✔
327
         }
400✔
328

329
         // Test decrypt_or_random with content check happy path
330
         for(size_t i = 1; i != pt_len; ++i) {
64✔
331
            const size_t req_bytes = i;
62✔
332

333
            std::vector<uint8_t> required_contents(req_bytes);
62✔
334
            std::vector<uint8_t> required_offsets(req_bytes);
62✔
335

336
            for(size_t j = 0; j != req_bytes; ++j) {
1,054✔
337
               uint8_t idx = rng.next_byte() % pt_len;
992✔
338
               required_contents[j] = msg[idx];
992✔
339
               required_offsets[j] = idx;
992✔
340
            }
341

342
            auto rec = dec.decrypt_or_random(
62✔
343
               ctext.data(), ctext.size(), pt_len, rng, required_contents.data(), required_offsets.data(), req_bytes);
62✔
344

345
            result.test_eq("Returned the expected message", rec, msg);
124✔
346
         }
186✔
347

348
         // Test decrypt_or_random with content check error path
349
         for(size_t i = 1; i != pt_len; ++i) {
64✔
350
            const size_t req_bytes = i;
62✔
351

352
            std::vector<uint8_t> required_contents(req_bytes);
62✔
353
            std::vector<uint8_t> required_offsets(req_bytes);
62✔
354

355
            size_t corrupted = Test::random_index(rng, req_bytes);
62✔
356
            uint8_t corruption = rng.next_nonzero_byte();
62✔
357

358
            for(size_t j = 0; j != req_bytes; ++j) {
1,054✔
359
               uint8_t idx = rng.next_byte() % pt_len;
992✔
360
               required_offsets[j] = idx;
992✔
361

362
               if(idx == corrupted) {
992✔
363
                  required_contents[j] = msg[idx] ^ corruption;
29✔
364
               } else {
365
                  required_contents[j] = msg[idx];
963✔
366
               }
367
            }
368

369
            auto rec = dec.decrypt_or_random(
62✔
370
               ctext.data(), ctext.size(), pt_len, rng, required_contents.data(), required_offsets.data(), req_bytes);
62✔
371

372
            result.test_ne("Returned random message", rec, ctext);
124✔
373

374
            for(size_t j = 0; j != req_bytes; ++j) {
1,054✔
375
               result.confirm("Random message satisfies stated content requirements",
1,984✔
376
                              rec[required_offsets[j]] == required_contents[j]);
992✔
377
            }
378
         }
186✔
379
      }
8✔
380
};
381

382
BOTAN_REGISTER_TEST("pubkey", "rsa_encrypt", RSA_ES_KAT_Tests);
383
BOTAN_REGISTER_TEST("pubkey", "rsa_decrypt", RSA_Decryption_KAT_Tests);
384
BOTAN_REGISTER_TEST("pubkey", "rsa_sign", RSA_Signature_KAT_Tests);
385
BOTAN_REGISTER_TEST("pubkey", "rsa_pss", RSA_PSS_KAT_Tests);
386
BOTAN_REGISTER_TEST("pubkey", "rsa_pss_raw", RSA_PSS_Raw_KAT_Tests);
387
BOTAN_REGISTER_TEST("pubkey", "rsa_verify", RSA_Signature_Verify_Tests);
388
BOTAN_REGISTER_TEST("pubkey", "rsa_verify_invalid", RSA_Signature_Verify_Invalid_Tests);
389
BOTAN_REGISTER_TEST("pubkey", "rsa_kem", RSA_KEM_Tests);
390
BOTAN_REGISTER_TEST("pubkey", "rsa_keygen", RSA_Keygen_Tests);
391
BOTAN_REGISTER_TEST("pubkey", "rsa_keygen_stability", RSA_Keygen_Stability_Tests);
392
BOTAN_REGISTER_TEST("pubkey", "rsa_keygen_badrng", RSA_Keygen_Bad_RNG_Test);
393
BOTAN_REGISTER_TEST("pubkey", "rsa_blinding", RSA_Blinding_Tests);
394
BOTAN_REGISTER_TEST("pubkey", "rsa_decrypt_or_random", RSA_DecryptOrRandom_Tests);
395

396
#endif
397

398
}  // namespace
399

400
}  // namespace Botan_Tests
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc