Coverage Report

Created: 2026-10-31 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/hpke/hpke.cc
Line
Count
Source
1
// Copyright 2020 The BoringSSL Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <openssl/hpke.h>
16
17
#include <assert.h>
18
#include <string.h>
19
20
#include <array>
21
#include <optional>
22
#include <string_view>
23
24
#include <openssl/aead.h>
25
#include <openssl/bytestring.h>
26
#include <openssl/curve25519.h>
27
#include <openssl/digest.h>
28
#include <openssl/ec.h>
29
#include <openssl/ec_key.h>
30
#include <openssl/err.h>
31
#include <openssl/evp.h>
32
#include <openssl/evp_errors.h>
33
#include <openssl/hkdf.h>
34
#include <openssl/mem.h>
35
#include <openssl/mlkem.h>
36
#include <openssl/sha2.h>
37
#include <openssl/span.h>
38
#include <openssl/xwing.h>
39
40
#include "../evp/internal.h"
41
#include "../fipsmodule/ec/internal.h"
42
#include "../fipsmodule/keccak/internal.h"
43
#include "../internal.h"
44
#include "../mem_internal.h"
45
46
47
using namespace bssl;
48
49
// This file implements RFC 9180.
50
51
#define MAX_SHARED_SECRET_LEN SHA256_DIGEST_LENGTH
52
#define MAX_DHKEM_DH_SHARED_KEY_LEN X25519_SHARED_KEY_LEN
53
#define MAX_DHKEM_PUBLIC_KEY_LEN 65  // kP256PublicValueLen
54
55
namespace {
56
57
// HpkeKeyMethod implements the key-type-specific operations that HPKE performs
58
// on keys of a particular `EVP_PKEY_ALG` type.
59
struct HpkeKeyMethod {
60
  // hpke_kem_id is the ID of the KEM in RFC 9180.
61
  uint16_t hpke_kem_id;
62
63
  // public_key_len corresponds to Npk in RFC 9180.
64
  size_t public_key_len;
65
  // private_key_len corresponds to Nsk in RFC 9180.
66
  size_t private_key_len;
67
68
  const EVP_PKEY_ALG *(*alg_func)();
69
70
  // deserialize_private_key and serialize_private_key implement the
71
  // DeserializePrivateKey and SerializePrivateKey operations for the key type
72
  // from section 4 of RFC 9180, using the same format accepted by
73
  // `EVP_HPKE_KEY_init`.
74
  EVP_PKEY *(*deserialize_private_key)(const EVP_PKEY_ALG *alg,
75
                                       const uint8_t *in, size_t len);
76
  int (*serialize_private_key)(const EVP_PKEY *pkey, uint8_t *out,
77
                               size_t *out_len);
78
79
  // deserialize_public_key and serialize_public_key implement the
80
  // DeserializePublicKey and SerializePublicKey operations from section 4 of
81
  // RFC 9180.
82
  EVP_PKEY *(*deserialize_public_key)(const EVP_PKEY_ALG *alg,
83
                                      const uint8_t *in, size_t len);
84
  int (*serialize_public_key)(const EVP_PKEY *pkey, uint8_t *out,
85
                              size_t *out_len);
86
87
  // derive_key_pair implements the DeriveKeyPair operation from section 4 of
88
  // RFC 9180.
89
  EVP_PKEY *(*derive_key_pair)(const EVP_PKEY_ALG *alg, uint16_t kem_suite_id,
90
                               Span<const uint8_t> ikm);
91
};
92
93
// EVP_KEM_DHKEM implements the DHKEM construction from RFC 9180 based on a
94
// DH group and an HKDF.
95
//
96
// In DHKEM, the encapsulated key is the serialized ephemeral public key, so
97
// Nenc (`ciphertext_len`) equals Npk (`public_key_len`).
98
struct EVP_KEM_DHKEM : public EVP_KEM {
99
  // dh_shared_key_len corresponds to Ndh in RFC 9180.
100
  size_t dh_shared_key_len;
101
102
  const HpkeKeyMethod *key_method;
103
  const EVP_MD *(*hkdf_digest_func)();
104
105
  // Generates the ephemeral encapsulation key from external entropy bytes
106
  // provided as a "seed" for testing. The seed's format is variant-specific.
107
  EVP_PKEY *(*key_from_encap_entropy)(const EVP_PKEY_ALG *alg,
108
                                      const uint8_t *in, size_t len);
109
};
110
111
}  // namespace
112
113
struct evp_hpke_kem_st {
114
  uint16_t id;
115
116
  const EVP_KEM *(*evp_kem_func)();
117
  const HpkeKeyMethod *key_method;
118
119
  int (*auth_encap)(const EVP_KEM *kem, Span<uint8_t> out_ciphertext,
120
                    Span<uint8_t> out_secret, const EVP_PKEY *peer_key,
121
                    const EVP_PKEY *auth_key);
122
  int (*auth_encap_external_entropy)(const EVP_KEM *kem,
123
                                     Span<uint8_t> out_ciphertext,
124
                                     Span<uint8_t> out_secret,
125
                                     const EVP_PKEY *peer_key,
126
                                     const EVP_PKEY *auth_key,
127
                                     Span<const uint8_t> entropy);
128
  int (*auth_decap)(const EVP_KEM *kem, Span<uint8_t> out_secret,
129
                    Span<const uint8_t> ciphertext, const EVP_PKEY *key,
130
                    const EVP_PKEY *auth_key);
131
};
132
133
struct evp_hpke_kdf_st {
134
  uint16_t id;
135
  // We only support HKDF-based KDFs.
136
  const EVP_MD *(*hkdf_md_func)();
137
};
138
139
struct evp_hpke_aead_st {
140
  uint16_t id;
141
  const EVP_AEAD *(*aead_func)();
142
};
143
144
namespace {
145
146
// Low-level labeled KDF functions.
147
148
const char kHpkeVersionId[] = "HPKE-v1";
149
150
4.64k
int add_label_string(CBB *cbb, const char *label) {
151
4.64k
  return CBB_add_bytes(cbb, (const uint8_t *)label, strlen(label));
152
4.64k
}
153
154
int hpke_labeled_extract(const EVP_MD *hkdf_md, uint8_t *out_key,
155
                         size_t *out_len, const uint8_t *salt, size_t salt_len,
156
                         const uint8_t *suite_id, size_t suite_id_len,
157
                         const char *label, const uint8_t *ikm,
158
1.16k
                         size_t ikm_len) {
159
  // labeledIKM = concat("HPKE-v1", suite_id, label, IKM)
160
1.16k
  CBB labeled_ikm;
161
1.16k
  int ok = CBB_init(&labeled_ikm, 0) &&
162
1.16k
           add_label_string(&labeled_ikm, kHpkeVersionId) &&
163
1.16k
           CBB_add_bytes(&labeled_ikm, suite_id, suite_id_len) &&
164
1.16k
           add_label_string(&labeled_ikm, label) &&
165
1.16k
           CBB_add_bytes(&labeled_ikm, ikm, ikm_len) &&
166
1.16k
           HKDF_extract(out_key, out_len, hkdf_md, CBB_data(&labeled_ikm),
167
1.16k
                        CBB_len(&labeled_ikm), salt, salt_len);
168
1.16k
  CBB_cleanup(&labeled_ikm);
169
1.16k
  return ok;
170
1.16k
}
171
172
int hpke_labeled_expand(const EVP_MD *hkdf_md, uint8_t *out_key, size_t out_len,
173
                        const uint8_t *prk, size_t prk_len,
174
                        const uint8_t *suite_id, size_t suite_id_len,
175
                        const char *label, const uint8_t *info,
176
1.16k
                        size_t info_len) {
177
  // labeledInfo = concat(I2OSP(L, 2), "HPKE-v1", suite_id, label, info)
178
1.16k
  CBB labeled_info;
179
1.16k
  int ok = CBB_init(&labeled_info, 0) &&  //
180
1.16k
           CBB_add_u16(&labeled_info, out_len) &&
181
1.16k
           add_label_string(&labeled_info, kHpkeVersionId) &&
182
1.16k
           CBB_add_bytes(&labeled_info, suite_id, suite_id_len) &&
183
1.16k
           add_label_string(&labeled_info, label) &&
184
1.16k
           CBB_add_bytes(&labeled_info, info, info_len) &&
185
1.16k
           HKDF_expand(out_key, out_len, hkdf_md, prk, prk_len,
186
1.16k
                       CBB_data(&labeled_info), CBB_len(&labeled_info));
187
1.16k
  CBB_cleanup(&labeled_info);
188
1.16k
  return ok;
189
1.16k
}
190
191
0
void absorb_u16(BORINGSSL_keccak_st *ctx, uint16_t n) {
192
0
  uint8_t bytes[2];
193
0
  CRYPTO_store_u16_be(bytes, n);
194
0
  BORINGSSL_keccak_absorb(ctx, bytes, sizeof(bytes));
195
0
}
196
197
void hpke_shake256_labeled_derive(Span<uint8_t> out, Span<const uint8_t> ikm,
198
                                  Span<const uint8_t> suite_id,
199
                                  std::string_view label,
200
0
                                  Span<const uint8_t> context) {
201
  // https://www.ietf.org/archive/id/draft-ietf-hpke-hpke-03.html#name-labeled-derivation-function
202
  // https://www.ietf.org/archive/id/draft-ietf-hpke-pq-04.html#name-single-stage-kdfs
203
0
  BORINGSSL_keccak_st ctx;
204
0
  BORINGSSL_keccak_init(&ctx, boringssl_shake256);
205
0
  BORINGSSL_keccak_absorb(&ctx, ikm.data(), ikm.size());
206
0
  auto hpke_version_id = StringAsBytes(kHpkeVersionId);
207
0
  BORINGSSL_keccak_absorb(&ctx, hpke_version_id.data(), hpke_version_id.size());
208
0
  BORINGSSL_keccak_absorb(&ctx, suite_id.data(), suite_id.size());
209
0
  auto label_bytes = StringAsBytes(label);
210
0
  assert(label_bytes.size() < 0xffff);
211
0
  absorb_u16(&ctx, static_cast<uint16_t>(label_bytes.size()));
212
0
  BORINGSSL_keccak_absorb(&ctx, label_bytes.data(), label_bytes.size());
213
0
  assert(out.size() <= 0xffff);
214
0
  absorb_u16(&ctx, static_cast<uint16_t>(out.size()));
215
0
  BORINGSSL_keccak_absorb(&ctx, context.data(), context.size());
216
0
  BORINGSSL_keccak_squeeze(&ctx, out.data(), out.size());
217
0
}
218
219
220
// KEM implementations.
221
222
290
std::array<uint8_t, 5> hpke_kem_suite_id(uint16_t kem_id) {
223
  // concat("KEM", I2OSP(kem_id, 2))
224
290
  return {'K', 'E', 'M', static_cast<uint8_t>(kem_id >> 8),
225
290
          static_cast<uint8_t>(kem_id)};
226
290
}
227
228
// dhkem_extract_and_expand implements the ExtractAndExpand operation in the
229
// DHKEM construction. See section 4.1 of RFC 9180.
230
int dhkem_extract_and_expand(uint16_t kem_id, const EVP_MD *hkdf_md,
231
                             uint8_t *out_key, size_t out_len,
232
                             const uint8_t *dh, size_t dh_len,
233
                             const uint8_t *kem_context,
234
290
                             size_t kem_context_len) {
235
290
  auto suite_id = hpke_kem_suite_id(kem_id);
236
290
  uint8_t prk[EVP_MAX_MD_SIZE];
237
290
  size_t prk_len;
238
290
  return hpke_labeled_extract(hkdf_md, prk, &prk_len, nullptr, 0,
239
290
                              suite_id.data(), suite_id.size(), "eae_prk", dh,
240
290
                              dh_len) &&
241
290
         hpke_labeled_expand(hkdf_md, out_key, out_len, prk, prk_len,
242
290
                             suite_id.data(), suite_id.size(), "shared_secret",
243
290
                             kem_context, kem_context_len);
244
290
}
245
246
bool dhkem_dh(const EVP_KEM_DHKEM *dhkem, Span<uint8_t> out,
247
293
              const EVP_PKEY *key, const EVP_PKEY *peer) {
248
293
  assert(out.size() == dhkem->dh_shared_key_len);
249
293
  UniquePtr<EVP_PKEY_CTX> pkctx(EVP_PKEY_CTX_new(key, nullptr));
250
293
  if (pkctx == nullptr) {
251
0
    return false;
252
0
  }
253
293
  size_t out_len = out.size();
254
293
  return EVP_PKEY_derive_init(pkctx.get()) &&
255
293
         EVP_PKEY_derive_set_peer(pkctx.get(), peer) &&
256
293
         EVP_PKEY_derive(pkctx.get(), out.data(), &out_len) &&
257
290
         out_len == dhkem->dh_shared_key_len;
258
293
}
259
260
bool dhkem_serialize_public_key(const EVP_KEM_DHKEM *dhkem, Span<uint8_t> out,
261
290
                                const EVP_PKEY *key) {
262
290
  if (out.size() != dhkem->key_method->public_key_len) {
263
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
264
0
    return false;
265
0
  }
266
290
  size_t serialized_len = out.size();
267
290
  if (!dhkem->key_method->serialize_public_key(key, out.data(),
268
290
                                               &serialized_len)) {
269
0
    return false;
270
0
  }
271
290
  BSSL_CHECK(serialized_len == out.size());
272
290
  return true;
273
290
}
274
275
bool dhkem_serialize_public_keys(const EVP_KEM_DHKEM *dhkem, Span<uint8_t> out,
276
0
                                 const EVP_PKEY *key1, const EVP_PKEY *key2) {
277
0
  const size_t public_len = dhkem->key_method->public_key_len;
278
0
  if (out.size() != 2 * dhkem->key_method->public_key_len) {
279
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
280
0
    return false;
281
0
  }
282
0
  return dhkem_serialize_public_key(dhkem, out.subspan(0, public_len), key1) &&
283
0
         dhkem_serialize_public_key(dhkem, out.subspan(public_len), key2);
284
0
}
285
286
bool dhkem_serialize_public_keys(const EVP_KEM_DHKEM *dhkem, Span<uint8_t> out,
287
                                 const EVP_PKEY *key1, const EVP_PKEY *key2,
288
0
                                 const EVP_PKEY *key3) {
289
0
  const size_t public_len = dhkem->key_method->public_key_len;
290
0
  if (out.size() != 3 * public_len) {
291
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
292
0
    return false;
293
0
  }
294
0
  return dhkem_serialize_public_key(dhkem, out.subspan(0, public_len), key1) &&
295
0
         dhkem_serialize_public_keys(dhkem, out.subspan(public_len), key2,
296
0
                                     key3);
297
0
}
298
299
int dhkem_encap_with_ephemeral_key(const EVP_KEM_DHKEM *dhkem,
300
                                   Span<uint8_t> out_ciphertext,
301
                                   Span<uint8_t> out_secret,
302
                                   const EVP_PKEY *peer_key,
303
0
                                   const EVP_PKEY *ephemeral_key) {
304
0
  const size_t public_len = dhkem->key_method->public_key_len;
305
0
  if (out_ciphertext.size() != public_len) {
306
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH);
307
0
    return 0;
308
0
  }
309
0
  if (out_secret.size() != dhkem->secret_len) {
310
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH);
311
0
    return 0;
312
0
  }
