Coverage Report

Created: 2025-10-28 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/providers/implementations/kem/ecx_kem.c
Line
Count
Source
1
/*
2
 * Copyright 2022-2025 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
/*
11
 * The following implementation is part of RFC 9180 related to DHKEM using
12
 * ECX keys (i.e. X25519 and X448)
13
 * References to Sections in the comments below refer to RFC 9180.
14
 */
15
16
#include "internal/deprecated.h"
17
18
#include <string.h>
19
#include <openssl/crypto.h>
20
#include <openssl/evp.h>
21
#include <openssl/core_dispatch.h>
22
#include <openssl/core_names.h>
23
#include <openssl/params.h>
24
#include <openssl/kdf.h>
25
#include <openssl/err.h>
26
#include <openssl/sha.h>
27
#include <openssl/rand.h>
28
#include <openssl/proverr.h>
29
#include "internal/cryptlib.h"
30
#include "prov/provider_ctx.h"
31
#include "prov/implementations.h"
32
#include "prov/securitycheck.h"
33
#include "prov/providercommon.h"
34
#include "prov/ecx.h"
35
#include "crypto/ecx.h"
36
#include <openssl/hpke.h>
37
#include "internal/hpke_util.h"
38
#include "prov/eckem.h"
39
#include "providers/implementations/kem/ecx_kem.inc"
40
41
#define MAX_ECX_KEYLEN X448_KEYLEN
42
43
/* KEM identifiers from Section 7.1 "Table 2 KEM IDs" */
44
#define KEMID_X25519_HKDF_SHA256 0x20
45
#define KEMID_X448_HKDF_SHA512   0x21
46
47
/* ASCII: "KEM", in hex for EBCDIC compatibility */
48
static const char LABEL_KEM[] = "\x4b\x45\x4d";
49
50
typedef struct {
51
    ECX_KEY *recipient_key;
52
    ECX_KEY *sender_authkey;
53
    OSSL_LIB_CTX *libctx;
54
    char *propq;
55
    unsigned int mode;
56
    unsigned int op;
57
    unsigned char *ikm;
58
    size_t ikmlen;
59
    const char *kdfname;
60
    const OSSL_HPKE_KEM_INFO *info;
61
} PROV_ECX_CTX;
62
63
static OSSL_FUNC_kem_newctx_fn ecxkem_newctx;
64
static OSSL_FUNC_kem_encapsulate_init_fn ecxkem_encapsulate_init;
65
static OSSL_FUNC_kem_encapsulate_fn ecxkem_encapsulate;
66
static OSSL_FUNC_kem_decapsulate_init_fn ecxkem_decapsulate_init;
67
static OSSL_FUNC_kem_decapsulate_fn ecxkem_decapsulate;
68
static OSSL_FUNC_kem_freectx_fn ecxkem_freectx;
69
static OSSL_FUNC_kem_set_ctx_params_fn ecxkem_set_ctx_params;
70
static OSSL_FUNC_kem_auth_encapsulate_init_fn ecxkem_auth_encapsulate_init;
71
static OSSL_FUNC_kem_auth_decapsulate_init_fn ecxkem_auth_decapsulate_init;
72
73
/*
74
 * Set KEM values as specified in Section 7.1 "Table 2 KEM IDs"
75
 * There is only one set of values for X25519 and X448.
76
 * Additional values could be set via set_params if required.
77
 */
78
static const OSSL_HPKE_KEM_INFO *get_kem_info(ECX_KEY *ecx)
79
0
{
80
0
    const char *name = NULL;
81
82
0
    if (ecx->type == ECX_KEY_TYPE_X25519)
83
0
        name = SN_X25519;
84
0
    else
85
0
        name = SN_X448;
86
0
    return ossl_HPKE_KEM_INFO_find_curve(name);
87
0
}
88
89
/*
90
 * Set the recipient key, and free any existing key.
91
 * ecx can be NULL. The ecx key may have only a private or public component.
92
 */
