Botan 3.14.1
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#include <botan/internal/pk_options_impl.h>
27
28#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
29 #include <botan/internal/kyber_round3_impl.h>
30#endif
31
32#if defined(BOTAN_HAS_ML_KEM)
33 #include <botan/internal/ml_kem_impl.h>
34#endif
35
36#include <memory>
37#include <vector>
38
39namespace Botan {
40
41namespace {
42
43KyberMode::Mode kyber_mode_from_string(std::string_view str) {
44 if(str == "Kyber-512-90s-r3") {
46 }
47 if(str == "Kyber-768-90s-r3") {
49 }
50 if(str == "Kyber-1024-90s-r3") {
52 }
53 if(str == "Kyber-512-r3") {
55 }
56 if(str == "Kyber-768-r3") {
58 }
59 if(str == "Kyber-1024-r3") {
61 }
62 if(str == "ML-KEM-512") {
64 }
65 if(str == "ML-KEM-768") {
67 }
68 if(str == "ML-KEM-1024") {
70 }
71
72 throw Invalid_Argument(fmt("'{}' is not a valid Kyber mode name", str));
73}
74
75KyberMode::Mode kyber_mode_from_oid(const OID& oid) {
76 if(const auto name = oid.registered_name()) {
77 return kyber_mode_from_string(*name);
78 }
79
80 throw Invalid_Argument(fmt("OID '{}' is not registered as a Kyber/ML-KEM mode", oid));
81}
82
83} // namespace
84
86
87KyberMode::KyberMode(const OID& oid) : m_mode(kyber_mode_from_oid(oid)) {}
88
89KyberMode::KyberMode(std::string_view str) : m_mode(kyber_mode_from_string(str)) {}
90
94
95std::string KyberMode::to_string() const {
96 switch(m_mode) {
97 case Kyber512_90s:
98 return "Kyber-512-90s-r3";
99 case Kyber768_90s:
100 return "Kyber-768-90s-r3";
101 case Kyber1024_90s:
102 return "Kyber-1024-90s-r3";
103 case Kyber512_R3:
104 return "Kyber-512-r3";
105 case Kyber768_R3:
106 return "Kyber-768-r3";
107 case Kyber1024_R3:
108 return "Kyber-1024-r3";
109 case ML_KEM_512:
110 return "ML-KEM-512";
111 case ML_KEM_768:
112 return "ML-KEM-768";
113 case ML_KEM_1024:
114 return "ML-KEM-1024";
115 }
116
118}
119
120bool KyberMode::is_90s() const {
121 return m_mode == Kyber512_90s || m_mode == Kyber768_90s || m_mode == Kyber1024_90s;
122}
123
125 return !is_90s();
126}
127
129 return m_mode == KyberMode::ML_KEM_512 || m_mode == KyberMode::ML_KEM_768 || m_mode == KyberMode::ML_KEM_1024;
130}
131
133 return m_mode == KyberMode::Kyber512_R3 || m_mode == KyberMode::Kyber768_R3 || m_mode == KyberMode::Kyber1024_R3 ||
135}
136
138#if defined(BOTAN_HAS_KYBER)
139 if(is_kyber_round3() && is_modern()) {
140 return true;
141 }
142#endif
143
144#if defined(BOTAN_HAS_KYBER_90S)
145 if(is_kyber_round3() && is_90s()) {
146 return true;
147 }
148#endif
149
150#if defined(BOTAN_HAS_ML_KEM)
151 if(is_ml_kem()) {
152 return true;
153 }
154#endif
155
156 return false;
157}
158
160 return m_public->mode().mode();
161}
162
163std::string Kyber_PublicKey::algo_name() const {
164 return mode().is_ml_kem() ? "ML-KEM" : "Kyber";
165}
166
168 // draft-ietf-lamps-kyber-certificates-latest (22 July 2024) The
169 // AlgorithmIdentifier for a ML-KEM public key MUST use one of the
170 // id-alg-ml-kem object identifiers [...]. The parameters field of the
171 // AlgorithmIdentifier for the ML-KEM public key MUST be absent.
173}
174
178
180 return m_public->mode().estimated_strength();
181}
182
183Kyber_PublicKey::Kyber_PublicKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) :
184 Kyber_PublicKey(key_bits, KyberMode(alg_id.oid())) {
185 // The parameter set is identified by the OID; no parameters are defined.
186 if(!alg_id.parameters_are_empty()) {
187 throw Decoding_Error("Unexpected parameters for ML-KEM/Kyber public key");
188 }
189}
190
191Kyber_PublicKey::Kyber_PublicKey(std::span<const uint8_t> pub_key, KyberMode mode) {
192 m_public = std::make_shared<Kyber_PublicKeyInternal>(mode, KyberSerializedPublicKey(pub_key));
193}
194
196 m_public(std::make_shared<Kyber_PublicKeyInternal>(
197 other.m_public->mode(), other.m_public->t().clone(), other.m_public->rho())) {}
198
199std::vector<uint8_t> Kyber_PublicKey::raw_public_key_bits() const {
200 return m_public->public_key_bits_raw().get();
201}
202
203std::vector<uint8_t> Kyber_PublicKey::public_key_bits() const {
204 // Currently, there isn't a finalized definition of an ASN.1 structure for
205 // Kyber aka ML-KEM public keys. Therefore, we return the raw public key bits.
206 return raw_public_key_bits();
207}
208
210 return m_public->mode().canonical_parameter_set_identifier();
211}
212
213bool Kyber_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*strong*/) const {
214 // Every possible check (length, coefficient range of t) is already performed
215 // when the key is decoded; see Kyber_PublicKeyInternal.
216 return true;
217}
218
219std::unique_ptr<Private_Key> Kyber_PublicKey::generate_another(RandomNumberGenerator& rng) const {
220 return std::make_unique<Kyber_PrivateKey>(rng, mode());
221}
222
223/**
224 * NIST FIPS 203, Algorithms 19 (ML-KEM.KeyGen)
225 */
233
234Kyber_PrivateKey::Kyber_PrivateKey(const AlgorithmIdentifier& alg_id, std::span<const uint8_t> key_bits) :
235 Kyber_PrivateKey(key_bits, KyberMode(alg_id.oid())) {
236 // The parameter set is identified by the OID; no parameters are defined.
237 if(!alg_id.parameters_are_empty()) {
238 throw Decoding_Error("Unexpected parameters for ML-KEM/Kyber private key");
239 }
240}
241
242Kyber_PrivateKey::Kyber_PrivateKey(std::span<const uint8_t> sk, KyberMode m) :
243 m_private_key_format(MlPrivateKeyFormat::Expanded) {
245
246 if(mode.mode().is_ml_kem()) {
247 auto decoded = decode_ml_kem_private_key(sk, std::move(mode));
248 m_public = std::move(decoded.keypair.first);
249 m_private = std::move(decoded.keypair.second);
250 m_private_key_format = decoded.format;
251 } else if(sk.size() == mode.expanded_private_key_bytes()) {
252 std::tie(m_public, m_private) = Expanded_Keypair_Codec().decode_keypair(sk, std::move(mode));
253 } else if(sk.size() == mode.seed_private_key_bytes()) {
254 throw Decoding_Error("Kyber round 3 private keys do not support the seed format");
255 } else {
256 throw Decoding_Error("Private key does not have the correct byte count");
257 }
258}
259
260std::unique_ptr<Public_Key> Kyber_PrivateKey::public_key() const {
261 return std::make_unique<Kyber_PublicKey>(*this);
262}
263
265 // The expanded encoding embeds ek and H(ek); their lengths, the coefficient
266 // ranges and the hash are all verified when the key is decoded. Both ML-KEM
267 // and Kyber round 3 also perform a pairwise consistency check during decoding.
268 // The strong check below performs an additional encaps/decaps round trip.
269
270 if(!Kyber_PublicKey::check_key(rng, strong)) {
271 return false;
272 }
273
274 if(!strong) {
275 return true;
276 }
277
278 PK_KEM_Encryptor enc(*this, "Raw");
279 PK_KEM_Decryptor dec(*this, rng, "Raw");
280
281 const auto [c, K] = KEM_Encapsulation::destructure(enc.encrypt(rng));
282 const auto K_prime = dec.decrypt(c);
283
284 return K == K_prime;
285}
286
287std::unique_ptr<PK_Ops::KEM_Encryption> Kyber_PublicKey::_create_kem_encryption_op(
288 const PK_KEM_Options_Reader& options) const {
290
291#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
292 if(mode().is_kyber_round3()) {
293 return std::make_unique<Kyber_KEM_Encryptor>(m_public, options);
294 }
295#endif
296
297#if defined(BOTAN_HAS_ML_KEM)
298 if(mode().is_ml_kem()) {
299 return std::make_unique<ML_KEM_Encryptor>(m_public, options);
300 }
301#endif
302
304}
305
306std::unique_ptr<PK_Ops::KEM_Decryption> Kyber_PrivateKey::_create_kem_decryption_op(
307 RandomNumberGenerator& rng, const PK_KEM_Options_Reader& options) const {
308 BOTAN_UNUSED(rng);
310
311#if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S)
312 if(mode().is_kyber_round3()) {
313 return std::make_unique<Kyber_KEM_Decryptor>(m_private, m_public, options);
314 }
315#endif
316
317#if defined(BOTAN_HAS_ML_KEM)
318 if(mode().is_ml_kem()) {
319 return std::make_unique<ML_KEM_Decryptor>(m_private, m_public, options);
320 }
321#endif
322
324}
325
327 return m_private_key_format;
328}
329
331 switch(format) {
333 if(mode().is_kyber_round3()) {
334 throw Encoding_Error("Kyber round 3 private keys only support the expanded format");
335 }
336 if(!m_private->seed().d.has_value()) {
337 throw Encoding_Error("Expanded private keys do not support the seed format");
338 }
341 return Expanded_Keypair_Codec().encode_keypair({m_public, m_private});
343 throw Encoding_Error(
344 "there is no raw encoding of an ML-KEM private key containing both seed and expanded key");
345 }
347}
348
350 if(mode().is_ml_kem()) {
351 return encode_ml_kem_private_key({m_public, m_private}, format);
352 }
353 // Kyber round 3 has no ASN.1 wrapping, the raw expanded key is the PKCS#8 content
354 if(format != MlPrivateKeyFormat::Expanded) {
355 throw Encoding_Error("Kyber round 3 private keys only support the expanded format");
356 }
357 return formatted_raw_private_key_bits(format);
358}
359
360} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_UNREACHABLE()
Definition assert.h:173
bool parameters_are_empty() const
Definition asn1_obj.h:715
Codec for expanded private keys (as specified in FIPS 203).
Definition kyber_keys.h:31
secure_vector< uint8_t > encode_keypair(KyberInternalKeypair private_key) const override
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:654
static constexpr size_t SEED_BYTES
bool is_available() const
Definition kyber.cpp:137
bool is_kyber_round3() const
Definition kyber.cpp:132
std::string to_string() const
Definition kyber.cpp:95
bool is_modern() const
Definition kyber.cpp:124
OID object_identifier() const
Definition kyber.cpp:91
KyberMode(Mode mode)
Definition kyber.cpp:85
bool is_90s() const
Definition kyber.cpp:120
bool is_ml_kem() const
Definition kyber.cpp:128
Mode mode() const
Definition kyber.h:61
std::unique_ptr< PK_Ops::KEM_Decryption > _create_kem_decryption_op(RandomNumberGenerator &rng, const PK_KEM_Options_Reader &options) const override
Definition kyber.cpp:306
secure_vector< uint8_t > formatted_private_key_bits(MlPrivateKeyFormat format) const override
Definition kyber.cpp:349
std::unique_ptr< Public_Key > public_key() const override
Definition kyber.cpp:260
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition kyber.cpp:264
Kyber_PrivateKey(RandomNumberGenerator &rng, KyberMode mode)
Definition kyber.cpp:226
MlPrivateKeyFormat private_key_format() const override
Definition kyber.cpp:326
secure_vector< uint8_t > formatted_raw_private_key_bits(MlPrivateKeyFormat format) const override
Definition kyber.cpp:330
std::vector< uint8_t > public_key_bits() const override
Definition kyber.cpp:203
std::vector< uint8_t > raw_public_key_bits() const override
Definition kyber.cpp:199
bool check_key(RandomNumberGenerator &rng, bool strong) const override
Definition kyber.cpp:213
std::string algo_name() const override
Definition kyber.cpp:163
size_t key_length() const override
Definition kyber.cpp:209
AlgorithmIdentifier algorithm_identifier() const override
Definition kyber.cpp:167
KyberMode mode() const
Definition kyber.cpp:159
std::shared_ptr< const Kyber_PublicKeyInternal > m_public
Definition kyber.h:134
OID object_identifier() const override
Definition kyber.cpp:175
std::unique_ptr< Private_Key > generate_another(RandomNumberGenerator &rng) const final
Definition kyber.cpp:219
Kyber_PublicKey(std::span< const uint8_t > pub_key, KyberMode mode)
Definition kyber.cpp:191
std::unique_ptr< PK_Ops::KEM_Encryption > _create_kem_encryption_op(const PK_KEM_Options_Reader &options) const override
Definition kyber.cpp:287
size_t estimated_strength() const override
Definition kyber.cpp:179
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:255
KEM_Encapsulation encrypt(RandomNumberGenerator &rng, size_t desired_shared_key_len=32, std::span< const uint8_t > salt={})
Definition pubkey.h:745
void random_vec(std::span< uint8_t > v)
Definition rng.h:254
Codec for private keys as 64-byte seeds: d || z.
Definition kyber_keys.h:38
secure_vector< uint8_t > encode_keypair(KyberInternalKeypair keypair) const override
const char * name
Definition ffi_tls.h:59
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
KyberDecodedKeypair decode_ml_kem_private_key(std::span< const uint8_t > private_key, KyberConstants mode)
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
secure_vector< uint8_t > encode_ml_kem_private_key(const KyberInternalKeypair &keypair, MlPrivateKeyFormat format)
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
void require_software_provider(const OptionsT &options, std::string_view algo_name)
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