313
  // dh = DH(skE, pkR)
314
0
  InplaceVector<uint8_t, MAX_DHKEM_DH_SHARED_KEY_LEN> dh;
315
0
  if (!dh.TryResizeForOverwrite(dhkem->dh_shared_key_len) ||
316
0
      !dhkem_dh(dhkem, Span(dh), ephemeral_key, peer_key)) {
317
0
    return 0;
318
0
  }
319
  // enc = SerializePublicKey(pkE)
320
  // pkRm = SerializePublicKey(pkR)
321
  // kem_context = concat(enc, pkRm)
322
0
  InplaceVector<uint8_t, 2 * MAX_DHKEM_PUBLIC_KEY_LEN> kem_context;
323
0
  if (!kem_context.TryResizeForOverwrite(2 * public_len) ||
324
0
      !dhkem_serialize_public_keys(dhkem, Span(kem_context), ephemeral_key,
325
0
                                   peer_key)) {
326
0
    return 0;
327
0
  }
328
0
  OPENSSL_memcpy(out_ciphertext.data(), kem_context.data(), public_len);
329
  // shared_secret = ExtractAndExpand(dh, kem_context)
330
0
  return dhkem_extract_and_expand(dhkem->key_method->hpke_kem_id,
331
0
                                  dhkem->hkdf_digest_func(), out_secret.data(),
332
0
                                  out_secret.size(), dh.data(), dh.size(),
333
0
                                  kem_context.data(), kem_context.size());
334
0
}
335
336
int dhkem_encap(const EVP_KEM *kem, Span<uint8_t> out_ciphertext,
337
0
                Span<uint8_t> out_secret, const EVP_PKEY *peer_key) {
338
0
  const auto *dhkem = static_cast<const EVP_KEM_DHKEM *>(kem);
339
0
  UniquePtr<EVP_PKEY> ephemeral_key(
340
0
      EVP_PKEY_generate_from_alg(dhkem->key_method->alg_func()));
341
0
  if (ephemeral_key == nullptr) {
342
0
    return 0;
343
0
  }
344
0
  return dhkem_encap_with_ephemeral_key(dhkem, out_ciphertext, out_secret,
345
0
                                        peer_key, ephemeral_key.get());
346
0
}
347
348
int dhkem_encap_external_entropy(const EVP_KEM *kem,
349
                                 Span<uint8_t> out_ciphertext,
350
                                 Span<uint8_t> out_secret,
351
                                 const EVP_PKEY *peer_key,
352
0
                                 Span<const uint8_t> entropy) {
353
0
  const auto *dhkem = static_cast<const EVP_KEM_DHKEM *>(kem);
354
0
  UniquePtr<EVP_PKEY> ephemeral_key(dhkem->key_from_encap_entropy(
355
0
      dhkem->key_method->alg_func(), entropy.data(), entropy.size()));
356
0
  if (ephemeral_key == nullptr) {
357
0
    return 0;
358
0
  }
359
0
  return dhkem_encap_with_ephemeral_key(dhkem, out_ciphertext, out_secret,
360
0
                                        peer_key, ephemeral_key.get());
361
0
}
362
363
int dhkem_decap(const EVP_KEM *kem, Span<uint8_t> out_secret,
364
303
                Span<const uint8_t> ciphertext, const EVP_PKEY *key) {
365
303
  const auto *dhkem = static_cast<const EVP_KEM_DHKEM *>(kem);
366
303
  const size_t public_len = dhkem->key_method->public_key_len;
367
303
  if (ciphertext.size() != public_len) {
368
10
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH);
369
10
    return 0;
370
10
  }
371
293
  if (out_secret.size() != dhkem->secret_len) {
372
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH);
373
0
    return 0;
374
0
  }
375
  // pkE = DeserializePublicKey(enc)
376
293
  UniquePtr<EVP_PKEY> ephemeral_key(dhkem->key_method->deserialize_public_key(
377
293
      dhkem->key_method->alg_func(), ciphertext.data(), ciphertext.size()));
378
293
  if (ephemeral_key == nullptr) {
379
0
    return 0;
380
0
  }
381
  // dh = DH(skR, pkE)
382
293
  InplaceVector<uint8_t, MAX_DHKEM_DH_SHARED_KEY_LEN> dh;
383
293
  if (!dh.TryResizeForOverwrite(dhkem->dh_shared_key_len) ||
384
293
      !dhkem_dh(dhkem, Span(dh), key, ephemeral_key.get())) {
385
3
    return 0;
386
3
  }