93
static int recipient_key_set(PROV_ECX_CTX *ctx, ECX_KEY *ecx)
94
0
{
95
0
    ossl_ecx_key_free(ctx->recipient_key);
96
0
    ctx->recipient_key = NULL;
97
0
    if (ecx != NULL) {
98
0
        ctx->info = get_kem_info(ecx);
99
0
        if (ctx->info == NULL)
100
0
            return -2;
101
0
        ctx->kdfname = "HKDF";
102
0
        if (!ossl_ecx_key_up_ref(ecx))
103
0
            return 0;
104
0
        ctx->recipient_key = ecx;
105
0
    }
106
0
    return 1;
107
0
}
108
109
/*
110
 * Set the senders auth key, and free any existing auth key.
111
 * ecx can be NULL.
112
 */
113
static int sender_authkey_set(PROV_ECX_CTX *ctx, ECX_KEY *ecx)
114
0
{
115
0
    ossl_ecx_key_free(ctx->sender_authkey);
116
0
    ctx->sender_authkey = NULL;
117
118
0
    if (ecx != NULL) {
119
0
        if (!ossl_ecx_key_up_ref(ecx))
120
0
            return 0;
121
0
        ctx->sender_authkey = ecx;
122
0
    }
123
0
    return 1;
124
0
}
125
126
/*
127
 * Serialize a public key from byte array's for the encoded public keys.
128
 * ctx is used to access the key type.
129
 * Returns: The created ECX_KEY or NULL on error.
130
 */
131
static ECX_KEY *ecxkey_pubfromdata(PROV_ECX_CTX *ctx,
132
                                   const unsigned char *pubbuf, size_t pubbuflen)
133
0
{
134
0
    ECX_KEY *ecx = NULL;
135
0
    OSSL_PARAM pub;
136
137
0
    pub = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
138
0
                                            (char *)pubbuf, pubbuflen);
139
140
0
    ecx = ossl_ecx_key_new(ctx->libctx, ctx->recipient_key->type, 1, ctx->propq);
141
0
    if (ecx == NULL)
142
0
        return NULL;
143
0
    if (ossl_ecx_key_fromdata(ecx, &pub, NULL, 0) <= 0) {
144
0
        ossl_ecx_key_free(ecx);
145
0
        ecx = NULL;
146
0
    }
147
0
    return ecx;
148
0
}
149
150
static unsigned char *ecx_pubkey(ECX_KEY *ecx)
151
0
{
152
0
    if (ecx == NULL || !ecx->haspubkey) {
153
0
        ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
154
0
        return 0;
155
0
    }
156
0
    return ecx->pubkey;
157
0
}
158
159
static void *ecxkem_newctx(void *provctx)
160
0
{
161
0
    PROV_ECX_CTX *ctx =  OPENSSL_zalloc(sizeof(PROV_ECX_CTX));
162
163
0
    if (ctx == NULL)
164
0
        return NULL;
165
0
    ctx->libctx = PROV_LIBCTX_OF(provctx);
166
0
    ctx->mode = KEM_MODE_DHKEM;
167
168
0
    return ctx;
169
0
}
170
171
static void ecxkem_freectx(void *vectx)
172
0
{
173
0
    PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vectx;
174
175
0
    OPENSSL_clear_free(ctx->ikm, ctx->ikmlen);
176
0
    recipient_key_set(ctx, NULL);
177
0
    sender_authkey_set(ctx, NULL);
178
0
    OPENSSL_free(ctx);
179
0
}
180
181
static int ecx_match_params(const ECX_KEY *key1, const ECX_KEY *key2)
182
0
{
183
0
    return (key1->type == key2->type && key1->keylen == key2->keylen);
184
0
}
185
186
static int ecx_key_check(const ECX_KEY *ecx, int requires_privatekey)
187
0
{
188
0
    if (ecx->privkey == NULL)
189
0
        return (requires_privatekey == 0);
190
0
    return 1;
191
0
}
192
193
static int ecxkem_init(void *vecxctx, int operation, void *vecx, void *vauth,
194
                       ossl_unused const OSSL_PARAM params[])
