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

randombit / botan / 14239872910

03 Apr 2025 09:40AM UTC coverage: 91.372% (+0.01%) from 91.36%
14239872910

Pull #4817

github

web-flow
Merge 2fb60b484 into 88bd49921
Pull Request #4817: ML-KEM: Minimal Support for Expanded Keys

95268 of 104264 relevant lines covered (91.37%)

11587736.02 hits per line

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

92.51
/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 <cmath>
20
#include <iterator>
21
#include <memory>
22

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

35
namespace Botan_Tests {
36

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

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

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

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

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

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

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

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

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

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

77
         //
78
         // negative tests
79
         //
80

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

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

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

100
         return result;
9✔
101
      }
72✔
102

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

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

120
namespace {
121

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

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

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

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

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

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

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

164
      Fixed_Output_RNG rng_for_encapsulation(const std::string&, Botan::RandomNumberGenerator& rng) const final {
225✔
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(const auto seedSk = skr->_seed_private_key_bits()) {
11✔
261
               result.test_eq("sk's seed encoding of sk", seedSk.value(), sk_raw);
6✔
262
               const auto skr_expanded =
3✔
263
                  std::make_unique<Botan::Kyber_PrivateKey>(skr->_expanded_private_key_bits(), mode);
3✔
264
               result.test_eq("sk's expanded encoding consistency",
6✔
265
                              skr->_expanded_private_key_bits(),
6✔
266
                              skr_expanded->_expanded_private_key_bits());
3✔
267
               result.confirm("expect no seed in expanded sk", !skr_expanded->_seed_private_key_bits().has_value());
6✔
268

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

275
            } else {
3✔
276
               result.test_eq("sk's expanded encoding of sk", skr->_expanded_private_key_bits(), sk_raw);
24✔
277
            }
11✔
278
         }
11✔
279

280
         return result;
11✔
281
      }
51✔
282
};
283

284
BOTAN_REGISTER_TEST("pubkey", "kyber_encodings", Kyber_Encoding_Test);
285

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

302
      std::string algo_name(std::string_view param) const override {
9✔
303
         if(param.starts_with("Kyber-")) {
9✔
304
            return "Kyber";
6✔
305
         } else {
306
            return "ML-KEM";
3✔
307
         }
308
      }
309

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

312
      std::unique_ptr<Botan::Public_Key> public_key_from_raw(std::string_view keygen_params,
9✔
313
                                                             std::string_view /* provider */,
314
                                                             std::span<const uint8_t> raw_pk) const override {
315
         return std::make_unique<Botan::Kyber_PublicKey>(raw_pk, Botan::KyberMode(keygen_params));
9✔
316
      }
317
};
318

319
BOTAN_REGISTER_TEST("pubkey", "kyber_keygen", Kyber_Keygen_Tests);
320

321
namespace {
322

323
template <size_t d>
324
void test_compress(Test::Result& res) {
5✔
325
   using namespace Botan;
326
   constexpr auto q = KyberConstants::Q;
5✔
327

328
   res.start_timer();
5✔
329

330
   for(uint16_t x = 0; x < q; ++x) {
16,650✔
331
      const uint32_t c = Kyber_Algos::compress<d>(x);
16,645✔
332
      constexpr auto twotothed = (uint32_t(1) << d);
16,645✔
333
      const auto e = ((twotothed * x + (q / 2)) / q) % twotothed;
16,645✔
334

335
      if(c != e) {
16,645✔
336
         res.test_failure(fmt("compress<{}>({}) = {}; expected {}", d, x, c, e));
×
337
         return;
×
338
      }
339
   }
340

341
   res.end_timer();
5✔
342
   res.test_success();
10✔
343
}
344

345
template <size_t d>
346
void test_decompress(Test::Result& result) {
5✔
347
   using namespace Botan;
348
   constexpr auto q = KyberConstants::Q;
5✔
349

350
   result.start_timer();
5✔
351

352
   using from_t = std::conditional_t<d <= 8, uint8_t, uint16_t>;
353
   const from_t twotothed = static_cast<from_t>(from_t(1) << d);
5✔
354

355
   for(from_t y = 0; y < twotothed; ++y) {
3,127✔
356
      const uint32_t c = Kyber_Algos::decompress<d>(y);
3,122✔
357
      const uint32_t e = (q * y + (twotothed / 2)) / twotothed;
3,122✔
358

359
      if(c != e) {
3,122✔
360
         result.test_failure(fmt("decompress<{}>({}) = {}; expected {}", d, static_cast<uint16_t>(y), c, e));
×
361
         return;
×
362
      }
363
   }
364

365
   result.end_timer();
5✔
366
   result.test_success();
10✔
367
}
368

369
template <size_t d>
370
void test_compress_roundtrip(Test::Result& result) {
5✔
371
   using namespace Botan;
372
   constexpr auto q = KyberConstants::Q;
5✔
373

374
   result.start_timer();
5✔
375

376
   for(uint16_t x = 0; x < q && x < (1 << d); ++x) {
3,127✔
377
      const uint16_t c = Kyber_Algos::compress<d>(Kyber_Algos::decompress<d>(x));
3,122✔
378
      if(x != c) {
3,122✔
379
         result.test_failure(fmt("compress<{}>(decompress<{}>({})) != {}", d, d, x, c));
×
380
         return;
×
381
      }
382
   }
383

384
   result.end_timer();
5✔
385
   result.test_success();
10✔
386
}
387

388
std::vector<Test::Result> test_kyber_helpers() {
1✔
389
   return {
1✔
390
      Botan_Tests::CHECK("compress<1>", [](Test::Result& res) { test_compress<1>(res); }),
1✔
391
      Botan_Tests::CHECK("compress<4>", [](Test::Result& res) { test_compress<4>(res); }),
1✔
392
      Botan_Tests::CHECK("compress<5>", [](Test::Result& res) { test_compress<5>(res); }),
1✔
393
      Botan_Tests::CHECK("compress<10>", [](Test::Result& res) { test_compress<10>(res); }),
1✔
394
      Botan_Tests::CHECK("compress<11>", [](Test::Result& res) { test_compress<11>(res); }),
1✔
395

396
      Botan_Tests::CHECK("decompress<1>", [](Test::Result& res) { test_decompress<1>(res); }),
1✔
397
      Botan_Tests::CHECK("decompress<4>", [](Test::Result& res) { test_decompress<4>(res); }),
1✔
398
      Botan_Tests::CHECK("decompress<5>", [](Test::Result& res) { test_decompress<5>(res); }),
1✔
399
      Botan_Tests::CHECK("decompress<10>", [](Test::Result& res) { test_decompress<10>(res); }),
1✔
400
      Botan_Tests::CHECK("decompress<11>", [](Test::Result& res) { test_decompress<11>(res); }),
1✔
401

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

410
}  // namespace
411

412
BOTAN_REGISTER_TEST_FN("pubkey", "kyber_helpers", test_kyber_helpers);
413

414
#endif
415

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

© 2025 Coveralls, Inc