387
  // pkRm = SerializePublicKey(pk(skR))
388
  // kem_context = concat(enc, pkRm)
389
290
  InplaceVector<uint8_t, 2 * MAX_DHKEM_PUBLIC_KEY_LEN> kem_context;
390
290
  if (!kem_context.TryResizeForOverwrite(2 * public_len) ||
391
290
      !dhkem_serialize_public_key(dhkem, Span(kem_context).subspan(public_len),
392
290
                                  key)) {
393
0
    return 0;
394
0
  }
395
290
  OPENSSL_memcpy(kem_context.data(), ciphertext.data(), ciphertext.size());
396
  // shared_secret = ExtractAndExpand(dh, kem_context)
397
290
  return dhkem_extract_and_expand(dhkem->key_method->hpke_kem_id,
398
290
                                  dhkem->hkdf_digest_func(), out_secret.data(),
399
290
                                  out_secret.size(), dh.data(), dh.size(),
400
290
                                  kem_context.data(), kem_context.size());
401
290
}
402
403
int dhkem_auth_encap_with_ephemeral_key(const EVP_KEM_DHKEM *dhkem,
404
                                        Span<uint8_t> out_ciphertext,
405
                                        Span<uint8_t> out_secret,
406
                                        const EVP_PKEY *peer_key,
407
                                        const EVP_PKEY *auth_key,
408
0
                                        const EVP_PKEY *ephemeral_key) {
409
0
  const size_t public_len = dhkem->key_method->public_key_len;
410
0
  if (out_ciphertext.size() != public_len) {
411
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH);
412
0
    return 0;
413
0
  }
414
0
  if (out_secret.size() != dhkem->secret_len) {
415
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH);
416
0
    return 0;
417
0
  }
418
  // dh = concat(DH(skE, pkR), DH(skS, pkR))
419
0
  InplaceVector<uint8_t, 2 * MAX_DHKEM_DH_SHARED_KEY_LEN> dh;
420
0
  if (!dh.TryResizeForOverwrite(2 * dhkem->dh_shared_key_len) ||
421
0
      !dhkem_dh(dhkem, Span(dh).subspan(0, dhkem->dh_shared_key_len),
422
0
                ephemeral_key, peer_key) ||
423
0
      !dhkem_dh(dhkem, Span(dh).subspan(dhkem->dh_shared_key_len), auth_key,
424
0
                peer_key)) {
425
0
    return 0;
426
0
  }
427
  // enc = SerializePublicKey(pkE)
428
  // pkRm = SerializePublicKey(pkR)
429
  // pkSm = SerializePublicKey(pk(skS))
430
  // kem_context = concat(enc, pkRm, pkSm)
431
0
  InplaceVector<uint8_t, 3 * MAX_DHKEM_PUBLIC_KEY_LEN> kem_context;
432
0
  if (!kem_context.TryResizeForOverwrite(3 * public_len) ||
433
0
      !dhkem_serialize_public_keys(dhkem, Span(kem_context), ephemeral_key,
434
0
                                   peer_key, auth_key)) {
435
0
    return 0;
436
0
  }
437
0
  OPENSSL_memcpy(out_ciphertext.data(), kem_context.data(), public_len);
438
  // shared_secret = ExtractAndExpand(dh, kem_context)
439
0
  return dhkem_extract_and_expand(dhkem->key_method->hpke_kem_id,
440
0
                                  dhkem->hkdf_digest_func(), out_secret.data(),
441
0
                                  out_secret.size(), dh.data(), dh.size(),
442
0
                                  kem_context.data(), kem_context.size());
443
0
}
444
445
int dhkem_auth_encap(const EVP_KEM *kem, Span<uint8_t> out_ciphertext,
446
                     Span<uint8_t> out_secret, const EVP_PKEY *peer_key,
447
0
                     const EVP_PKEY *auth_key) {
448
0
  const auto *dhkem = static_cast<const EVP_KEM_DHKEM *>(kem);
449
0
  UniquePtr<EVP_PKEY> ephemeral_key(
450
0
      EVP_PKEY_generate_from_alg(dhkem->key_method->alg_func()));
451
0
  if (ephemeral_key == nullptr) {
452
0
    return 0;
453
0
  }
454
0
  return dhkem_auth_encap_with_ephemeral_key(dhkem, out_ciphertext, out_secret,
455
0
                                             peer_key, auth_key,
456
0
                                             ephemeral_key.get());
457
0
}
458
459
int dhkem_auth_encap_external_entropy(const EVP_KEM *kem,
460
                                      Span<uint8_t> out_ciphertext,
461
                                      Span<uint8_t> out_secret,
462
                                      const EVP_PKEY *peer_key,
463
                                      const EVP_PKEY *auth_key,
464
0
                                      Span<const uint8_t> entropy) {
465
0
  const auto *dhkem = static_cast<const EVP_KEM_DHKEM *>(kem);
466
0
  UniquePtr<EVP_PKEY> ephemeral_key(dhkem->key_from_encap_entropy(
467
0
      dhkem->key_method->alg_func(), entropy.data(), entropy.size()));
468
0
  if (ephemeral_key == nullptr) {
469
0
    return 0;
470
0
  }
471
0
  return dhkem_auth_encap_with_ephemeral_key(dhkem, out_ciphertext, out_secret,
472
0
                                             peer_key, auth_key,
473
0
                                             ephemeral_key.get());
474
0
}
475
476
int dhkem_auth_decap(const EVP_KEM *kem, Span<uint8_t> out_secret,
477
                     Span<const uint8_t> ciphertext, const EVP_PKEY *key,
478
0
                     const EVP_PKEY *auth_key) {
479
0
  const auto *dhkem = static_cast<const EVP_KEM_DHKEM *>(kem);
480
0
  const size_t public_len = dhkem->key_method->public_key_len;
481
0
  if (ciphertext.size() != public_len) {
482
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_CIPHERTEXT_LENGTH);
483
0
    return 0;
484
0
  }
485
0
  if (out_secret.size() != dhkem->secret_len) {
486
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_SECRET_LENGTH);
487
0
    return 0;
488
0
  }
489
  // pkE = DeserializePublicKey(enc)
490
0
  UniquePtr<EVP_PKEY> ephemeral_key(dhkem->key_method->deserialize_public_key(
491
0
      dhkem->key_method->alg_func(), ciphertext.data(), ciphertext.size()));
492
0
  if (ephemeral_key == nullptr) {
493
0
    return 0;
494
0
  }
495
  // dh = concat(DH(skR, pkE), DH(skR, pkS))
496
0
  InplaceVector<uint8_t, 2 * MAX_DHKEM_DH_SHARED_KEY_LEN> dh;
497
0
  if (!dh.TryResizeForOverwrite(2 * dhkem->dh_shared_key_len) ||
498
0
      !dhkem_dh(dhkem, Span(dh).subspan(0, dhkem->dh_shared_key_len), key,
499
0
                ephemeral_key.get()) ||
500
0
      !dhkem_dh(dhkem, Span(dh).subspan(dhkem->dh_shared_key_len), key,
501
0
                auth_key)) {
502
0
    return 0;
503
0
  }
504
  // pkRm = SerializePublicKey(pk(skR))
505
  // pkSm = SerializePublicKey(pkS)
506
  // kem_context = concat(enc, pkRm, pkSm)
507
0
  InplaceVector<uint8_t, 3 * MAX_DHKEM_PUBLIC_KEY_LEN> kem_context;
508
0
  if (!kem_context.TryResizeForOverwrite(3 * public_len) ||
509
0
      !dhkem_serialize_public_keys(dhkem, Span(kem_context).subspan(public_len),
510
0
                                   key, auth_key)) {
511
0
    return 0;
512
0
  }
513
0
  OPENSSL_memcpy(kem_context.data(), ciphertext.data(), ciphertext.size());
514
  // shared_secret = ExtractAndExpand(dh, kem_context)
515
0
  return dhkem_extract_and_expand(dhkem->key_method->hpke_kem_id,
516
0
                                  dhkem->hkdf_digest_func(), out_secret.data(),
517
0
                                  out_secret.size(), dh.data(), dh.size(),
518
0
                                  kem_context.data(), kem_context.size());