195
0
{
196
0
    int rv;
197
0
    PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vecxctx;
198
0
    ECX_KEY *ecx = vecx;
199
0
    ECX_KEY *auth = vauth;
200
201
0
    if (!ossl_prov_is_running())
202
0
        return 0;
203
204
0
    if (!ecx_key_check(ecx, operation == EVP_PKEY_OP_DECAPSULATE))
205
0
        return 0;
206
0
    rv = recipient_key_set(ctx, ecx);
207
0
    if (rv <= 0)
208
0
        return rv;
209
210
0
    if (auth != NULL) {
211
0
        if (!ecx_match_params(auth, ctx->recipient_key)
212
0
                || !ecx_key_check(auth, operation == EVP_PKEY_OP_ENCAPSULATE)
213
0
                || !sender_authkey_set(ctx, auth))
214
0
            return 0;
215
0
    }
216
217
0
    ctx->op = operation;
218
0
    return ecxkem_set_ctx_params(vecxctx, params);
219
0
}
220
221
static int ecxkem_encapsulate_init(void *vecxctx, void *vecx,
222
                                   const OSSL_PARAM params[])
223
0
{
224
0
    return ecxkem_init(vecxctx, EVP_PKEY_OP_ENCAPSULATE, vecx, NULL, params);
225
0
}
226
227
static int ecxkem_decapsulate_init(void *vecxctx, void *vecx,
228
                                   const OSSL_PARAM params[])
229
0
{
230
0
    return ecxkem_init(vecxctx, EVP_PKEY_OP_DECAPSULATE, vecx, NULL, params);
231
0
}
232
233
static int ecxkem_auth_encapsulate_init(void *vctx, void *vecx, void *vauthpriv,
234
                                        const OSSL_PARAM params[])
235
0
{
236
0
    return ecxkem_init(vctx, EVP_PKEY_OP_ENCAPSULATE, vecx, vauthpriv, params);
237
0
}
238
239
static int ecxkem_auth_decapsulate_init(void *vctx, void *vecx, void *vauthpub,
240
                                        const OSSL_PARAM params[])
241
0
{
242
0
    return ecxkem_init(vctx, EVP_PKEY_OP_DECAPSULATE, vecx, vauthpub, params);
243
0
}
244
245
static int ecxkem_set_ctx_params(void *vctx, const OSSL_PARAM params[])
246
0
{
247
0
    PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vctx;
248
0
    struct ecxkem_set_ctx_params_st p;
249
0
    int mode;
250
251
0
    if (ctx == NULL || !ecxkem_set_ctx_params_decoder(params, &p))
252
0
        return 0;
253
254
0
    if (p.ikme != NULL) {
255
0
        void *tmp = NULL;
256
0
        size_t tmplen = 0;
257
258
0
        if (p.ikme->data != NULL && p.ikme->data_size != 0) {
259
0
            if (!OSSL_PARAM_get_octet_string(p.ikme, &tmp, 0, &tmplen))
260
0
                return 0;
261
0
        }
262
0
        OPENSSL_clear_free(ctx->ikm, ctx->ikmlen);
263
0
        ctx->ikm = tmp;
264
0
        ctx->ikmlen = tmplen;
265
0
    }
266
267
0
    if (p.op != NULL) {
268
0
        if (p.op->data_type != OSSL_PARAM_UTF8_STRING)
269
0
            return 0;
270
0
        mode = ossl_eckem_modename2id(p.op->data);
271
0
        if (mode == KEM_MODE_UNDEFINED)
272
0
            return 0;
273
0
        ctx->mode = mode;
274
0
    }
275
0
    return 1;
276
0
}
277
278
static const OSSL_PARAM *ecxkem_settable_ctx_params(ossl_unused void *vctx,
279
                                                   ossl_unused void *provctx)
280
0
{
281
0
    return ecxkem_set_ctx_params_list;
282
0
}
283
284
/*
285
 * See Section 4.1 DH-Based KEM (DHKEM) ExtractAndExpand
286
 */
