Botan 3.13.0
Crypto and TLS for C&
kyber.cpp
Go to the documentation of this file.
1/*
2 * Crystals Kyber key encapsulation mechanism
3 * Based on the public domain reference implementation by the
4 * designers (https://github.com/pq-crystals/kyber)
5 *
6 * Further changes
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) 2024 René Meusel, Fabian Albert, Rohde & Schwarz Cybersecurity
11 *
12 * Botan is released under the Simplified BSD License (see license.txt)
13 */
14
15#include <botan/kyber.h>
16
17#include <botan/assert.h>
18#include <botan/pubkey.h>
19#include <botan/rng.h>
20#include <botan/secmem.h>
21#include <botan/internal/fmt.h>
22#include <botan/internal/kyber_algos.h>
23#include <botan/internal/kyber_constants.h>
24#include <botan/internal/kyber_keys.h>
25#include <botan/internal/kyber_types.h>
26
27#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
28 #include <botan/internal/kyber_round3_impl.h>
29#endif
30
31#if defined(BOTAN_HAS_ML_KEM)
32 #include <botan/internal/ml_kem_impl.h>
33#endif
34
35#include <memory>
36#include <vector>
37
38namespace Botan {
39
40namespace {
41
42KyberMode::Mode kyber_mode_from_string(std::string_view str) {
43 if(str == "Kyber-512-90s-r3") {
45 }
46 if(str == "Kyber-768-90s-r3") {
48 }
49 if(str == "Kyber-1024-90s-r3") {
51 }
52 if(str == "Kyber-512-r3") {
54 }
55 if(str == "Kyber-768-r3") {
57 }
58 if(str == "Kyber-1024-r3") {
60 }
61 if(str == "ML-KEM-512") {
63 }
64 if(str == "ML-KEM-768") {
66 }
67 if(str == "ML-KEM-1024") {
69 }
70
71 throw Invalid_Argument(fmt("'{}' is not a valid Kyber mode name", str));
72}
73
74KyberMode::Mode kyber_mode_from_oid(const OID& oid) {
75 if(const auto name = oid.registered_name()) {
76 return kyber_mode_from_string(*name);
77 }
78
79 throw Invalid_Argument(fmt("OID '{}' is not registered as a Kyber/ML-KEM mode", oid));
80}
81
82} // namespace
83
85
86KyberMode::KyberMode(const OID& oid) : m_mode(kyber_mode_from_oid(oid)) {}
87
88KyberMode::KyberMode(std::string_view str) : m_mode(kyber_mode_from_string(str)) {}
89
93
94std::string KyberMode::to_string() const {
95 switch(m_mode) {
96 case Kyber512_90s:
97 return "Kyber-512-90s-r3";
98 case Kyber768_90s:
99 return "Kyber-768-90s-r3";
100 case Kyber1024_90s:
101 return "Kyber-1024-90s-r3";
102 case Kyber512_R3:
103 return "Kyber-512-r3";
104 case Kyber768_R3:
105 return "Kyber-768-r3";
106 case Kyber1024_R3:
107 return "Kyber-1024-r3";
108 case ML_KEM_512:
109 return "ML-KEM-512";
110 case ML_KEM_768:
111 return "ML-KEM-768";
112 case ML_KEM_1024:
113 return "ML-KEM-1024";
114 }
115
117}
118
119bool KyberMode::is_90s() const {
120 return m_mode == Kyber512_90s || m_mode == Kyber768_90s || m_mode == Kyber1024_90s;
121}
122
124 return !is_90s();
125}
126
128 return m_mode == KyberMode::ML_KEM_512 || m_mode == KyberMode::ML_KEM_768 || m_mode == KyberMode::ML_KEM_1024;
129}
130
132 return m_mode == KyberMode::Kyber512_R3 || m_mode == KyberMode::Kyber768_R3 || m_mode == KyberMode::Kyber1024_R3 ||
134}
135
137#if defined(BOTAN_HAS_KYBER)
138 if(is_kyber_round3() && is_modern()) {
139 return true;
140 }
141#endif
142
143#if defined(BOTAN_HAS_KYBER_90S)
144 if(is_kyber_round3() && is_90s()) {
145 return true;
146 }
147#endif
148
149#if defined(BOTAN_HAS_ML_KEM)
150 if(is_ml_kem()) {
151 return true;
152 }
153#endif
154
155 return false;
156}
157
159 return m_public->mode().mode();
160}
161
162std::string Kyber_PublicKey::algo_name() const {
163 return mode().is_ml_kem() ? "ML-KEM" : "Kyber";
164}
165
167 // draft-ietf-lamps-kyber-certificates-latest (22 July 2024) The
168 // AlgorithmIdentifier for a ML-KEM public key MUST use one of the
169 // id-alg-ml-kem object identifiers [...]. The parameters field of the
170 // AlgorithmIdentifier for the ML-KEM public key MUST be absent.
172}
173
177
179 return m_public->mode().estimated_strength();
180}
181
182Kyber_PublicKey::Kyber_PublicKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) :
183 Kyber_PublicKey(key_bits, KyberMode(alg_id.oid())) {
184 // The parameter set is identified by the OID; no parameters are defined.
185 if(!alg_id.parameters_are_empty()) {
186 throw Decoding_Error("Unexpected parameters for ML-KEM/Kyber public key");
187 }
188}
189
190Kyber_PublicKey::Kyber_PublicKey(std::span<const uint8_t> pub_key, KyberMode mode) {
191 m_public = std::make_shared<Kyber_PublicKeyInternal>(mode, KyberSerializedPublicKey(pub_key));
192}
193
195 m_public(std::make_shared<Kyber_PublicKeyInternal>(
196 other.m_public->mode(), other.m_public->t().clone(), other.m_public->rho())) {}
197
198std::vector<uint8_t> Kyber_PublicKey::raw_public_key_bits() const {
199 return m_public->public_key_bits_raw().get();
200}
201
202std::vector<uint8_t> Kyber_PublicKey::public_key_bits() const {
203 // Currently, there isn't a finalized definition of an ASN.1 structure for
204 // Kyber aka ML-KEM public keys. Therefore, we return the raw public key bits.
205 return raw_public_key_bits();
206}
207
209 return m_public->mode().canonical_parameter_set_identifier();
210}
211
212bool Kyber_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*strong*/) const {
213 // The length checks described in FIPS 203, Section 7.2 are already performed
214 // while decoding the public key. See constructor of Kyber_PublicKeyInternal.
215 // The decoding function KyberAlgos::byte_decode() also checks the range of
216 // the decoded values. The check below is added for completeness.
217
218 std::vector<uint8_t> test(m_public->mode().polynomial_vector_bytes());
220
221 const auto& serialized_pubkey = m_public->public_key_bits_raw();
222 return test.size() < serialized_pubkey.size() && std::equal(test.begin(), test.end(), serialized_pubkey.begin());
223}
224
225std::unique_ptr<Private_Key> Kyber_PublicKey::generate_another(RandomNumberGenerator& rng) const {
226 return std::make_unique<Kyber_PrivateKey>(rng, mode());
227}
228
229/**
230 * NIST FIPS 203, Algorithms 19 (ML-KEM.KeyGen)
231 */
238
239Kyber_PrivateKey::Kyber_PrivateKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) :
240 Kyber_PrivateKey(key_bits, KyberMode(alg_id.oid())) {
241 // The parameter set is identified by the OID; no parameters are defined.
242 if(!alg_id.parameters_are_empty()) {
243 throw Decoding_Error("Unexpected parameters for ML-KEM/Kyber private key");
244 }
245}
246
247Kyber_PrivateKey::Kyber_PrivateKey(std::span<const uint8_t> sk, KyberMode m) {
249
250 if(mode.mode().is_ml_kem() && sk.size() == mode.seed_private_key_bytes()) {
251 std::tie(m_public, m_private) = Seed_Expanding_Keypair_Codec().decode_keypair(sk, std::move(mode));
252 } else if(sk.size() == mode.expanded_private_key_bytes()) {
253 std::tie(m_public, m_private) = Expanded_Keypair_Codec().decode_keypair(sk, std::move(mode));
254 } else if(!mode.mode().is_ml_kem() && sk.size() == mode.seed_private_key_bytes()) {
255 throw Invalid_Argument("Kyber round 3 private keys do not support the seed format");
256 } else {
257 throw Invalid_Argument("Private key does not have the correct byte count");
258 }
259}
260
261std::unique_ptr<Public_Key> Kyber_PrivateKey::public_key() const {
262 return std::make_unique<Kyber_PublicKey>(*this);
263}
264
268
272
274 // As we do not support loading a private key in extended format but rather
275 // always extract it from a 64-byte seed, these checks (as described in
276 // FIPS 203, Section 7.1) should never fail. Particularly, the length checks
277 // and the hash consistency check described in Section 7.2 and 7.3 are
278 // trivial when the private key is always extracted from a seed. The encaps/
279 // decaps roundtrip test is added for completeness.
280
281 if(!Kyber_PublicKey::check_key(rng, strong)) {
282 return false;
283 }
284
285 PK_KEM_Encryptor enc(*this, "Raw");
286 PK_KEM_Decryptor dec(*this, rng, "Raw");
287
288 const auto [c, K] = KEM_Encapsulation::destructure(enc.encrypt(rng));
289 const auto K_prime = dec.decrypt(c);
290
291 return K == K_prime;
292}
293
294std::unique_ptr<PK_Ops::KEM_Encryption> Kyber_PublicKey::create_kem_encryption_op(std::string_view params,
295 std::string_view provider) const {
296 if(provider.empty() || provider == "base") {
297#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
298 if(mode().is_kyber_round3()) {
299 return std::make_unique<Kyber_KEM_Encryptor>(m_public, params);
300 }
301#endif
302
303#if defined(BOTAN_HAS_ML_KEM)
304 if(mode().is_ml_kem()) {
305 return std::make_unique<ML_KEM_Encryptor>(m_public, params);
306 }
307#endif
308
310 }
311 throw Provider_Not_Found(algo_name(), provider);
312}
313
314std::unique_ptr<PK_Ops::KEM_Decryption> Kyber_PrivateKey::create_kem_decryption_op(RandomNumberGenerator& rng,
315 std::string_view params,
316 std::string_view provider) const {
317 BOTAN_UNUSED(rng);
318 if(provider.empty() || provider == "base") {
319#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
320 if(mode().is_kyber_round3()) {
321 return std::make_unique<Kyber_KEM_Decryptor>(m_private, m_public, params);
322 }
323#endif
324
325#if defined(BOTAN_HAS_ML_KEM)
326 if(mode().is_ml_kem()) {
327 return std::make_unique<ML_KEM_Decryptor>(m_private, m_public, params);
328 }
329#endif
330
332 }
333 throw Provider_Not_Found(algo_name(), provider);
334}
335
337 if(mode().is_ml_kem() && m_private->seed().d.has_value()) {
339 }
341}
342
345 throw Encoding_Error("Expanded private keys do not support the seed format");
346 }
347 const auto codec = [&]() -> std::unique_ptr<Kyber_Keypair_Codec> {
348 switch(format) {
350 return std::make_unique<Seed_Expanding_Keypair_Codec>();
352 return std::make_unique<Expanded_Keypair_Codec>();
353 }
355 }();
356 return codec->encode_keypair({m_public, m_private});
357}
358} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:144
#define BOTAN_ASSERT_UNREACHABLE()
Definition assert.h:166
bool parameters_are_empty() const
Definition asn1_obj.h:715
Codec for expanded private keys (as specified in FIPS 203).
Definition kyber_keys.h:30
KyberInternalKeypair decode_keypair(std::span< const uint8_t > buffer, KyberConstants mode) const override
static std::pair< std::vector< uint8_t >, secure_vector< uint8_t > > destructure(KEM_Encapsulation &&kem)
Definition pubkey.h:588
static constexpr size_t SEED_BYTES
bool is_available() const
Definition kyber.cpp:136
bool is_kyber_round3() const
Definition kyber.cpp:131
std::string to_string() const
Definition kyber.cpp:94
bool is_modern() const
Definition kyber.cpp:123
OID object_identifier() const
Definition kyber.cpp:90
KyberMode(Mode mode)
Definition kyber.cpp:84
bool is_90s() const
Definition kyber.cpp:119
bool is_ml_kem() const
Definition kyber.cpp:127
Mode mode() const
Definition kyber.h:60
MlPrivateKeyFormat private_key_format() const
Definition kyber.cpp:336
secure_vector< uint8_t > private_key_bits_with_format(MlPrivateKeyFormat format) const
Definition kyber.cpp:343
std::unique_ptr< PK_Ops::KEM_Decryption > create_kem_decryption_op(RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition kyber.cpp:314
std::unique_ptr< Public_Key > public_key() const override
Definition kyber.cpp:261
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition kyber.cpp:273
Kyber_PrivateKey(RandomNumberGenerator &rng, KyberMode mode)
Definition kyber.cpp:232
secure_vector< uint8_t > raw_private_key_bits() const override
Definition kyber.cpp:265
secure_vector< uint8_t > private_key_bits() const override
Definition kyber.cpp:269
std::vector< uint8_t > public_key_bits() const override
Definition kyber.cpp:202
std::vector< uint8_t > raw_public_key_bits() const override
Definition kyber.cpp:198
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition kyber.cpp:212
std::string algo_name() const override
Definition kyber.cpp:162
size_t key_length() const override
Definition kyber.cpp:208
AlgorithmIdentifier algorithm_identifier() const override
Definition kyber.cpp:166
std::unique_ptr< PK_Ops::KEM_Encryption > create_kem_encryption_op(std::string_view params, std::string_view provider) const override
Definition kyber.cpp:294
KyberMode mode() const
Definition kyber.cpp:158
std::shared_ptr< const Kyber_PublicKeyInternal > m_public
Definition kyber.h:144
OID object_identifier() const override
Definition kyber.cpp:174
std::unique_ptr< Private_Key > generate_another(RandomNumberGenerator &rng) const final
Definition kyber.cpp:225
Kyber_PublicKey(std::span< const uint8_t > pub_key, KyberMode mode)
Definition kyber.cpp:190
size_t estimated_strength() const override
Definition kyber.cpp:178
static OID from_string(std::string_view str)
Definition asn1_oid.cpp:80
void decrypt(std::span< uint8_t > out_shared_key, std::span< const uint8_t > encap_key, size_t desired_shared_key_len=32, std::span< const uint8_t > salt={})
Definition pubkey.cpp:208
KEM_Encapsulation encrypt(RandomNumberGenerator &rng, size_t desired_shared_key_len=32, std::span< const uint8_t > salt={})
Definition pubkey.h:672
void random_vec(std::span< uint8_t > v)
Definition rng.h:244
Codec for private keys as 64-byte seeds: d || z.
Definition kyber_keys.h:37
KyberInternalKeypair decode_keypair(std::span< const uint8_t > buffer, KyberConstants mode) const override
void encode_polynomial_vector(std::span< uint8_t > out, const KyberPolyVecNTT &vec)
KyberInternalKeypair expand_keypair(KyberPrivateKeySeed seed, KyberConstants mode)
Strong< secure_vector< uint8_t >, struct KyberImplicitRejectionValue_ > KyberImplicitRejectionValue
Secret random value (called Z in the spec), used for implicit rejection in the decapsulation.
Definition kyber_types.h:42
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
MlPrivateKeyFormat
Byte encoding format of ML-KEM and ML-DSA the private key.
Definition kyber.h:81
@ Expanded
The expanded format, i.e., the format specified in FIPS-203/204.
Definition kyber.h:88
BOTAN_FORCE_INLINE constexpr T rho(T x)
Definition rotate.h:53
Strong< secure_vector< uint8_t >, struct KyberSeedRandomness_ > KyberSeedRandomness
Principal seed used to generate Kyber key pairs.
Definition kyber_types.h:33
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
Strong< std::vector< uint8_t >, struct KyberSerializedPublicKey_ > KyberSerializedPublicKey
Public key in serialized form (t || rho).
Definition kyber_types.h:57