519
0
}
520
521
// RFC 9180: "For X25519 ..., the DeriveKeyPair() function applies a KDF to the
522
// input." Since HPKE uses X25519 only in the DHKEM(X25519, HKDF-SHA256)
523
// construction, this uses HKDF-SHA256 as the KDF.
524
EVP_PKEY *x25519_derive_key_pair(const EVP_PKEY_ALG *alg, uint16_t kem_suite_id,
525
0
                                 Span<const uint8_t> ikm) {
526
  // https://www.rfc-editor.org/rfc/rfc9180.html#name-derivekeypair
527
0
  auto suite_id = hpke_kem_suite_id(kem_suite_id);
528
0
  uint8_t dkp_prk[SHA256_DIGEST_LENGTH];
529
0
  size_t dkp_prk_len;
530
0
  uint8_t sk[X25519_PRIVATE_KEY_LEN];
531
0
  if (!hpke_labeled_extract(EVP_sha256(), dkp_prk, &dkp_prk_len, nullptr, 0,
532
0
                            suite_id.data(), suite_id.size(), "dkp_prk",
533
0
                            ikm.data(), ikm.size()) ||
534
0
      !hpke_labeled_expand(EVP_sha256(), sk, sizeof(sk), dkp_prk, dkp_prk_len,
535
0
                           suite_id.data(), suite_id.size(), "sk",
536
0
                           /*info=*/nullptr, /*info_len=*/0)) {
537
0
    return nullptr;
538
0
  }
539
0
  return EVP_PKEY_from_raw_private_key(alg, sk, sizeof(sk));
540
0
}
541
542
constexpr HpkeKeyMethod kX25519KeyMethod = {
543
    /*hpke_kem_id=*/EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
544
    /*public_key_len=*/X25519_PUBLIC_VALUE_LEN,
545
    /*private_key_len=*/X25519_PRIVATE_KEY_LEN,
546
    /*alg_func=*/&EVP_pkey_x25519,
547
    /*deserialize_private_key=*/&EVP_PKEY_from_raw_private_key,
548
    /*serialize_private_key=*/&EVP_PKEY_get_raw_private_key,
549
    /*deserialize_public_key=*/&EVP_PKEY_from_raw_public_key,
550
    /*serialize_public_key=*/&EVP_PKEY_get_raw_public_key,
551
    /*derive_key_pair=*/x25519_derive_key_pair,
552
};
553
554
}  // namespace
555
556
593
const EVP_KEM *EVP_kem_dhkem_x25519_hkdf_sha256() {
557
593
  static constexpr EVP_KEM_DHKEM kDhkemX25519 = {
558
593
      /*EVP_KEM=*/{
559
593
          /*pkey_id=*/EVP_PKEY_X25519,
560
593
          /*ciphertext_len=*/X25519_PUBLIC_VALUE_LEN,
561
593
          /*secret_len=*/SHA256_DIGEST_LENGTH,
562
593
          /*entropy_len=*/X25519_PRIVATE_KEY_LEN,
563
593
          /*check_key=*/nullptr,
564
593
          /*encap=*/&dhkem_encap,
565
593
          /*encap_external_entropy=*/&dhkem_encap_external_entropy,
566
593
          /*decap=*/&dhkem_decap,
567
593
      },
568
593
      /*dh_shared_key_len=*/X25519_SHARED_KEY_LEN,
569
593
      /*key_method=*/&kX25519KeyMethod,
570
593
      /*hkdf_digest_func=*/&EVP_sha256,
571
      // The X25519 encap entropy is the ephemeral private key itself.
572
593
      /*key_from_encap_entropy=*/&EVP_PKEY_from_raw_private_key,
573
593
  };
574
593
  return &kDhkemX25519;
575
593
}
576
577
14.9k
const EVP_HPKE_KEM *EVP_hpke_x25519_hkdf_sha256() {
578
14.9k
  static constexpr EVP_HPKE_KEM kKEM = {
579
14.9k
      /*id=*/EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
580
14.9k
      /*evp_kem_func=*/&EVP_kem_dhkem_x25519_hkdf_sha256,
581
14.9k
      /*key_method=*/&kX25519KeyMethod,
582
14.9k
      /*auth_encap=*/&dhkem_auth_encap,
583
14.9k
      /*auth_encap_external_entropy=*/&dhkem_auth_encap_external_entropy,
584
14.9k
      /*auth_decap=*/&dhkem_auth_decap,
585
14.9k
  };
586
14.9k
  return &kKEM;
587
14.9k
}
588
589
namespace {
590
591
constexpr size_t kP256PrivateKeyLen = 32;
592
constexpr size_t kP256PublicValueLen = 65;
593
constexpr size_t kP256SeedLen = 32;
594
constexpr size_t kP256SharedKeyLen = 32;
595
596
// RFC 9180's SerializePublicKey format for DHKEM(P-256, HKDF-SHA256) is the
597
// uncompressed X9.62 point, and its private keys are the big-endian scalar.
598
int p256_serialize_public_key(const EVP_PKEY *pkey, uint8_t *out,
599
0
                              size_t *out_len) {
600
0
  CBB cbb;
601
0
  CBB_init_fixed(&cbb, out, *out_len);
602
0
  if (!EVP_PKEY_marshal_ec_uncompressed_point(&cbb, pkey)) {
603
0
    return 0;
604
0
  }
605
0
  *out_len = CBB_len(&cbb);
606
0
  return 1;
607
0
}
608
609
int p256_serialize_private_key(const EVP_PKEY *pkey, uint8_t *out,
610
0
                               size_t *out_len) {
611
0
  CBB cbb;
612
0
  CBB_init_fixed(&cbb, out, *out_len);
613
0
  if (!EVP_PKEY_marshal_ec_private_scalar(&cbb, pkey)) {
614
0
    return 0;
615
0
  }
616
0
  *out_len = CBB_len(&cbb);
617
0
  return 1;
618
0
}
619
620
EVP_PKEY *p256_derive_key_pair(const EVP_PKEY_ALG *alg, uint16_t kem_suite_id,
621
0
                               Span<const uint8_t> ikm) {
622
  // https://www.rfc-editor.org/rfc/rfc9180.html#name-derivekeypair
623
0
  auto suite_id = hpke_kem_suite_id(kem_suite_id);
624
0
  uint8_t dkp_prk[SHA256_DIGEST_LENGTH];
625
0
  size_t dkp_prk_len;
626
0
  if (!hpke_labeled_extract(EVP_sha256(), dkp_prk, &dkp_prk_len, nullptr, 0,
627
0
                            suite_id.data(), suite_id.size(), "dkp_prk",
628
0
                            ikm.data(), ikm.size())) {
629
0
    return nullptr;
630
0
  }
631
0
  assert(dkp_prk_len == sizeof(dkp_prk));
632
0
  const EC_GROUP *const group = EC_group_p256();
633
634
  // Rejection sampling.
635
0
  uint8_t priv[kP256PrivateKeyLen];
636
0
  for (size_t counter = 0; counter < 256; counter++) {
637
0
    const uint8_t counter_byte = counter & 0xff;
638
0
    if (!hpke_labeled_expand(EVP_sha256(), priv, sizeof(priv), dkp_prk,
639
0
                             sizeof(dkp_prk), suite_id.data(), suite_id.size(),
640
0
                             "candidate", &counter_byte,
641
0
                             sizeof(counter_byte))) {
642
0
      return nullptr;
643
0
    }
644
0
    EC_SCALAR private_scalar;
645
    // `ec_scalar_from_bytes` checks that the scalar is less than the order.
646
0
    if (ec_scalar_from_bytes(group, &private_scalar, priv, sizeof(priv)) &&
647
0
        !ec_scalar_is_zero(group, &private_scalar)) {
648
0
      return EVP_PKEY_from_ec_private_scalar(alg, priv, sizeof(priv));
649
0
    }
650
0
  }
651
  // This happens with probability of 2^-(32*256).
652
0
  OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR);
653
0
  return nullptr;
654
0
}
655
656
// The P-256 encap entropy is ikmE, the input to DeriveKeyPair.
657
EVP_PKEY *p256_key_from_encap_entropy(const EVP_PKEY_ALG *alg,
658
0
                                      const uint8_t *in, size_t len) {
659
0
  return p256_derive_key_pair(alg, EVP_HPKE_DHKEM_P256_HKDF_SHA256,
660
0
                              Span(in, len));
661
0
}
662
663
0
bool p256_check_key(const EVP_KEM *kem, const EVP_PKEY *key) {
664
0
  const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(key);
665
0
  return ec_key != nullptr &&
666
0
         EC_GROUP_cmp(EC_KEY_get0_group(ec_key), EC_group_p256(),
667
0
                      /*ignored=*/nullptr) == 0;
668
0
}
669
670
constexpr HpkeKeyMethod kP256KeyMethod = {
671
    /*hpke_kem_id=*/EVP_HPKE_DHKEM_P256_HKDF_SHA256,
672
    /*public_key_len=*/kP256PublicValueLen,
673
    /*private_key_len=*/kP256PrivateKeyLen,
674
    /*alg_func=*/&EVP_pkey_ec_p256,
675
    /*deserialize_private_key=*/&EVP_PKEY_from_ec_private_scalar,
676
    /*serialize_private_key=*/&p256_serialize_private_key,
677
    /*deserialize_public_key=*/&EVP_PKEY_from_ec_uncompressed_point,
678
    /*serialize_public_key=*/&p256_serialize_public_key,
679
    /*derive_key_pair=*/&p256_derive_key_pair,
680
};
681
682
}  // namespace
683
684
0
const EVP_KEM *EVP_kem_dhkem_p256_hkdf_sha256() {
685
0
  static constexpr EVP_KEM_DHKEM kDhkemP256 = {
686
0
      /*EVP_KEM=*/{
687
0
          /*pkey_id=*/EVP_PKEY_EC,
688
0
          /*ciphertext_len=*/kP256PublicValueLen,
689
0
          /*secret_len=*/SHA256_DIGEST_LENGTH,
690
0
          /*entropy_len=*/kP256SeedLen,
691
0
          /*check_key=*/&p256_check_key,
692
0
          /*encap=*/&dhkem_encap,
693
0
          /*encap_external_entropy=*/&dhkem_encap_external_entropy,
694
0
          /*decap=*/&dhkem_decap,
695
0
      },
696
0
      /*dh_shared_key_len=*/kP256SharedKeyLen,
697
0
      /*key_method=*/&kP256KeyMethod,
698
0
      /*hkdf_digest_func=*/&EVP_sha256,
699
0
      /*key_from_encap_entropy=*/&p256_key_from_encap_entropy,
700
0
  };
701
0
  return &kDhkemP256;
702
0
}
703
704
0
const EVP_HPKE_KEM *EVP_hpke_p256_hkdf_sha256() {
705
0
  static constexpr EVP_HPKE_KEM kKEM = {
706
0
      /*id=*/EVP_HPKE_DHKEM_P256_HKDF_SHA256,
707
0
      /*evp_kem_func=*/&EVP_kem_dhkem_p256_hkdf_sha256,
708
0
      /*key_method=*/&kP256KeyMethod,
709
0
      /*auth_encap=*/&dhkem_auth_encap,
710
0
      /*auth_encap_external_entropy=*/&dhkem_auth_encap_external_entropy,
711
0
      /*auth_decap=*/&dhkem_auth_decap,
712
0
  };
713
0
  return &kKEM;
714
0
}
715
716
namespace {
717
718
template <size_t SEED_BYTES>
719
EVP_PKEY *shake256_derive_key_pair_from_private_seed(const EVP_PKEY_ALG *alg,
720
                                                     uint16_t kem_suite_id,
721
0
                                                     Span<const uint8_t> ikm) {
722
0
  uint8_t seed[SEED_BYTES];
723
0
  hpke_shake256_labeled_derive(seed, ikm, hpke_kem_suite_id(kem_suite_id),
724
0
                               "DeriveKeyPair", /*context=*/{});
725
0
  return EVP_PKEY_from_private_seed(alg, seed, sizeof(seed));
726
0
}
Unexecuted instantiation: hpke.cc:evp_pkey_st* (anonymous namespace)::shake256_derive_key_pair_from_private_seed<32ul>(evp_pkey_alg_st const*, unsigned short, bssl::Span<unsigned char const, 18446744073709551615ul>)
Unexecuted instantiation: hpke.cc:evp_pkey_st* (anonymous namespace)::shake256_derive_key_pair_from_private_seed<64ul>(evp_pkey_alg_st const*, unsigned short, bssl::Span<unsigned char const, 18446744073709551615ul>)
727
728
constexpr HpkeKeyMethod kXwingKeyMethod = {
729
    /*hpke_kem_id=*/EVP_HPKE_XWING,
730
    /*public_key_len=*/XWING_PUBLIC_KEY_BYTES,
731
    /*private_key_len=*/XWING_PRIVATE_KEY_BYTES,
732
    /*alg_func=*/&EVP_pkey_xwing,
733
    /*deserialize_private_key=*/&EVP_PKEY_from_private_seed,
734
    /*serialize_private_key=*/&EVP_PKEY_get_private_seed,
735
    /*deserialize_public_key=*/&EVP_PKEY_from_raw_public_key,
736
    /*serialize_public_key=*/&EVP_PKEY_get_raw_public_key,
737
    /*derive_key_pair=*/
738
    shake256_derive_key_pair_from_private_seed<XWING_PRIVATE_KEY_BYTES>,
739
};
740
741
}  // namespace
742
743
0
const EVP_HPKE_KEM *EVP_hpke_xwing() {
744
0
  static constexpr EVP_HPKE_KEM kKEM = {
745
0
      /*id=*/EVP_HPKE_XWING,
746
0
      /*evp_kem_func=*/&EVP_kem_xwing,
747
0
      /*key_method=*/&kXwingKeyMethod,
748
      // X-Wing doesn't support authenticated encapsulation/decapsulation:
749
      // https://datatracker.ietf.org/doc/html/draft-connolly-cfrg-xwing-kem-08#name-use-in-hpke
750
0
      /*auth_encap=*/nullptr,
751
0
      /*auth_encap_external_entropy=*/nullptr,
752
0
      /*auth_decap=*/nullptr,
753
0
  };
754
0
  return &kKEM;
755
0
}
756
757
namespace {
758
759
constexpr HpkeKeyMethod kMlkem768KeyMethod = {
760
    /*hpke_kem_id=*/EVP_HPKE_MLKEM768,
761
    /*public_key_len=*/MLKEM768_PUBLIC_KEY_BYTES,
762
    /*private_key_len=*/MLKEM_SEED_BYTES,
763
    /*alg_func=*/&EVP_pkey_ml_kem_768,
764
    /*deserialize_private_key=*/&EVP_PKEY_from_private_seed,
765
    /*serialize_private_key=*/&EVP_PKEY_get_private_seed,
766
    /*deserialize_public_key=*/&EVP_PKEY_from_raw_public_key,
767
    /*serialize_public_key=*/&EVP_PKEY_get_raw_public_key,
768
    /*derive_key_pair=*/
769
    shake256_derive_key_pair_from_private_seed<MLKEM_SEED_BYTES>,
770
};
771
772
constexpr HpkeKeyMethod kMlkem1024KeyMethod = {
773
    /*hpke_kem_id=*/EVP_HPKE_MLKEM1024,
774
    /*public_key_len=*/MLKEM1024_PUBLIC_KEY_BYTES,
775
    /*private_key_len=*/MLKEM_SEED_BYTES,
776
    /*alg_func=*/&EVP_pkey_ml_kem_1024,
777
    /*deserialize_private_key=*/&EVP_PKEY_from_private_seed,
778
    /*serialize_private_key=*/&EVP_PKEY_get_private_seed,
779
    /*deserialize_public_key=*/&EVP_PKEY_from_raw_public_key,
780
    /*serialize_public_key=*/&EVP_PKEY_get_raw_public_key,
781
    /*derive_key_pair=*/
782
    shake256_derive_key_pair_from_private_seed<MLKEM_SEED_BYTES>,
783
};
784
785
}  // namespace
786
787
0
const EVP_HPKE_KEM *EVP_hpke_mlkem768() {
788
0
  static constexpr EVP_HPKE_KEM kKEM = {
789
0
      /*id=*/EVP_HPKE_MLKEM768,
790
0
      /*evp_kem_func=*/&EVP_kem_ml_kem_768,
791
0
      /*key_method=*/&kMlkem768KeyMethod,
792
      // ML-KEM doesn't support authenticated encapsulation/decapsulation:
793
      // https://datatracker.ietf.org/doc/draft-ietf-hpke-pq/01/
794
0
      /*auth_encap=*/nullptr,
795
0
      /*auth_encap_external_entropy=*/nullptr,
796
0
      /*auth_decap=*/nullptr,
797
0
  };
798
0
  return &kKEM;
799
0
}
800
801
0
const EVP_HPKE_KEM *EVP_hpke_mlkem1024() {
802
0
  static constexpr EVP_HPKE_KEM kKEM = {
803
0
      /*id=*/EVP_HPKE_MLKEM1024,
804
0
      /*evp_kem_func=*/&EVP_kem_ml_kem_1024,
805
0
      /*key_method=*/&kMlkem1024KeyMethod,
806
      // ML-KEM doesn't support authenticated encapsulation/decapsulation:
807
      // https://datatracker.ietf.org/doc/draft-ietf-hpke-pq/01/
808
0
      /*auth_encap=*/nullptr,
809
0
      /*auth_encap_external_entropy=*/nullptr,
810
0
      /*auth_decap=*/nullptr,
811
0
  };
812
0
  return &kKEM;
813
0
}
814
815
503
uint16_t EVP_HPKE_KEM_id(const EVP_HPKE_KEM *kem) { return kem->id; }
816
817
503
size_t EVP_HPKE_KEM_public_key_len(const EVP_HPKE_KEM *kem) {
818
503
  return kem->key_method->public_key_len;
819
503
}
820
821
0
size_t EVP_HPKE_KEM_private_key_len(const EVP_HPKE_KEM *kem) {
822
0
  return kem->key_method->private_key_len;
823
0
}
824
825
0
size_t EVP_HPKE_KEM_enc_len(const EVP_HPKE_KEM *kem) {
826
0
  return EVP_KEM_ciphertext_len(kem->evp_kem_func());
827
0
}
828
829
290
size_t EVP_HPKE_KEM_shared_secret_len(const EVP_HPKE_KEM *kem) {
830
290
  return EVP_KEM_secret_len(kem->evp_kem_func());
831
290
}
832
833
43.9k
void EVP_HPKE_KEY_zero(EVP_HPKE_KEY *key) {
834
43.9k
  OPENSSL_memset(key, 0, sizeof(EVP_HPKE_KEY));
835
43.9k
}
836
837
28.9k
void EVP_HPKE_KEY_cleanup(EVP_HPKE_KEY *key) {
838
28.9k
  EVP_PKEY_free(key->pkey);
839
28.9k
  key->pkey = nullptr;
840
28.9k
}
841
842
0
EVP_HPKE_KEY *EVP_HPKE_KEY_new() {
843
0
  EVP_HPKE_KEY *key = New<EVP_HPKE_KEY>();
844
0
  if (key == nullptr) {
845
0
    return nullptr;
846
0
  }
847
0
  EVP_HPKE_KEY_zero(key);
848
0
  return key;
849
0
}
850
851
0
void EVP_HPKE_KEY_free(EVP_HPKE_KEY *key) {
852
0
  if (key != nullptr) {
853
0
    EVP_HPKE_KEY_cleanup(key);
854
0
    Delete(key);
855
0
  }
856
0
}
857
858
6
int EVP_HPKE_KEY_copy(EVP_HPKE_KEY *dst, const EVP_HPKE_KEY *src) {
859
6
  dst->kem = src->kem;
860
6
  dst->pkey = EVP_PKEY_dup_ref(src->pkey);
861
6
  return 1;
862
6
}
863
864
0
void EVP_HPKE_KEY_move(EVP_HPKE_KEY *out, EVP_HPKE_KEY *in) {
865
0
  EVP_HPKE_KEY_cleanup(out);
866
  // For now, `EVP_HPKE_KEY` is trivially movable.
867
  // Note that Rust may move this structure. See
868
  // bssl-crypto/src/scoped.rs:EvpHpkeKey.
869
0
  *out = *in;
870
0
  EVP_HPKE_KEY_zero(in);
871
0
}
872
873
int EVP_HPKE_KEY_init(EVP_HPKE_KEY *key, const EVP_HPKE_KEM *kem,
874
14.9k
                      const uint8_t *priv_key, size_t priv_key_len) {
875
14.9k
  EVP_HPKE_KEY_zero(key);
876
14.9k
  key->kem = kem;
877
14.9k
  UniquePtr<EVP_PKEY> pkey(kem->key_method->deserialize_private_key(
878
14.9k
      kem->key_method->alg_func(), priv_key, priv_key_len));
879
14.9k
  if (pkey == nullptr) {
880
841
    key->kem = nullptr;
881
841
    return 0;
882
841
  }
883
14.0k
  key->pkey = pkey.release();
884
14.0k
  return 1;
885
14.9k
}
886
887
0
int EVP_HPKE_KEY_generate(EVP_HPKE_KEY *key, const EVP_HPKE_KEM *kem) {
888
0
  EVP_HPKE_KEY_zero(key);
889
0
  key->kem = kem;
890
0
  UniquePtr<EVP_PKEY> pkey(
891
0
      EVP_PKEY_generate_from_alg(kem->key_method->alg_func()));
892
0
  if (pkey == nullptr) {
893
0
    key->kem = nullptr;
894
0
    return 0;
895
0
  }
896
0
  key->pkey = pkey.release();
897
0
  return 1;
898
0
}
899
900
int EVP_HPKE_KEY_derive(EVP_HPKE_KEY *key, const EVP_HPKE_KEM *kem,
901
0
                        const uint8_t *ikm, size_t ikm_len) {
902
0
  EVP_HPKE_KEY_zero(key);
903
0
  key->kem = kem;
904
0
  UniquePtr<EVP_PKEY> pkey(kem->key_method->derive_key_pair(
905
0
      kem->key_method->alg_func(), kem->id, Span(ikm, ikm_len)));
906
0
  if (pkey == nullptr) {
907
0
    key->kem = nullptr;
908
0
    return 0;
909
0
  }
910
0
  key->pkey = pkey.release();
911
0
  return 1;
912
0
}
913
914
503
const EVP_HPKE_KEM *EVP_HPKE_KEY_kem(const EVP_HPKE_KEY *key) {
915
503
  return key->kem;
916
503
}
917
918
int EVP_HPKE_KEY_public_key(const EVP_HPKE_KEY *key, uint8_t *out,
919
503
                            size_t *out_len, size_t max_out) {
920
503
  if (max_out < EVP_HPKE_KEM_public_key_len(key->kem)) {
921
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
922
0
    return 0;
923
0
  }
924
503
  *out_len = max_out;
925
503
  return key->kem->key_method->serialize_public_key(key->pkey, out, out_len);
926
503
}
927
928
int EVP_HPKE_KEY_private_key(const EVP_HPKE_KEY *key, uint8_t *out,
929
0
                             size_t *out_len, size_t max_out) {
930
0
  if (max_out < EVP_HPKE_KEM_private_key_len(key->kem)) {
931
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
932
0
    return 0;
933
0
  }
934
0
  *out_len = max_out;
935
0
  return key->kem->key_method->serialize_private_key(key->pkey, out, out_len);
936
0
}
937
938
939
// Supported KDFs and AEADs.
940
941
303
const EVP_HPKE_KDF *EVP_hpke_hkdf_sha256() {
942
303
  static const EVP_HPKE_KDF kKDF = {EVP_HPKE_HKDF_SHA256, &EVP_sha256};
943
303
  return &kKDF;
944
303
}
945
946
0
const EVP_HPKE_KDF *EVP_hpke_hkdf_sha384() {
947
0
  static const EVP_HPKE_KDF kKDF = {EVP_HPKE_HKDF_SHA384, &EVP_sha384};
948
0
  return &kKDF;
949
0
}
950
951
68
uint16_t EVP_HPKE_KDF_id(const EVP_HPKE_KDF *kdf) { return kdf->id; }
952
953
0
const EVP_MD *EVP_HPKE_KDF_hkdf_md(const EVP_HPKE_KDF *kdf) {
954
0
  return kdf->hkdf_md_func();
955
0
}
956
957
3.37k
const EVP_HPKE_AEAD *EVP_hpke_aes_128_gcm() {
958
3.37k
  static const EVP_HPKE_AEAD kAEAD = {EVP_HPKE_AES_128_GCM,
959
3.37k
                                      &EVP_aead_aes_128_gcm};
960
3.37k
  return &kAEAD;
961
3.37k
}
962
963
2.61k
const EVP_HPKE_AEAD *EVP_hpke_aes_256_gcm() {
964
2.61k
  static const EVP_HPKE_AEAD kAEAD = {EVP_HPKE_AES_256_GCM,
965
2.61k
                                      &EVP_aead_aes_256_gcm};
966
2.61k
  return &kAEAD;
967
2.61k
}
968
969
2.56k
const EVP_HPKE_AEAD *EVP_hpke_chacha20_poly1305() {
970
2.56k
  static const EVP_HPKE_AEAD kAEAD = {EVP_HPKE_CHACHA20_POLY1305,
971
2.56k
                                      &EVP_aead_chacha20_poly1305};
972
2.56k
  return &kAEAD;
973
2.56k
}
974
975
8.59k
uint16_t EVP_HPKE_AEAD_id(const EVP_HPKE_AEAD *aead) { return aead->id; }
976
977
290
const EVP_AEAD *EVP_HPKE_AEAD_aead(const EVP_HPKE_AEAD *aead) {
978
290
  return aead->aead_func();
979
290
}
980
981
982
// HPKE implementation.
983
984
290
#define HPKE_MODE_BASE 0
985
0
#define HPKE_MODE_AUTH 2
986
987
namespace {
988
989
290
std::array<uint8_t, 10> hpke_full_suite_id(const EVP_HPKE_CTX *ctx) {
990
290
  return {
991
290
      'H',
992
290
      'P',
993
290
      'K',
994
290
      'E',
995
290
      static_cast<uint8_t>(ctx->kem->id >> 8),
996
290
      static_cast<uint8_t>(ctx->kem->id),
997
290
      static_cast<uint8_t>(ctx->kdf->id >> 8),
998
290
      static_cast<uint8_t>(ctx->kdf->id),
999
290
      static_cast<uint8_t>(ctx->aead->id >> 8),
1000
290
      static_cast<uint8_t>(ctx->aead->id),
1001
290
  };
1002
290
}
1003
int hpke_key_schedule(EVP_HPKE_CTX *ctx, uint8_t mode,
1004
                      const uint8_t *shared_secret, size_t shared_secret_len,
1005
290
                      const uint8_t *info, size_t info_len) {
1006
290
  auto suite_id = hpke_full_suite_id(ctx);
1007
1008
  // psk_id_hash = LabeledExtract("", "psk_id_hash", psk_id)
1009
  // TODO(davidben): Precompute this value and store it with the EVP_HPKE_KDF.
1010
290
  const EVP_MD *hkdf_md = ctx->kdf->hkdf_md_func();
1011
290
  uint8_t psk_id_hash[EVP_MAX_MD_SIZE];
1012
290
  size_t psk_id_hash_len;
1013
290
  if (!hpke_labeled_extract(hkdf_md, psk_id_hash, &psk_id_hash_len, nullptr, 0,
1014
290
                            suite_id.data(), suite_id.size(), "psk_id_hash",
1015
290
                            nullptr, 0)) {
1016
0
    return 0;
1017
0
  }
1018
1019
  // info_hash = LabeledExtract("", "info_hash", info)
1020
290
  uint8_t info_hash[EVP_MAX_MD_SIZE];
1021
290
  size_t info_hash_len;
1022
290
  if (!hpke_labeled_extract(hkdf_md, info_hash, &info_hash_len, nullptr, 0,
1023
290
                            suite_id.data(), suite_id.size(), "info_hash", info,
1024
290
                            info_len)) {
1025
0
    return 0;
1026
0
  }
1027
1028
  // key_schedule_context = concat(mode, psk_id_hash, info_hash)
1029
290
  uint8_t context[sizeof(uint8_t) + 2 * EVP_MAX_MD_SIZE];
1030
290
  size_t context_len;
1031
290
  CBB context_cbb;
1032
290
  CBB_init_fixed(&context_cbb, context, sizeof(context));
1033
290
  if (!CBB_add_u8(&context_cbb, mode) ||
1034
290
      !CBB_add_bytes(&context_cbb, psk_id_hash, psk_id_hash_len) ||
1035
290
      !CBB_add_bytes(&context_cbb, info_hash, info_hash_len) ||
1036
290
      !CBB_finish(&context_cbb, nullptr, &context_len)) {
1037
0
    return 0;
1038
0
  }
1039
1040
  // secret = LabeledExtract(shared_secret, "secret", psk)
1041
290
  uint8_t secret[EVP_MAX_MD_SIZE];
1042
290
  size_t secret_len;
1043
290
  if (!hpke_labeled_extract(hkdf_md, secret, &secret_len, shared_secret,
1044
290
                            shared_secret_len, suite_id.data(), suite_id.size(),
1045
290
                            "secret", nullptr, 0)) {
1046
0
    return 0;
1047
0
  }
1048
1049
  // key = LabeledExpand(secret, "key", key_schedule_context, Nk)
1050
290
  const EVP_AEAD *aead = EVP_HPKE_AEAD_aead(ctx->aead);
1051
290
  uint8_t key[EVP_AEAD_MAX_KEY_LENGTH];
1052
290
  const size_t kKeyLen = EVP_AEAD_key_length(aead);
1053
290
  if (!hpke_labeled_expand(hkdf_md, key, kKeyLen, secret, secret_len,
1054
290
                           suite_id.data(), suite_id.size(), "key", context,
1055
290
                           context_len) ||
1056
290
      !EVP_AEAD_CTX_init(&ctx->aead_ctx, aead, key, kKeyLen,
1057
290
                         EVP_AEAD_DEFAULT_TAG_LENGTH, nullptr)) {
1058
0
    return 0;
1059
0
  }
1060
1061
  // base_nonce = LabeledExpand(secret, "base_nonce", key_schedule_context, Nn)
1062
290
  if (!hpke_labeled_expand(hkdf_md, ctx->base_nonce,
1063
290
                           EVP_AEAD_nonce_length(aead), secret, secret_len,
1064
290
                           suite_id.data(), suite_id.size(), "base_nonce",
1065
290
                           context, context_len)) {
1066
0
    return 0;
1067
0
  }
1068
1069
  // exporter_secret = LabeledExpand(secret, "exp", key_schedule_context, Nh)
1070
290
  if (!hpke_labeled_expand(hkdf_md, ctx->exporter_secret, EVP_MD_size(hkdf_md),
1071
290
                           secret, secret_len, suite_id.data(), suite_id.size(),
1072
290
                           "exp", context, context_len)) {
1073
0
    return 0;
1074
0
  }
1075
1076
290
  return 1;
1077
290
}
1078
1079
int hpke_setup_sender_impl(EVP_HPKE_CTX *ctx, uint8_t *out_enc,
1080
                           size_t *out_enc_len, size_t max_enc,
1081
                           const EVP_HPKE_KEM *kem, const EVP_HPKE_KDF *kdf,
1082
                           const EVP_HPKE_AEAD *aead,
1083
                           Span<const uint8_t> peer_public_key,
1084
                           Span<const uint8_t> info,
1085
0
                           std::optional<Span<const uint8_t>> entropy) {
1086
0
  EVP_HPKE_CTX_zero(ctx);
1087
0
  ctx->is_sender = 1;
1088
0
  ctx->kem = kem;
1089
0
  ctx->kdf = kdf;
1090
0
  ctx->aead = aead;
1091
1092
0
  const EVP_KEM *evp_kem = kem->evp_kem_func();
1093
0
  if (max_enc < EVP_KEM_ciphertext_len(evp_kem)) {
1094
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
1095
0
    return 0;
1096
0
  }
1097
0
  *out_enc_len = EVP_KEM_ciphertext_len(evp_kem);
1098
1099
0
  UniquePtr<EVP_PKEY> peer_pubkey(kem->key_method->deserialize_public_key(
1100
0
      kem->key_method->alg_func(), peer_public_key.data(),
1101
0
      peer_public_key.size()));
1102
0
  if (peer_pubkey == nullptr) {
1103
0
    return 0;
1104
0
  }
1105
0
  InplaceVector<uint8_t, MAX_SHARED_SECRET_LEN> shared_secret;
1106
0
  if (!shared_secret.TryResizeForOverwrite(evp_kem->secret_len)) {
1107
0
    OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR);
1108
0
    return 0;
1109
0
  }
1110
0
  int encap_ok =
1111
0
      entropy.has_value()
1112
0
          ? EVP_KEM_encap_external_entropy_for_testing(
1113
0
                evp_kem, out_enc, *out_enc_len, shared_secret.data(),
1114
0
                shared_secret.size(), peer_pubkey.get(), entropy->data(),
1115
0
                entropy->size())
1116
0
          : EVP_KEM_encap(evp_kem, out_enc, *out_enc_len, shared_secret.data(),
1117
0
                          shared_secret.size(), peer_pubkey.get());
1118
0
  if (!encap_ok ||
1119
0
      !hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret.data(),
1120
0
                         shared_secret.size(), info.data(), info.size())) {
1121
0
    EVP_HPKE_CTX_cleanup(ctx);
1122
0
    return 0;
1123
0
  }