287
static int dhkem_extract_and_expand(EVP_KDF_CTX *kctx,
288
                                    unsigned char *okm, size_t okmlen,
289
                                    uint16_t kemid,
290
                                    const unsigned char *dhkm, size_t dhkmlen,
291
                                    const unsigned char *kemctx,
292
                                    size_t kemctxlen)
293
0
{
294
0
    uint8_t suiteid[2];
295
0
    uint8_t prk[EVP_MAX_MD_SIZE];
296
0
    size_t prklen = okmlen; /* Nh */
297
0
    int ret;
298
299
0
    if (prklen > sizeof(prk))
300
0
        return 0;
301
302
0
    suiteid[0] = (kemid >> 8) &0xff;
303
0
    suiteid[1] = kemid & 0xff;
304
305
0
    ret = ossl_hpke_labeled_extract(kctx, prk, prklen,
306
0
                                    NULL, 0, LABEL_KEM, suiteid, sizeof(suiteid),
307
0
                                    OSSL_DHKEM_LABEL_EAE_PRK, dhkm, dhkmlen)
308
0
          && ossl_hpke_labeled_expand(kctx, okm, okmlen, prk, prklen,
309
0
                                      LABEL_KEM, suiteid, sizeof(suiteid),
310
0
                                      OSSL_DHKEM_LABEL_SHARED_SECRET,
311
0
                                      kemctx, kemctxlen);
312
0
    OPENSSL_cleanse(prk, prklen);
313
0
    return ret;
314
0
}
315
316
/*
317
 * See Section 7.1.3 DeriveKeyPair.
318
 *
319
 * This function is used by ecx keygen.
320
 * (For this reason it does not use any of the state stored in PROV_ECX_CTX).
321
 *
322
 * Params:
323
 *     ecx An initialized ecx key.
324
 *     privout The buffer to store the generated private key into (it is assumed
325
 *             this is of length ecx->keylen).
326
 *     ikm buffer containing the input key material (seed). This must be non NULL.
327
 *     ikmlen size of the ikm buffer in bytes
328
 * Returns:
329
 *     1 if successful or 0 otherwise.
330
 */
331
int ossl_ecx_dhkem_derive_private(ECX_KEY *ecx, unsigned char *privout,
332
                                  const unsigned char *ikm, size_t ikmlen)
333
0
{
334
0
    int ret = 0;
335
0
    EVP_KDF_CTX *kdfctx = NULL;
336
0
    unsigned char prk[EVP_MAX_MD_SIZE];
337
0
    uint8_t suiteid[2];
338
0
    const OSSL_HPKE_KEM_INFO *info = get_kem_info(ecx);
339
340
    /* ikmlen should have a length of at least Nsk */
341
0
    if (ikmlen < info->Nsk) {
342
0
        ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_INPUT_LENGTH,
343
0
                       "ikm length is :%zu, should be at least %zu",
344
0
                       ikmlen, info->Nsk);
345
0
        goto err;
346
0
    }
347
348
0
    kdfctx = ossl_kdf_ctx_create("HKDF", info->mdname, ecx->libctx, ecx->propq);
349
0
    if (kdfctx == NULL)
350
0
        return 0;
351
352
0
    suiteid[0] = info->kem_id / 256;
353
0
    suiteid[1] = info->kem_id % 256;
354
355
0
    if (!ossl_hpke_labeled_extract(kdfctx, prk, info->Nsecret,
356
0
                                   NULL, 0, LABEL_KEM, suiteid, sizeof(suiteid),
357
0
                                   OSSL_DHKEM_LABEL_DKP_PRK, ikm, ikmlen))
358
0
        goto err;
359
360
0
    if (!ossl_hpke_labeled_expand(kdfctx, privout, info->Nsk, prk, info->Nsecret,
361
0
                                  LABEL_KEM, suiteid, sizeof(suiteid),
362
0
                                  OSSL_DHKEM_LABEL_SK, NULL, 0))
363
0
        goto err;
364
0
    ret = 1;
