2013-07-17 14:01:08 +00:00
|
|
|
/*
|
2016-05-17 18:51:04 +00:00
|
|
|
* Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
|
2013-07-17 14:01:08 +00:00
|
|
|
*
|
2016-05-17 18:51:04 +00:00
|
|
|
* Licensed under the OpenSSL license (the "License"). You may not use
|
|
|
|
* this file except in compliance with the License. You can obtain a copy
|
|
|
|
* in the file LICENSE in the source distribution or at
|
|
|
|
* https://www.openssl.org/source/license.html
|
2013-07-17 14:01:08 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <string.h>
|
2015-10-22 14:47:38 +00:00
|
|
|
#include <openssl/ec.h>
|
2013-07-17 14:01:08 +00:00
|
|
|
#include <openssl/evp.h>
|
|
|
|
|
|
|
|
/* Key derivation function from X9.62/SECG */
|
2013-10-15 00:17:40 +00:00
|
|
|
/* Way more than we will ever need */
|
2015-01-22 03:40:55 +00:00
|
|
|
#define ECDH_KDF_MAX (1 << 30)
|
2013-07-17 14:01:08 +00:00
|
|
|
|
2015-01-22 03:40:55 +00:00
|
|
|
int ECDH_KDF_X9_62(unsigned char *out, size_t outlen,
|
|
|
|
const unsigned char *Z, size_t Zlen,
|
|
|
|
const unsigned char *sinfo, size_t sinfolen,
|
|
|
|
const EVP_MD *md)
|
|
|
|
{
|
2015-11-27 13:02:12 +00:00
|
|
|
EVP_MD_CTX *mctx = NULL;
|
2015-01-22 03:40:55 +00:00
|
|
|
int rv = 0;
|
|
|
|
unsigned int i;
|
|
|
|
size_t mdlen;
|
|
|
|
unsigned char ctr[4];
|
|
|
|
if (sinfolen > ECDH_KDF_MAX || outlen > ECDH_KDF_MAX
|
|
|
|
|| Zlen > ECDH_KDF_MAX)
|
|
|
|
return 0;
|
2015-12-01 23:49:35 +00:00
|
|
|
mctx = EVP_MD_CTX_new();
|
2015-11-27 13:02:12 +00:00
|
|
|
if (mctx == NULL)
|
|
|
|
return 0;
|
2015-01-22 03:40:55 +00:00
|
|
|
mdlen = EVP_MD_size(md);
|
|
|
|
for (i = 1;; i++) {
|
|
|
|
unsigned char mtmp[EVP_MAX_MD_SIZE];
|
2015-11-27 13:02:12 +00:00
|
|
|
EVP_DigestInit_ex(mctx, md, NULL);
|
2015-01-22 03:40:55 +00:00
|
|
|
ctr[3] = i & 0xFF;
|
|
|
|
ctr[2] = (i >> 8) & 0xFF;
|
|
|
|
ctr[1] = (i >> 16) & 0xFF;
|
|
|
|
ctr[0] = (i >> 24) & 0xFF;
|
2015-11-27 13:02:12 +00:00
|
|
|
if (!EVP_DigestUpdate(mctx, Z, Zlen))
|
2015-01-22 03:40:55 +00:00
|
|
|
goto err;
|
2015-11-27 13:02:12 +00:00
|
|
|
if (!EVP_DigestUpdate(mctx, ctr, sizeof(ctr)))
|
2015-01-22 03:40:55 +00:00
|
|
|
goto err;
|
2015-11-27 13:02:12 +00:00
|
|
|
if (!EVP_DigestUpdate(mctx, sinfo, sinfolen))
|
2015-01-22 03:40:55 +00:00
|
|
|
goto err;
|
|
|
|
if (outlen >= mdlen) {
|
2015-11-27 13:02:12 +00:00
|
|
|
if (!EVP_DigestFinal(mctx, out, NULL))
|
2015-01-22 03:40:55 +00:00
|
|
|
goto err;
|
|
|
|
outlen -= mdlen;
|
|
|
|
if (outlen == 0)
|
|
|
|
break;
|
|
|
|
out += mdlen;
|
|
|
|
} else {
|
2015-11-27 13:02:12 +00:00
|
|
|
if (!EVP_DigestFinal(mctx, mtmp, NULL))
|
2015-01-22 03:40:55 +00:00
|
|
|
goto err;
|
|
|
|
memcpy(out, mtmp, outlen);
|
|
|
|
OPENSSL_cleanse(mtmp, mdlen);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
rv = 1;
|
|
|
|
err:
|
2015-12-01 23:49:35 +00:00
|
|
|
EVP_MD_CTX_free(mctx);
|
2015-01-22 03:40:55 +00:00
|
|
|
return rv;
|
|
|
|
}
|