1124
0
  return 1;
1125
0
}
1126
1127
int hpke_setup_auth_sender_impl(
1128
    EVP_HPKE_CTX *ctx, uint8_t *out_enc, size_t *out_enc_len, size_t max_enc,
1129
    const EVP_HPKE_KEY *key, const EVP_HPKE_KDF *kdf, const EVP_HPKE_AEAD *aead,
1130
    Span<const uint8_t> peer_public_key, Span<const uint8_t> info,
1131
0
    std::optional<Span<const uint8_t>> entropy) {
1132
0
  if (entropy.has_value() ? key->kem->auth_encap_external_entropy == nullptr
1133
0
                          : key->kem->auth_encap == nullptr) {
1134
    // Not all HPKE KEMs support AuthEncap.
1135
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
1136
0
    return 0;
1137
0
  }
1138
1139
0
  const EVP_KEM *kem = key->kem->evp_kem_func();
1140
0
  EVP_HPKE_CTX_zero(ctx);
1141
0
  ctx->is_sender = 1;
1142
0
  ctx->kem = key->kem;
1143
0
  ctx->kdf = kdf;
1144
0
  ctx->aead = aead;
1145
0
  if (max_enc < kem->ciphertext_len) {
1146
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
1147
0
    return 0;
1148
0
  }
1149
0
  UniquePtr<EVP_PKEY> peer_key(key->kem->key_method->deserialize_public_key(
1150
0
      key->kem->key_method->alg_func(), peer_public_key.data(),
1151
0
      peer_public_key.size()));
1152
0
  if (peer_key == nullptr) {
1153
0
    return 0;
1154
0
  }
1155
1156
0
  InplaceVector<uint8_t, MAX_SHARED_SECRET_LEN> shared_secret;
1157
0
  if (!shared_secret.TryResizeForOverwrite(kem->secret_len)) {
1158
0
    OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR);
1159
0
    return 0;
1160
0
  }