365
0
err:
366
0
    OPENSSL_cleanse(prk, sizeof(prk));
367
0
    EVP_KDF_CTX_free(kdfctx);
368
0
    return ret;
369
0
}
370
371
/*
372
 * Do a keygen operation without having to use EVP_PKEY.
373
 * Params:
374
 *     ctx Context object
375
 *     ikm The seed material - if this is NULL, then a random seed is used.
376
 * Returns:
377
 *     The generated ECX key, or NULL on failure.
378
 */
379
static ECX_KEY *derivekey(PROV_ECX_CTX *ctx,
380
                          const unsigned char *ikm, size_t ikmlen)
381
0
{
382
0
    int ok = 0;
383
0
    ECX_KEY *key;
384
0
    unsigned char *privkey;
385
0
    unsigned char *seed = (unsigned char *)ikm;
386
0
    size_t seedlen = ikmlen;
387
0
    unsigned char tmpbuf[OSSL_HPKE_MAX_PRIVATE];
388
0
    const OSSL_HPKE_KEM_INFO *info = ctx->info;
389
390
0
    key = ossl_ecx_key_new(ctx->libctx, ctx->recipient_key->type, 0, ctx->propq);
391
0
    if (key == NULL)
392
0
        return NULL;
393
0
    privkey = ossl_ecx_key_allocate_privkey(key);
394
0
    if (privkey == NULL)
395
0
        goto err;
396
397
    /* Generate a random seed if there is no input ikm */
398
0
    if (seed == NULL || seedlen == 0) {
399
0
        if (info->Nsk > sizeof(tmpbuf))
400
0
            goto err;
401
0
        if (RAND_priv_bytes_ex(ctx->libctx, tmpbuf, info->Nsk, 0) <= 0)
402
0
            goto err;
403
0
        seed = tmpbuf;
404
0
        seedlen = info->Nsk;
405
0
    }
406
0
    if (!ossl_ecx_dhkem_derive_private(key, privkey, seed, seedlen))
407
0
        goto err;
408
0
    if (!ossl_ecx_public_from_private(key))
409
0
        goto err;
410
0
    key->haspubkey = 1;
411
0
    ok = 1;
412
0
err:
413
0
    if (!ok) {
414
0
        ossl_ecx_key_free(key);
415
0
        key = NULL;
416
0
    }
417
0
    if (seed != ikm)
418
0
        OPENSSL_cleanse(seed, seedlen);
419
0
    return key;
420
0
}
421
422
/*
423
 * Do an ecxdh key exchange.
424
 * dhkm = DH(sender, peer)
425
 *
426
 * NOTE: Instead of using EVP_PKEY_derive() API's, we use ECX_KEY operations
427
 *       to avoid messy conversions back to EVP_PKEY.
428
 *
429
 * Returns the size of the secret if successful, or 0 otherwise,
430
 */
431
static int generate_ecxdhkm(const ECX_KEY *sender, const ECX_KEY *peer,
432
                           unsigned char *out,  size_t maxout,
433
                           unsigned int secretsz)
434
0
{
435
0
    size_t len = 0;
436
437
    /* NOTE: ossl_ecx_compute_key checks for shared secret being all zeros */
438
0
    return ossl_ecx_compute_key((ECX_KEY *)peer, (ECX_KEY *)sender,
439
0
                                 sender->keylen, out, &len, maxout);
440
0
}
441
442
/*
443
 * Derive a secret using ECXDH (code is shared by the encap and decap)
444
 *
445
 * dhkm = Concat(ecxdh(privkey1, peerkey1), ecdh(privkey2, peerkey2)
446
 * kemctx = Concat(sender_pub, recipient_pub, ctx->sender_authkey)
447
 * secret = dhkem_extract_and_expand(kemid, dhkm, kemctx);
448
 *
449
 * Params:
450
 *     ctx Object that contains algorithm state and constants.
451
 *     secret The returned secret (with a length ctx->alg->secretlen bytes).
452
 *     privkey1 A private key used for ECXDH key derivation.
453
 *     peerkey1 A public key used for ECXDH key derivation with privkey1
454
 *     privkey2 A optional private key used for a second ECXDH key derivation.
455
 *              It can be NULL.
456
 *     peerkey2 A optional public key used for a second ECXDH key derivation
457
 *              with privkey2,. It can be NULL.
458
 *     sender_pub The senders public key in encoded form.
459
 *     recipient_pub The recipients public key in encoded form.
460
 * Notes:
461
 *     The second ecdh() is only used for the HPKE auth modes when both privkey2
462
 *     and peerkey2 are non NULL (i.e. ctx->sender_authkey is not NULL).
463
 */
