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

randombit / botan / 16271721753

14 Jul 2025 11:26AM UTC coverage: 90.622% (-0.003%) from 90.625%
16271721753

push

github

web-flow
Merge pull request #4989 from randombit/jack/fix-more-named-parameters

Fix more readability-named-parameter warnings from clang-tidy

99624 of 109934 relevant lines covered (90.62%)

12378967.04 hits per line

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

92.11
/src/tests/test_kyber.cpp
1
/*
2
 * Tests for Crystals Kyber
3
 * - simple roundtrip test
4
 * - KAT tests using the KAT vectors from
5
 *   https://csrc.nist.gov/CSRC/media/Projects/post-quantum-cryptography/documents/round-3/submissions/Kyber-Round3.zip
6
 *
7
 * (C) 2021-2024 Jack Lloyd
8
 * (C) 2021-2022 Manuel Glaser and Michael Boric, Rohde & Schwarz Cybersecurity
9
 * (C) 2021-2022 René Meusel and Hannes Rantzsch, neXenio GmbH
10
 * (C) 2023-2024 René Meusel, Rohde & Schwarz Cybersecurity
11
 *
12
 * Botan is released under the Simplified BSD License (see license.txt)
13
 */
14

15
#include "test_pubkey_pqc.h"
16
#include "test_rng.h"
17
#include "tests.h"
18

19
#include <iterator>
20
#include <memory>
21

22
#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S) || defined(BOTAN_HAS_ML_KEM)
23
   #include "test_pubkey.h"
24
   #include <botan/hex.h>
25
   #include <botan/kyber.h>
26
   #include <botan/pubkey.h>
27
   #include <botan/rng.h>
28
   #include <botan/internal/fmt.h>
29
   #include <botan/internal/kyber_constants.h>
30
   #include <botan/internal/kyber_helpers.h>
31
   #include <botan/internal/stl_util.h>
32
#endif
33