1161
0
  Span<uint8_t> enc_span(out_enc, kem->ciphertext_len);
1162
0
  Span<uint8_t> secret_span(shared_secret);
1163
0
  int auth_encap_ok =
1164
0
      entropy.has_value()
1165
0
          ? key->kem->auth_encap_external_entropy(
1166
0
                kem, enc_span, secret_span, peer_key.get(), key->pkey, *entropy)
1167
0
          : key->kem->auth_encap(kem, enc_span, secret_span, peer_key.get(),
1168
0
                                 key->pkey);
1169
0
  if (!auth_encap_ok ||
1170
0
      !hpke_key_schedule(ctx, HPKE_MODE_AUTH, secret_span.data(),
1171
0
                         secret_span.size(), info.data(), info.size())) {
1172
0
    EVP_HPKE_CTX_cleanup(ctx);
1173
0
    return 0;
1174
0
  }
1175
0
  *out_enc_len = kem->ciphertext_len;
1176
0
  return 1;
1177
0
}
1178
1179
27
void hpke_nonce(const EVP_HPKE_CTX *ctx, uint8_t *out_nonce, size_t nonce_len) {
1180
27
  assert(nonce_len >= 8);
1181
1182
  // Write padded big-endian bytes of `ctx->seq` to `out_nonce`.
1183
27
  OPENSSL_memset(out_nonce, 0, nonce_len);
1184
27
  uint64_t seq_copy = ctx->seq;
1185
243
  for (size_t i = 0; i < 8; i++) {
1186
216
    out_nonce[nonce_len - i - 1] = seq_copy & 0xff;
1187
216
    seq_copy >>= 8;
1188
216
  }
1189
1190
  // XOR the encoded sequence with the `ctx->base_nonce`.
1191
351
  for (size_t i = 0; i < nonce_len; i++) {
1192
324
    out_nonce[i] ^= ctx->base_nonce[i];
1193
324
  }
1194
27
}
1195
1196
}  // namespace
1197
1198
99.4k
void EVP_HPKE_CTX_zero(EVP_HPKE_CTX *ctx) {
1199
99.4k
  OPENSSL_memset(ctx, 0, sizeof(EVP_HPKE_CTX));
1200
99.4k
  EVP_AEAD_CTX_zero(&ctx->aead_ctx);
1201
99.4k
}
1202
1203
98.8k
void EVP_HPKE_CTX_cleanup(EVP_HPKE_CTX *ctx) {
1204
98.8k
  EVP_AEAD_CTX_cleanup(&ctx->aead_ctx);
1205
98.8k
}
1206
1207
0
EVP_HPKE_CTX *EVP_HPKE_CTX_new() {
1208
0
  EVP_HPKE_CTX *ctx = New<EVP_HPKE_CTX>();
1209
0
  if (ctx == nullptr) {
1210
0
    return nullptr;
1211
0
  }
1212
0
  EVP_HPKE_CTX_zero(ctx);
1213
0
  return ctx;
1214
0
}
1215
1216
0
void EVP_HPKE_CTX_free(EVP_HPKE_CTX *ctx) {
1217
0
  if (ctx != nullptr) {
1218
0
    EVP_HPKE_CTX_cleanup(ctx);
1219
0
    Delete(ctx);
1220
0
  }
1221
0
}
1222
1223
1224
int EVP_HPKE_CTX_setup_sender(EVP_HPKE_CTX *ctx, uint8_t *out_enc,
1225
                              size_t *out_enc_len, size_t max_enc,
1226
                              const EVP_HPKE_KEM *kem, const EVP_HPKE_KDF *kdf,
1227
                              const EVP_HPKE_AEAD *aead,
1228
                              const uint8_t *peer_public_key,
1229
                              size_t peer_public_key_len, const uint8_t *info,
1230
0
                              size_t info_len) {
1231
0
  return hpke_setup_sender_impl(ctx, out_enc, out_enc_len, max_enc, kem, kdf,
1232
0
                                aead,
1233
0
                                Span(peer_public_key, peer_public_key_len),
1234
0
                                Span(info, info_len), /*entropy=*/std::nullopt);
1235
0
}
1236
1237
int EVP_HPKE_CTX_setup_sender_with_seed_for_testing(
1238
    EVP_HPKE_CTX *ctx, uint8_t *out_enc, size_t *out_enc_len, size_t max_enc,
1239
    const EVP_HPKE_KEM *kem, const EVP_HPKE_KDF *kdf, const EVP_HPKE_AEAD *aead,
1240
    const uint8_t *peer_public_key, size_t peer_public_key_len,
1241
    const uint8_t *info, size_t info_len, const uint8_t *seed,
1242
0
    size_t seed_len) {
1243
0
  return hpke_setup_sender_impl(ctx, out_enc, out_enc_len, max_enc, kem, kdf,
1244
0
                                aead,
1245
0
                                Span(peer_public_key, peer_public_key_len),
1246
0
                                Span(info, info_len), Span(seed, seed_len));
1247
0
}
1248
1249
int EVP_HPKE_CTX_setup_recipient_with_shared_secret(
1250
    EVP_HPKE_CTX *ctx, const EVP_HPKE_KEM *kem, const EVP_HPKE_KDF *kdf,
1251
    const EVP_HPKE_AEAD *aead, const uint8_t *shared_secret,
1252
290
    size_t shared_secret_len, const uint8_t *info, size_t info_len) {
1253
290
  EVP_HPKE_CTX_zero(ctx);
1254
1255
290
  if (shared_secret_len != EVP_HPKE_KEM_shared_secret_len(kem)) {
1256
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_INVALID_BUFFER_SIZE);
1257
0
    return 0;
1258
0
  }