464
static int derive_secret(PROV_ECX_CTX *ctx, unsigned char *secret,
465
                         const ECX_KEY *privkey1, const ECX_KEY *peerkey1,
466
                         const ECX_KEY *privkey2, const ECX_KEY *peerkey2,
467
                         const unsigned char *sender_pub,
468
                         const unsigned char *recipient_pub)
469
0
{
470
0
    int ret = 0;
471
0
    EVP_KDF_CTX *kdfctx = NULL;
472
0
    unsigned char *sender_authpub = NULL;
473
0
    unsigned char dhkm[MAX_ECX_KEYLEN * 2];
474
0
    unsigned char kemctx[MAX_ECX_KEYLEN * 3];
475
0
    size_t kemctxlen = 0, dhkmlen = 0;
476
0
    const OSSL_HPKE_KEM_INFO *info = ctx->info;
477
0
    int auth = ctx->sender_authkey != NULL;
478
0
    size_t encodedkeylen = info->Npk;
479
480
0
    if (!generate_ecxdhkm(privkey1, peerkey1, dhkm, sizeof(dhkm),
481
0
                          (unsigned int)encodedkeylen))
482
0
        goto err;
483
0
    dhkmlen = encodedkeylen;
484
485
    /* Concat the optional second ECXDH (used for Auth) */
486
0
    if (auth) {
487
0
        if (!generate_ecxdhkm(privkey2, peerkey2,
488
0
                              dhkm + dhkmlen, sizeof(dhkm) - dhkmlen,
489
0
                              (unsigned int)encodedkeylen))
490
0
            goto err;
491
        /* Get the public key of the auth sender in encoded form */
492
0
        sender_authpub = ecx_pubkey(ctx->sender_authkey);
493
0
        if (sender_authpub == NULL)
494
0
            goto err;
495
0
        dhkmlen += encodedkeylen;
496
0
    }
497
0
    kemctxlen = encodedkeylen + dhkmlen;
498
0
    if (kemctxlen > sizeof(kemctx))
499
0
        goto err;
500
501
    /* kemctx is the concat of both sides encoded public key */
502
0
    memcpy(kemctx, sender_pub, encodedkeylen);
503
0
    memcpy(kemctx + encodedkeylen, recipient_pub, encodedkeylen);
504
0
    if (auth)
505
0
        memcpy(kemctx + 2 * encodedkeylen, sender_authpub, encodedkeylen);
506
0
    kdfctx = ossl_kdf_ctx_create(ctx->kdfname, info->mdname,
507
0
                                 ctx->libctx, ctx->propq);
508
0
    if (kdfctx == NULL)
509
0
        goto err;
510
0
    if (!dhkem_extract_and_expand(kdfctx, secret, info->Nsecret,
511
0
                                  info->kem_id, dhkm, dhkmlen,
512
0
                                  kemctx, kemctxlen))
513
0
        goto err;
514
0
    ret = 1;
515
0
err:
516
0
    OPENSSL_cleanse(dhkm, dhkmlen);
517
0
    EVP_KDF_CTX_free(kdfctx);
518
0
    return ret;
519
0
}
520
521
/*
522
 * Do a DHKEM encapsulate operation.
523
 *
524
 * See Section 4.1 Encap() and AuthEncap()
525
 *
526
 * Params:
527
 *     ctx A context object holding the recipients public key and the
528
 *         optional senders auth private key.
529
 *     enc A buffer to return the senders ephemeral public key.
530
 *         Setting this to NULL allows the enclen and secretlen to return
531
 *         values, without calculating the secret.
532
 *     enclen Passes in the max size of the enc buffer and returns the
533
 *            encoded public key length.
534
 *     secret A buffer to return the calculated shared secret.
535
 *     secretlen Passes in the max size of the secret buffer and returns the
536
 *               secret length.
537
 * Returns: 1 on success or 0 otherwise.
538
 */
