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

randombit / botan / 16244527778

13 Jul 2025 02:43AM UTC coverage: 90.572% (-0.003%) from 90.575%
16244527778

push

github

web-flow
Merge pull request #4978 from randombit/jack/clang-tidy-misc-redundant-expression

Enable and fix clang-tidy warning misc-redundant-expression

99098 of 109413 relevant lines covered (90.57%)

12337696.32 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&, Botan::RandomNumberGenerator& rng) const final {
225✔
164
         return Fixed_Output_RNG(rng.random_vec(32));
450✔
165
      }
166
};
167

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

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

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

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

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

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

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

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

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

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

209
}  // namespace
210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

326
namespace {
327

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

333
   res.start_timer();
5✔
334

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

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

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

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

355
   result.start_timer();
5✔
356

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

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

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

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

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

379
   result.start_timer();
5✔
380

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

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

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

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

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

416
}  // namespace
417

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

420
#endif
421

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