1259
1260
290
  ctx->is_sender = 0;
1261
290
  ctx->kem = kem;
1262
290
  ctx->kdf = kdf;
1263
290
  ctx->aead = aead;
1264
290
  if (!hpke_key_schedule(ctx, HPKE_MODE_BASE, shared_secret, shared_secret_len,
1265
290
                         info, info_len)) {
1266
0
    EVP_HPKE_CTX_cleanup(ctx);
1267
0
    return 0;
1268
0
  }
1269
290
  return 1;
1270
290
}
1271
1272
int EVP_HPKE_CTX_setup_recipient(EVP_HPKE_CTX *ctx, const EVP_HPKE_KEY *key,
1273
                                 const EVP_HPKE_KDF *kdf,
1274
                                 const EVP_HPKE_AEAD *aead, const uint8_t *enc,
1275
                                 size_t enc_len, const uint8_t *info,
1276
303
                                 size_t info_len) {
1277
303
  EVP_HPKE_CTX_zero(ctx);
1278
1279
303
  const EVP_KEM *evp_kem = key->kem->evp_kem_func();
1280
303
  const EVP_PKEY *decap_key = key->pkey;
1281
1282
303
  InplaceVector<uint8_t, MAX_SHARED_SECRET_LEN> shared_secret;
1283
303
  if (!shared_secret.TryResizeForOverwrite(evp_kem->secret_len)) {
1284
0
    OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR);
1285
0
    return 0;
1286
0
  }