539
static int dhkem_encap(PROV_ECX_CTX *ctx,
540
                       unsigned char *enc, size_t *enclen,
541
                       unsigned char *secret, size_t *secretlen)
542
0
{
543
0
    int ret = 0;
544
0
    ECX_KEY *sender_ephemkey = NULL;
545
0
    unsigned char *sender_ephempub, *recipient_pub;
546
0
    const OSSL_HPKE_KEM_INFO *info = ctx->info;
547
548
0
    if (enc == NULL) {
549
0
        if (enclen == NULL && secretlen == NULL)
550
0
            return 0;
551
0
        if (enclen != NULL)
552
0
            *enclen = info->Nenc;
553
0
        if (secretlen != NULL)
554
0
            *secretlen = info->Nsecret;
555
0
       return 1;
556
0
    }
557
558
0
    if (*secretlen < info->Nsecret) {
559
0
        ERR_raise_data(ERR_LIB_PROV, PROV_R_BAD_LENGTH, "*secretlen too small");
560
0
        return 0;
561
0
    }
562
0
    if (*enclen < info->Nenc) {
563
0
        ERR_raise_data(ERR_LIB_PROV, PROV_R_BAD_LENGTH, "*enclen too small");
564
0
        return 0;
565
0
    }
566
567
    /* Create an ephemeral key */
568
0
    sender_ephemkey = derivekey(ctx, ctx->ikm, ctx->ikmlen);
569
570
0
    sender_ephempub = ecx_pubkey(sender_ephemkey);
571
0
    recipient_pub = ecx_pubkey(ctx->recipient_key);
572
0
    if (sender_ephempub == NULL || recipient_pub == NULL)
573
0
        goto err;
574
575
0
    if (!derive_secret(ctx, secret,
576
0
                       sender_ephemkey, ctx->recipient_key,
577
0
                       ctx->sender_authkey, ctx->recipient_key,
578
0
                       sender_ephempub, recipient_pub))
579
0
        goto err;
580
581
    /* Return the public part of the ephemeral key */
582
0
    memcpy(enc, sender_ephempub, info->Nenc);
583
0
    *enclen = info->Nenc;
584
0
    *secretlen = info->Nsecret;
585
0
    ret = 1;
586
0
err:
587
0
    ossl_ecx_key_free(sender_ephemkey);
588
0
    return ret;
589
0
}
590
591
/*
592
 * Do a DHKEM decapsulate operation.
593
 * See Section 4.1 Decap() and Auth Decap()
594
 *
595
 * Params:
596
 *     ctx A context object holding the recipients private key and the
597
 *         optional senders auth public key.
598
 *     secret A buffer to return the calculated shared secret. Setting this to
599
 *            NULL can be used to return the secretlen.
600
 *     secretlen Passes in the max size of the secret buffer and returns the
601
 *               secret length.
602
 *     enc A buffer containing the senders ephemeral public key that was returned
603
 *         from dhkem_encap().
604
 *     enclen The length in bytes of enc.
605
 * Returns: 1 If the shared secret is returned or 0 on error.
606
 */
607
static int dhkem_decap(PROV_ECX_CTX *ctx,
608
                       unsigned char *secret, size_t *secretlen,
609
                       const unsigned char *enc, size_t enclen)
