2 * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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
11 #include <openssl/ec.h>
12 #include <openssl/evp.h>
15 /* Key derivation function from X9.63/SECG */
16 /* Way more than we will ever need */
17 #define ECDH_KDF_MAX (1 << 30)
19 int ecdh_KDF_X9_63(unsigned char *out, size_t outlen,
20 const unsigned char *Z, size_t Zlen,
21 const unsigned char *sinfo, size_t sinfolen,
24 EVP_MD_CTX *mctx = NULL;
29 if (sinfolen > ECDH_KDF_MAX || outlen > ECDH_KDF_MAX
30 || Zlen > ECDH_KDF_MAX)
32 mctx = EVP_MD_CTX_new();
35 mdlen = EVP_MD_size(md);
37 unsigned char mtmp[EVP_MAX_MD_SIZE];
38 if (!EVP_DigestInit_ex(mctx, md, NULL))
41 ctr[2] = (i >> 8) & 0xFF;
42 ctr[1] = (i >> 16) & 0xFF;
43 ctr[0] = (i >> 24) & 0xFF;
44 if (!EVP_DigestUpdate(mctx, Z, Zlen))
46 if (!EVP_DigestUpdate(mctx, ctr, sizeof(ctr)))
48 if (!EVP_DigestUpdate(mctx, sinfo, sinfolen))
50 if (outlen >= mdlen) {
51 if (!EVP_DigestFinal(mctx, out, NULL))
58 if (!EVP_DigestFinal(mctx, mtmp, NULL))
60 memcpy(out, mtmp, outlen);
61 OPENSSL_cleanse(mtmp, mdlen);
67 EVP_MD_CTX_free(mctx);
72 * The old name for ecdh_KDF_X9_63
73 * Retained for ABI compatibility
75 int ECDH_KDF_X9_62(unsigned char *out, size_t outlen,
76 const unsigned char *Z, size_t Zlen,
77 const unsigned char *sinfo, size_t sinfolen,
80 return ecdh_KDF_X9_63(out, outlen, Z, Zlen, sinfo, sinfolen, md);