1287
303
  return EVP_KEM_decap(evp_kem, shared_secret.data(), shared_secret.size(), enc,
1288
303
                       enc_len, decap_key) &&
1289
290
         EVP_HPKE_CTX_setup_recipient_with_shared_secret(
1290
290
             ctx, key->kem, kdf, aead, shared_secret.data(),
1291
290
             shared_secret.size(), info, info_len);
1292
303
}
1293
1294
int EVP_HPKE_CTX_setup_auth_sender(
1295
    EVP_HPKE_CTX *ctx, uint8_t *out_enc, size_t *out_enc_len, size_t max_enc,
1296
    const EVP_HPKE_KEY *key, const EVP_HPKE_KDF *kdf, const EVP_HPKE_AEAD *aead,
1297
    const uint8_t *peer_public_key, size_t peer_public_key_len,
1298
0
    const uint8_t *info, size_t info_len) {
1299
0
  return hpke_setup_auth_sender_impl(
1300
0
      ctx, out_enc, out_enc_len, max_enc, key, kdf, aead,
1301
0
      Span(peer_public_key, peer_public_key_len), Span(info, info_len),
1302
0
      /*entropy=*/std::nullopt);
1303
0
}
1304
1305
int EVP_HPKE_CTX_setup_auth_sender_with_seed_for_testing(
1306
    EVP_HPKE_CTX *ctx, uint8_t *out_enc, size_t *out_enc_len, size_t max_enc,
1307
    const EVP_HPKE_KEY *key, const EVP_HPKE_KDF *kdf, const EVP_HPKE_AEAD *aead,
1308
    const uint8_t *peer_public_key, size_t peer_public_key_len,
1309
    const uint8_t *info, size_t info_len, const uint8_t *seed,
1310
0
    size_t seed_len) {
1311
0
  return hpke_setup_auth_sender_impl(
1312
0
      ctx, out_enc, out_enc_len, max_enc, key, kdf, aead,
1313
0
      Span(peer_public_key, peer_public_key_len), Span(info, info_len),
1314
0
      Span(seed, seed_len));
1315
0
}
1316
1317
int EVP_HPKE_CTX_setup_auth_recipient(
1318
    EVP_HPKE_CTX *ctx, const EVP_HPKE_KEY *key, const EVP_HPKE_KDF *kdf,
1319
    const EVP_HPKE_AEAD *aead, const uint8_t *enc, size_t enc_len,
1320
    const uint8_t *info, size_t info_len, const uint8_t *peer_public_key,
1321
0
    size_t peer_public_key_len) {
1322
0
  if (key->kem->auth_decap == nullptr) {
1323
    // Not all HPKE KEMs support AuthDecap.
1324
0
    OPENSSL_PUT_ERROR(EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
1325
0
    return 0;
1326
0
  }
1327
1328
0
  EVP_HPKE_CTX_zero(ctx);
1329
0
  ctx->is_sender = 0;
1330
0
  ctx->kem = key->kem;
1331
0
  ctx->kdf = kdf;
1332
0
  ctx->aead = aead;
1333
0
  const EVP_KEM *kem = key->kem->evp_kem_func();
1334
0
  InplaceVector<uint8_t, MAX_SHARED_SECRET_LEN> shared_secret;
1335
0
  if (!shared_secret.TryResizeForOverwrite(kem->secret_len)) {
1336
0
    OPENSSL_PUT_ERROR(EVP, ERR_R_INTERNAL_ERROR);
1337
0
    return 0;
1338
0
  }
1339
0
  UniquePtr<EVP_PKEY> peer_key(key->kem->key_method->deserialize_public_key(
1340
0
      key->kem->key_method->alg_func(), peer_public_key, peer_public_key_len));
1341
0
  if (peer_key == nullptr) {
1342
0
    return 0;
1343
0
  }
1344
0
  if (!key->kem->auth_decap(kem, Span(shared_secret), Span(enc, enc_len),
1345
0
                            key->pkey, peer_key.get()) ||
1346
0
      !hpke_key_schedule(ctx, HPKE_MODE_AUTH, shared_secret.data(),
1347
0
                         shared_secret.size(), info, info_len)) {
1348
0
    EVP_HPKE_CTX_cleanup(ctx);
1349
0
    return 0;
1350
0
  }
1351
0
  return 1;
1352
0
}
1353
1354
int EVP_HPKE_CTX_open(EVP_HPKE_CTX *ctx, uint8_t *out, size_t *out_len,
1355
                      size_t max_out_len, const uint8_t *in, size_t in_len,
1356
27
                      const uint8_t *ad, size_t ad_len) {
1357
27
  if (ctx->is_sender) {
1358
0
    OPENSSL_PUT_ERROR(EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1359
0
    return 0;
1360
0
  }
1361
27
  if (ctx->seq == UINT64_MAX) {
1362
0
    OPENSSL_PUT_ERROR(EVP, ERR_R_OVERFLOW);
1363
0
    return 0;
1364
0
  }
1365
1366
27
  uint8_t nonce[EVP_AEAD_MAX_NONCE_LENGTH];
1367
27
  const size_t nonce_len = EVP_AEAD_nonce_length(ctx->aead_ctx.aead);
1368
27
  hpke_nonce(ctx, nonce, nonce_len);
1369
1370
27
  if (!EVP_AEAD_CTX_open(&ctx->aead_ctx, out, out_len, max_out_len, nonce,
1371
27
                         nonce_len, in, in_len, ad, ad_len)) {
1372
27
    return 0;
1373
27
  }
1374
0
  ctx->seq++;
1375
0
  return 1;
1376
27
}
1377
1378
int EVP_HPKE_CTX_seal(EVP_HPKE_CTX *ctx, uint8_t *out, size_t *out_len,
1379
                      size_t max_out_len, const uint8_t *in, size_t in_len,
1380
0
                      const uint8_t *ad, size_t ad_len) {
1381
0
  if (!ctx->is_sender) {
1382
0
    OPENSSL_PUT_ERROR(EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1383
0
    return 0;
1384
0
  }
1385
0
  if (ctx->seq == UINT64_MAX) {
1386
0
    OPENSSL_PUT_ERROR(EVP, ERR_R_OVERFLOW);
1387
0
    return 0;
1388
0
  }
1389
1390
0
  uint8_t nonce[EVP_AEAD_MAX_NONCE_LENGTH];
1391
0
  const size_t nonce_len = EVP_AEAD_nonce_length(ctx->aead_ctx.aead);
1392
0
  hpke_nonce(ctx, nonce, nonce_len);
1393
1394
0
  if (!EVP_AEAD_CTX_seal(&ctx->aead_ctx, out, out_len, max_out_len, nonce,
1395
0
                         nonce_len, in, in_len, ad, ad_len)) {
1396
0
    return 0;
1397
0
  }
1398
0
  ctx->seq++;
1399
0
  return 1;
1400
0
}
1401
1402
int EVP_HPKE_CTX_export(const EVP_HPKE_CTX *ctx, uint8_t *out,
1403
                        size_t secret_len, const uint8_t *context,
1404
0
                        size_t context_len) {
1405
0
  auto suite_id = hpke_full_suite_id(ctx);
1406
0
  const EVP_MD *hkdf_md = ctx->kdf->hkdf_md_func();
1407
0
  if (!hpke_labeled_expand(hkdf_md, out, secret_len, ctx->exporter_secret,
1408
0
                           EVP_MD_size(hkdf_md), suite_id.data(),
1409
0
                           suite_id.size(), "sec", context, context_len)) {
1410
0
    return 0;
1411
0
  }
1412
0
  return 1;
1413
0
}
1414
1415
0
size_t EVP_HPKE_CTX_max_overhead(const EVP_HPKE_CTX *ctx) {
1416
0
  assert(ctx->is_sender);
1417
0
  return EVP_AEAD_max_overhead(EVP_AEAD_CTX_aead(&ctx->aead_ctx));
1418
0
}
1419
1420
0
const EVP_HPKE_KEM *EVP_HPKE_CTX_kem(const EVP_HPKE_CTX *ctx) {
1421
0
  return ctx->kem;
1422
0
}
1423
1424
43
const EVP_HPKE_AEAD *EVP_HPKE_CTX_aead(const EVP_HPKE_CTX *ctx) {
1425
43
  return ctx->aead;
1426
43
}
1427
1428
68
const EVP_HPKE_KDF *EVP_HPKE_CTX_kdf(const EVP_HPKE_CTX *ctx) {
1429
68
  return ctx->kdf;
1430
68
}