610
0
{
611
0
    int ret = 0;
612
0
    ECX_KEY *recipient_privkey = ctx->recipient_key;
613
0
    ECX_KEY *sender_ephempubkey = NULL;
614
0
    const OSSL_HPKE_KEM_INFO *info = ctx->info;
615
0
    unsigned char *recipient_pub;
616
617
0
    if (secret == NULL) {
618
0
        *secretlen = info->Nsecret;
619
0
        return 1;
620
0
    }
621
0
    if (*secretlen < info->Nsecret) {
622
0
        ERR_raise_data(ERR_LIB_PROV, PROV_R_BAD_LENGTH, "*secretlen too small");
623
0
        return 0;
624
0
    }
625
0
    if (enclen != info->Nenc) {
626
0
        ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY, "Invalid enc public key");
627
0
        return 0;
628
0
    }
629
630
    /* Get the public part of the ephemeral key created by encap */
631
0
    sender_ephempubkey = ecxkey_pubfromdata(ctx, enc, enclen);
632
0
    if (sender_ephempubkey == NULL)
633
0
        goto err;
634
635
0
    recipient_pub = ecx_pubkey(recipient_privkey);
636
0
    if (recipient_pub == NULL)
637
0
        goto err;
638
639
0
    if (!derive_secret(ctx, secret,
640
0
                       ctx->recipient_key, sender_ephempubkey,
641
0
                       ctx->recipient_key, ctx->sender_authkey,
642
0
                       enc, recipient_pub))
643
0
        goto err;
644
645
0
    *secretlen = info->Nsecret;
646
0
    ret = 1;
647
0
err:
648
0
    ossl_ecx_key_free(sender_ephempubkey);
649
0
    return ret;
650
0
}
651
652
static int ecxkem_encapsulate(void *vctx, unsigned char *out, size_t *outlen,
653
                              unsigned char *secret, size_t *secretlen)
654
0
{
655
0
    PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vctx;
656
657
0
    switch (ctx->mode) {
658
0
        case KEM_MODE_DHKEM:
659
0
            return dhkem_encap(ctx, out, outlen, secret, secretlen);
660
0
        default:
661
0
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
662
0
            return -2;
663
0
    }
664
0
}
665
666
static int ecxkem_decapsulate(void *vctx, unsigned char *out, size_t *outlen,
667
                              const unsigned char *in, size_t inlen)
668
0
{
669
0
    PROV_ECX_CTX *ctx = (PROV_ECX_CTX *)vctx;
670
671
0
    switch (ctx->mode) {
672
0
        case KEM_MODE_DHKEM:
673
0
            return dhkem_decap(vctx, out, outlen, in, inlen);
674
0
        default:
675
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_MODE);
676
0
            return -2;
677
0
    }
678
0
}
679
680
const OSSL_DISPATCH ossl_ecx_asym_kem_functions[] = {
681
    { OSSL_FUNC_KEM_NEWCTX, (void (*)(void))ecxkem_newctx },
682
    { OSSL_FUNC_KEM_ENCAPSULATE_INIT,
683
      (void (*)(void))ecxkem_encapsulate_init },
684
    { OSSL_FUNC_KEM_ENCAPSULATE, (void (*)(void))ecxkem_encapsulate },
685
    { OSSL_FUNC_KEM_DECAPSULATE_INIT,
686
      (void (*)(void))ecxkem_decapsulate_init },
687
    { OSSL_FUNC_KEM_DECAPSULATE, (void (*)(void))ecxkem_decapsulate },
688
    { OSSL_FUNC_KEM_FREECTX, (void (*)(void))ecxkem_freectx },
689
    { OSSL_FUNC_KEM_SET_CTX_PARAMS,
690
      (void (*)(void))ecxkem_set_ctx_params },
691
    { OSSL_FUNC_KEM_SETTABLE_CTX_PARAMS,
692
      (void (*)(void))ecxkem_settable_ctx_params },
693
    { OSSL_FUNC_KEM_AUTH_ENCAPSULATE_INIT,
694
      (void (*)(void))ecxkem_auth_encapsulate_init },
695
    { OSSL_FUNC_KEM_AUTH_DECAPSULATE_INIT,
696
      (void (*)(void))ecxkem_auth_decapsulate_init },
697
    OSSL_DISPATCH_END
698
};