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

randombit / botan / 13000762371

28 Jan 2025 12:04AM UTC coverage: 91.247% (+0.001%) from 91.246%
13000762371

push

github

web-flow
Merge pull request #4600 from randombit/jack/padding-alias

Avoid using IEEE 1363 EMSA names in OID data or EMSA::name

93989 of 103005 relevant lines covered (91.25%)

11450631.08 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/fmt.h>
14
#endif
15

16
namespace Botan_Tests {
17

18
namespace {
19

20
#if defined(BOTAN_HAS_RSA)
21

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

27
   return std::make_unique<Botan::RSA_PrivateKey>(p, q, e);
555✔
28
}
1,665✔
29

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

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

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

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

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

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

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

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

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

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

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

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

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

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

89
      bool clear_between_callbacks() const override { return false; }
80✔
90

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

197
   #if defined(BOTAN_HAS_EMSA_RAW)
198

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

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

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

215
            signer.update(input);
768✔
216

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

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

224
   #if defined(BOTAN_HAS_EME_RAW)
225

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

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

236
         /*
237
         Test blinding reinit interval
238

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

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

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

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

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

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

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

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

271
   #endif
272

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

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

289
         constexpr size_t bits = 1024;
1✔
290

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

395
#endif
396

397
}  // namespace
398

399
}  // 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