34
namespace Botan_Tests {
35

36
#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S) || defined(BOTAN_HAS_ML_KEM)
37

38
class KYBER_Tests final : public Test {
×
39
   public:
40
      static Test::Result run_kyber_test(const char* test_name, Botan::KyberMode mode, size_t strength, size_t psid) {
9✔
41
         Test::Result result(test_name);
9✔
42

43
         if(!mode.is_available()) {
9✔
44
            result.note_missing(mode.to_string());
×
45
            return result;
×
46
         }
47

48
         auto rng = Test::new_rng(test_name);
9✔
49

50
         const std::vector<uint8_t> empty_salt;
9✔
51

52
         // Alice
53
         const Botan::Kyber_PrivateKey priv_key(*rng, mode);
9✔
54
         const auto pub_key = priv_key.public_key();
9✔
55

56
         result.test_eq("estimated strength private", priv_key.estimated_strength(), strength);
9✔
57
         result.test_eq("estimated strength public", pub_key->estimated_strength(), strength);
9✔
58
         result.test_eq("canonical parameter set identifier", priv_key.key_length(), psid);
9✔
59
         result.test_eq("canonical parameter set identifier", pub_key->key_length(), psid);
9✔
60

61
         // Serialize
62
         const auto priv_key_bits = priv_key.private_key_bits();
9✔
63
         const auto pub_key_bits = pub_key->public_key_bits();
9✔
64

65
         // Bob (reading from serialized public key)
66
         Botan::Kyber_PublicKey alice_pub_key(pub_key_bits, mode);
9✔
67
         auto enc = Botan::PK_KEM_Encryptor(alice_pub_key, "Raw", "base");
9✔
68
         const auto kem_result = enc.encrypt(*rng);
9✔
69

70
         // Alice (reading from serialized private key)
71
         Botan::Kyber_PrivateKey alice_priv_key(priv_key_bits, mode);
9✔
72
         auto dec = Botan::PK_KEM_Decryptor(alice_priv_key, *rng, "Raw", "base");
9✔
73
         const auto key_alice = dec.decrypt(kem_result.encapsulated_shared_key(), 0 /* no KDF */, empty_salt);
9✔
74
         result.test_eq("shared secrets are equal", key_alice, kem_result.shared_key());
18✔
75

76
         //
77
         // negative tests
78
         //
79

80
         // Broken cipher_text from Alice (wrong length)
81
         result.test_throws("fail to read cipher_text", "Kyber: unexpected ciphertext length", [&] {
18✔
82
            auto short_cipher_text = kem_result.encapsulated_shared_key();
9✔
83
            short_cipher_text.pop_back();
9✔
84
            dec.decrypt(short_cipher_text, 0, empty_salt);
9✔
85
         });
×
86

87
         // Invalid cipher_text from Alice
88
         Botan::secure_vector<uint8_t> reverse_cipher_text;
9✔
89
         std::copy(kem_result.encapsulated_shared_key().crbegin(),
9✔
90
                   kem_result.encapsulated_shared_key().crend(),
9✔
91
                   std::back_inserter(reverse_cipher_text));
92
         const auto key_alice_rev = dec.decrypt(reverse_cipher_text, 0, empty_salt);
9✔
93
         result.confirm("shared secrets are not equal", key_alice != key_alice_rev);
18✔
94

95
         // Try to decrypt the valid ciphertext again
96
         const auto key_alice_try2 = dec.decrypt(kem_result.encapsulated_shared_key(), 0 /* no KDF */, empty_salt);
9✔
97
         result.test_eq("shared secrets are equal", key_alice_try2, kem_result.shared_key());
18✔
98

99
         return result;
9✔
100
      }
72✔
101

102
      std::vector<Test::Result> run() override {
1✔
103
         return {
1✔
104
            run_kyber_test("Kyber512_90s API", Botan::KyberMode::Kyber512_90s, 128, 512),
105
            run_kyber_test("Kyber768_90s API", Botan::KyberMode::Kyber768_90s, 192, 768),
106
            run_kyber_test("Kyber1024_90s API", Botan::KyberMode::Kyber1024_90s, 256, 1024),
107
            run_kyber_test("Kyber512 API", Botan::KyberMode::Kyber512_R3, 128, 512),
108
            run_kyber_test("Kyber768 API", Botan::KyberMode::Kyber768_R3, 192, 768),
109
            run_kyber_test("Kyber1024 API", Botan::KyberMode::Kyber1024_R3, 256, 1024),
110
            run_kyber_test("ML-KEM-512 API", Botan::KyberMode::ML_KEM_512, 128, 512),
111
            run_kyber_test("ML-KEM-768 API", Botan::KyberMode::ML_KEM_768, 192, 768),
112
            run_kyber_test("ML-KEM-1024 API", Botan::KyberMode::ML_KEM_1024, 256, 1024),
113
         };
10✔
114
      }
2✔
115
};
116

117
BOTAN_REGISTER_TEST("pubkey", "kyber_pairwise", KYBER_Tests);
118

119
namespace {
120

121
class Kyber_KAT_Tests : public PK_PQC_KEM_KAT_Test {
122
   protected:
123
      Kyber_KAT_Tests(const std::string& algo_name,
2✔
124
                      const std::string& kat_file,
125
                      const std::string& further_optional_keys = "") :
2✔
126
            PK_PQC_KEM_KAT_Test(algo_name, kat_file, further_optional_keys) {}
2✔
127

128
   private:
129
      Botan::KyberMode get_mode(const std::string& mode) const { return Botan::KyberMode(mode); }
2,400✔
130

131
      bool is_available(const std::string& mode) const final { return get_mode(mode).is_available(); }
225✔
132

133
      std::vector<uint8_t> map_value(const std::string& mode,
900✔
134
                                     std::span<const uint8_t> value,
135
                                     VarType var_type) const final {
136
         if(var_type == VarType::SharedSecret) {
900✔
137
            return {value.begin(), value.end()};
225✔
138
         }
139

140
         // We use different hash functions for Kyber 90s, as those are
141
         // consistent with the algorithm requirements of the implementations.
142
         std::string_view hash_name = get_mode(mode).is_90s() ? "SHA-256" : "SHAKE-256(128)";
675✔
143

144
         auto hash = Botan::HashFunction::create_or_throw(hash_name);
675✔
145
         const auto digest = hash->process(value);
675✔
146
         return {digest.begin(), digest.begin() + 16};
675✔
147
      }
1,350✔
148

149
      Fixed_Output_RNG rng_for_keygen(const std::string& mode, Botan::RandomNumberGenerator& rng) const final {
225✔
150
         if(get_mode(mode).is_kyber_round3()) {
225✔
151
            const auto seed = rng.random_vec(32);
150✔
152
            const auto z = rng.random_vec(32);
150✔
153
            return Fixed_Output_RNG(Botan::concat(seed, z));
300✔
154
         } else if(get_mode(mode).is_ml_kem()) {
375✔
155
            const auto z = rng.random_vec(32);
75✔
156
            const auto d = rng.random_vec(32);
75✔
157
            return Fixed_Output_RNG(Botan::concat(d, z));
150✔
158
         } else {
150✔
159
            return Fixed_Output_RNG(rng.random_vec(64));
×
160
         }
161
      }
162

163
      Fixed_Output_RNG rng_for_encapsulation(const std::string& /*mode*/,
225✔
164
                                             Botan::RandomNumberGenerator& rng) const final {
165
         return Fixed_Output_RNG(rng.random_vec(32));
450✔
166
      }
167
};
168

169
class KyberR3_KAT_Tests : public Kyber_KAT_Tests {
170
   public:
171
      KyberR3_KAT_Tests() : Kyber_KAT_Tests("Kyber", "pubkey/kyber_kat.vec") {}
2✔
172
};
173

174
class ML_KEM_KAT_Tests : public Kyber_KAT_Tests {
175
   public:
176
      ML_KEM_KAT_Tests() : Kyber_KAT_Tests("ML-KEM", "pubkey/ml_kem.vec", "CT_N,SS_N") {}
2✔
177
};
178

179
class ML_KEM_ACVP_KAT_KeyGen_Tests : public PK_PQC_KEM_ACVP_KAT_KeyGen_Test {
180
   public:
181
      ML_KEM_ACVP_KAT_KeyGen_Tests() :
1✔
182
            PK_PQC_KEM_ACVP_KAT_KeyGen_Test("ML-KEM", "pubkey/ml_kem_acvp_keygen.vec", "Z,D") {}
2✔
183

184
   private:
185
      Botan::KyberMode get_mode(const std::string& mode) const { return Botan::KyberMode(mode); }
150✔
186

187
      bool is_available(const std::string& mode) const final { return get_mode(mode).is_available(); }
75✔
188

189
      Fixed_Output_RNG rng_for_keygen(const VarMap& vars) const override {
75✔
190
         const auto d = vars.get_req_bin("D");
75✔
191
         const auto z = vars.get_req_bin("Z");
75✔
192
         return Fixed_Output_RNG(Botan::concat(d, z));
150✔
193
      }
150✔
194
};
195

196
class ML_KEM_PQC_KEM_ACVP_KAT_Encap_Test : public PK_PQC_KEM_ACVP_KAT_Encap_Test {
197
   public:
198
      ML_KEM_PQC_KEM_ACVP_KAT_Encap_Test() : PK_PQC_KEM_ACVP_KAT_Encap_Test("ML-KEM", "pubkey/ml_kem_acvp_encap.vec") {}
2✔
199

200
   private:
201
      Botan::KyberMode get_mode(const std::string& mode) const { return Botan::KyberMode(mode); }
300✔
202

203
      bool is_available(const std::string& mode) const final { return get_mode(mode).is_available(); }
75✔
204

205
      std::unique_ptr<Botan::Public_Key> load_public_key(const VarMap& vars, const std::string& mode) const final {
75✔
206
         return std::make_unique<Botan::Kyber_PublicKey>(vars.get_req_bin("EK"), get_mode(mode));
225✔
207
      }
208
};
209

210
}  // namespace
211

212
BOTAN_REGISTER_TEST("pubkey", "kyber_kat", KyberR3_KAT_Tests);
213
BOTAN_REGISTER_TEST("pubkey", "ml_kem_kat", ML_KEM_KAT_Tests);
214
BOTAN_REGISTER_TEST("pubkey", "ml_kem_acvp_kat_keygen", ML_KEM_ACVP_KAT_KeyGen_Tests);
215
BOTAN_REGISTER_TEST("pubkey", "ml_kem_acvp_kat_encap", ML_KEM_PQC_KEM_ACVP_KAT_Encap_Test);
216

217
// Currently we cannot use the ACVP decapsulation tests because they do not
218
// provide the private key's seed values.
219
//BOTAN_REGISTER_TEST("pubkey", "ml_kem_acvp_kat_decap", ML_KEM_PQC_KEM_ACVP_KAT_Decap_Test);
220

221
class Kyber_Encoding_Test : public Text_Based_Test {
222
   public:
223
      Kyber_Encoding_Test() : Text_Based_Test("pubkey/kyber_encodings.vec", "PrivateRaw,PublicRaw", "Error") {}
2✔
224

225
   public:
226
      bool skip_this_test(const std::string& algo_name, const VarMap& /*vars*/) override {
17✔
227
         return !Botan::KyberMode(algo_name).is_available();
17✔
228
      }
229

230
      Test::Result run_one_test(const std::string& algo_name, const VarMap& vars) override {
17✔
231
         Test::Result result("kyber_encodings");
17✔
232

233
         const auto mode = Botan::KyberMode(algo_name);
17✔
234
         const auto pk_raw = Botan::hex_decode(vars.get_req_str("PublicRaw"));
34✔
235
         const auto sk_raw = Botan::hex_decode_locked(vars.get_req_str("PrivateRaw"));
34✔
236
         const auto error = vars.get_opt_str("Error", "");
34✔
237

238
         if(!error.empty()) {
17✔
239
            // negative tests
240

241
            result.test_throws("failing decoding", error, [&] {
12✔
242
               if(!sk_raw.empty()) {
6✔
243
                  Botan::Kyber_PrivateKey(sk_raw, mode);
5✔
244
               }
245
               if(!pk_raw.empty()) {
3✔
246
                  Botan::Kyber_PublicKey(pk_raw, mode);
3✔
247
               }
248
            });
×
249

250
            return result;
6✔
251
         } else {
252
            const auto skr = std::make_unique<Botan::Kyber_PrivateKey>(sk_raw, mode);
11✔
253
            const auto pkr = std::make_unique<Botan::Kyber_PublicKey>(pk_raw, mode);
11✔
254

255
            result.test_eq("sk's encoding of pk", skr->public_key_bits(), pk_raw);
22✔
256
            result.test_eq("sk's encoding of sk", skr->private_key_bits(), sk_raw);
22✔
257
            result.test_eq("pk's encoding of pk", pkr->public_key_bits(), pk_raw);
22✔
258

259
            // expanded vs seed encoding
260
            if(skr->private_key_format() == Botan::MlPrivateKeyFormat::Seed) {
11✔
261
               result.test_eq("sk's seed encoding of sk",
6✔
262
                              skr->private_key_bits_with_format(Botan::MlPrivateKeyFormat::Seed),
3✔
263
                              sk_raw);
264
               const auto skr_expanded = std::make_unique<Botan::Kyber_PrivateKey>(
3✔
265
                  skr->private_key_bits_with_format(Botan::MlPrivateKeyFormat::Expanded), mode);
3✔
266
               result.test_eq("sk's expanded encoding consistency",
6✔
267
                              skr->private_key_bits_with_format(Botan::MlPrivateKeyFormat::Expanded),
6✔
268
                              skr_expanded->private_key_bits_with_format(Botan::MlPrivateKeyFormat::Expanded));
3✔
269
               result.test_throws<Botan::Encoding_Error>("expect no seed in expanded sk", [&] {
6✔
270
                  skr_expanded->private_key_bits_with_format(Botan::MlPrivateKeyFormat::Seed);
3✔
271
               });
×
272

273
               const auto encapsulation = Botan::PK_KEM_Encryptor(*pkr, "Raw").encrypt(rng());
3✔
274
               result.test_eq(
6✔
275
                  "expanded sk decapsulation",
276
                  Botan::PK_KEM_Decryptor(*skr_expanded, rng(), "Raw").decrypt(encapsulation.encapsulated_shared_key()),
6✔
277
                  encapsulation.shared_key());
3✔
278

279
            } else {
3✔
280
               result.test_eq("sk's expanded encoding of sk",
16✔
281
                              skr->private_key_bits_with_format(Botan::MlPrivateKeyFormat::Expanded),
16✔
282
                              sk_raw);
283
            }
284
         }
11✔
285

286
         return result;
11✔
287
      }
51✔
288
};
289

290
BOTAN_REGISTER_TEST("pubkey", "kyber_encodings", Kyber_Encoding_Test);
291

292
class Kyber_Keygen_Tests final : public PK_Key_Generation_Test {
×
293
   public:
294
      std::vector<std::string> keygen_params() const override {
1✔
295
         return {
1✔
296
   #if defined(BOTAN_HAS_KYBER_90S)
297
            "Kyber-512-90s-r3", "Kyber-768-90s-r3", "Kyber-1024-90s-r3",
298
   #endif
299
   #if defined(BOTAN_HAS_KYBER)
300
               "Kyber-512-r3", "Kyber-768-r3", "Kyber-1024-r3",
301
   #endif
302
   #if defined(BOTAN_HAS_ML_KEM)
303
               "ML-KEM-512", "ML-KEM-768", "ML-KEM-1024",
304
   #endif
305
         };
1✔
306
      }
307

308
      std::string algo_name(std::string_view param) const override {
9✔
309
         if(param.starts_with("Kyber-")) {
9✔
310
            return "Kyber";
6✔
311
         } else {
312
            return "ML-KEM";
3✔
313
         }
314
      }
315

316
      std::string algo_name() const override { throw Test_Error("No default algo name set for Kyber"); }
×
317

318
      std::unique_ptr<Botan::Public_Key> public_key_from_raw(std::string_view keygen_params,
9✔
319
                                                             std::string_view /* provider */,
320
                                                             std::span<const uint8_t> raw_pk) const override {
321
         return std::make_unique<Botan::Kyber_PublicKey>(raw_pk, Botan::KyberMode(keygen_params));
9✔
322
      }
323
};
324

325
BOTAN_REGISTER_TEST("pubkey", "kyber_keygen", Kyber_Keygen_Tests);
326

327
namespace {
328

329
template <size_t d>
330
void test_compress(Test::Result& res) {
5✔
331
   using namespace Botan;
332
   constexpr auto q = KyberConstants::Q;
5✔
333

334
   res.start_timer();
5✔
335

336
   for(uint16_t x = 0; x < q; ++x) {
16,650✔
337
      const uint32_t c = Kyber_Algos::compress<d>(x);
16,645✔
338
      constexpr auto twotothed = (uint32_t(1) << d);
16,645✔
339
      const auto e = ((twotothed * x + (q / 2)) / q) % twotothed;
16,645✔
340

341
      if(c != e) {
16,645✔
342
         res.test_failure(fmt("compress<{}>({}) = {}; expected {}", d, x, c, e));
×
343
         return;
×
344
      }
345
   }
346

347
   res.end_timer();
5✔
348
   res.test_success();
10✔
349
}
350

351
template <size_t d>
352
void test_decompress(Test::Result& result) {
5✔
353
   using namespace Botan;
354
   constexpr auto q = KyberConstants::Q;
5✔
355

356
   result.start_timer();
5✔
357

358
   using from_t = std::conditional_t<d <= 8, uint8_t, uint16_t>;
359
   const from_t twotothed = static_cast<from_t>(from_t(1) << d);
5✔
360

361
   for(from_t y = 0; y < twotothed; ++y) {
3,127✔
362
      const uint32_t c = Kyber_Algos::decompress<d>(y);
3,122✔
363
      const uint32_t e = (q * y + (twotothed / 2)) / twotothed;
3,122✔
364

365
      if(c != e) {
3,122✔
366
         result.test_failure(fmt("decompress<{}>({}) = {}; expected {}", d, static_cast<uint16_t>(y), c, e));
×
367
         return;
×
368
      }
369
   }
370

371
   result.end_timer();
5✔
372
   result.test_success();
10✔
373
}
374

375
template <size_t d>
376
void test_compress_roundtrip(Test::Result& result) {
5✔
377
   using namespace Botan;
378
   constexpr auto q = KyberConstants::Q;
5✔
379

380
   result.start_timer();
5✔
381

382
   // NOLINTNEXTLINE(*-redundant-expression)
383
   for(uint16_t x = 0; x < q && x < (1 << d); ++x) {
3,127✔
384
      const uint16_t c = Kyber_Algos::compress<d>(Kyber_Algos::decompress<d>(x));
3,122✔
385
      if(x != c) {
3,122✔
386
         result.test_failure(fmt("compress<{}>(decompress<{}>({})) != {}", d, d, x, c));
×
387
         return;
×
388
      }
389
   }
390

391
   result.end_timer();
5✔
392
   result.test_success();
10✔
393
}
394

395
std::vector<Test::Result> test_kyber_helpers() {
1✔
396
   return {
1✔
397
      Botan_Tests::CHECK("compress<1>", [](Test::Result& res) { test_compress<1>(res); }),
1✔
398
      Botan_Tests::CHECK("compress<4>", [](Test::Result& res) { test_compress<4>(res); }),
1✔
399
      Botan_Tests::CHECK("compress<5>", [](Test::Result& res) { test_compress<5>(res); }),
1✔
400
      Botan_Tests::CHECK("compress<10>", [](Test::Result& res) { test_compress<10>(res); }),
1✔
401
      Botan_Tests::CHECK("compress<11>", [](Test::Result& res) { test_compress<11>(res); }),
1✔
402

403
      Botan_Tests::CHECK("decompress<1>", [](Test::Result& res) { test_decompress<1>(res); }),
1✔
404
      Botan_Tests::CHECK("decompress<4>", [](Test::Result& res) { test_decompress<4>(res); }),
1✔
405
      Botan_Tests::CHECK("decompress<5>", [](Test::Result& res) { test_decompress<5>(res); }),
1✔
406
      Botan_Tests::CHECK("decompress<10>", [](Test::Result& res) { test_decompress<10>(res); }),
1✔
407
      Botan_Tests::CHECK("decompress<11>", [](Test::Result& res) { test_decompress<11>(res); }),
1✔
408

409
      Botan_Tests::CHECK("compress<1>(decompress())", [](Test::Result& res) { test_compress_roundtrip<1>(res); }),
1✔
410
      Botan_Tests::CHECK("compress<4>(decompress())", [](Test::Result& res) { test_compress_roundtrip<4>(res); }),
1✔
411
      Botan_Tests::CHECK("compress<5>(decompress())", [](Test::Result& res) { test_compress_roundtrip<5>(res); }),
1✔
412
      Botan_Tests::CHECK("compress<10>(decompress())>", [](Test::Result& res) { test_compress_roundtrip<10>(res); }),
1✔
413
      Botan_Tests::CHECK("compress<11>(decompress())>", [](Test::Result& res) { test_compress_roundtrip<11>(res); }),
1✔
414
   };
16✔
415
}
1✔
416

417
}  // namespace
418

419
BOTAN_REGISTER_TEST_FN("pubkey", "kyber_helpers", test_kyber_helpers);
420

421
#endif
422

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