1 /*
2 * Copyright 2013-2022 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 * DH low level APIs are deprecated for public use, but still ok for
12 * internal use.
13 */
14 #include "internal/deprecated.h"
15
16 #include "internal/e_os.h"
17 #include <string.h>
18 #include <openssl/core_names.h>
19 #include <openssl/dh.h>
20 #include <openssl/evp.h>
21 #include <openssl/asn1.h>
22 #include <openssl/kdf.h>
23 #include "internal/provider.h"
24 #include "crypto/dh.h"
25
26 /* Key derivation function from X9.63/SECG */
ossl_dh_kdf_X9_42_asn1(unsigned char * out,size_t outlen,const unsigned char * Z,size_t Zlen,const char * cek_alg,const unsigned char * ukm,size_t ukmlen,const EVP_MD * md,OSSL_LIB_CTX * libctx,const char * propq)27 int ossl_dh_kdf_X9_42_asn1(unsigned char *out, size_t outlen,
28 const unsigned char *Z, size_t Zlen,
29 const char *cek_alg,
30 const unsigned char *ukm, size_t ukmlen,
31 const EVP_MD *md,
32 OSSL_LIB_CTX *libctx, const char *propq)
33 {
34 int ret = 0;
35 EVP_KDF_CTX *kctx = NULL;
36 EVP_KDF *kdf = NULL;
37 OSSL_PARAM params[5], *p = params;
38 const char *mdname = EVP_MD_get0_name(md);
39
40 kdf = EVP_KDF_fetch(libctx, OSSL_KDF_NAME_X942KDF_ASN1, propq);
41 if (kdf == NULL)
42 return 0;
43 kctx = EVP_KDF_CTX_new(kdf);
44 if (kctx == NULL)
45 goto err;
46
47 *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
48 (char *)mdname, 0);
49 *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
50 (unsigned char *)Z, Zlen);
51 if (ukm != NULL)
52 *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_UKM,
53 (unsigned char *)ukm, ukmlen);
54 *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_CEK_ALG,
55 (char *)cek_alg, 0);
56 *p = OSSL_PARAM_construct_end();
57 ret = EVP_KDF_derive(kctx, out, outlen, params) > 0;
58 err:
59 EVP_KDF_CTX_free(kctx);
60 EVP_KDF_free(kdf);
61 return ret;
62 }
63
64 #if !defined(FIPS_MODULE)
DH_KDF_X9_42(unsigned char * out,size_t outlen,const unsigned char * Z,size_t Zlen,ASN1_OBJECT * key_oid,const unsigned char * ukm,size_t ukmlen,const EVP_MD * md)65 int DH_KDF_X9_42(unsigned char *out, size_t outlen,
66 const unsigned char *Z, size_t Zlen,
67 ASN1_OBJECT *key_oid,
68 const unsigned char *ukm, size_t ukmlen, const EVP_MD *md)
69 {
70 char key_alg[OSSL_MAX_NAME_SIZE];
71 const OSSL_PROVIDER *prov = EVP_MD_get0_provider(md);
72 OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov);
73
74 if (OBJ_obj2txt(key_alg, sizeof(key_alg), key_oid, 0) <= 0)
75 return 0;
76
77 return ossl_dh_kdf_X9_42_asn1(out, outlen, Z, Zlen, key_alg,
78 ukm, ukmlen, md, libctx, NULL);
79 }
80 #endif /* !defined(FIPS_MODULE) */
81